Public
Edited
Oct 7, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
combined = addVectors(subtractVectors(text1_embed, text2_embed), text3_embed)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
transformers = import("https://cdn.jsdelivr.net/npm/@xenova/transformers")
Insert cell
tokenizer = await transformers.AutoTokenizer.from_pretrained(
"Xenova/clip-vit-base-patch16"
)
Insert cell
text_model = await transformers.CLIPTextModelWithProjection.from_pretrained(
"Xenova/clip-vit-base-patch16"
)
Insert cell
function subtractVectors(a, b) {
if (a.length !== b.length) {
throw new Error("Both vectors must have the same length");
}
return a.map((element, index) => element - b[index]);
}
Insert cell
function addVectors(a, b) {
if (a.length !== b.length) {
throw new Error("Both vectors must have the same length");
}
return a.map((element, index) => element + b[index]);
}
Insert cell
function dotProduct(a, b) {
let sum = 0;
for (let i = 0; i < a.length; i++) {
sum += a[i] * b[i];
}
return sum;
}
Insert cell
function magnitude(a) {
return Math.sqrt(dotProduct(a, a));
}
Insert cell
function cosineSimilarity(a, b) {
if (a.length !== b.length) {
throw new Error("Vectors must have the same dimensions");
}

const magA = magnitude(a);
const magB = magnitude(b);

if (magA === 0 || magB === 0) {
throw new Error(
"Magnitude of one of the vectors is zero, cannot calculate cosine similarity"
);
}

return dotProduct(a, b) / (magA * magB);
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more