Public
Edited
Apr 25, 2023
1 star
Insert cell
Insert cell
cosineSimilarity([1, 2, 3], [4, 5, 6])
Insert cell
cosineSimilarityList([1, 2, 3], [[4, 5, 6], [7, 8, 9], [1, 2, 3]])
Insert cell
cosineSimilarity = (a, b) => {
const dotProduct = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
const magnitude = (v) => Math.sqrt(v.map((x, i) => v[i] * v[i]).reduce((m, n) => m + n));

if (a.length !== b.length) {
throw new Error('Vectors must have the same length.');
}

const prod = dotProduct(a, b);
const magnitudeA = magnitude(a);
const magnitudeB = magnitude(b);

if (magnitudeA === 0 || magnitudeB === 0) {
throw new Error('Vectors must be non-zero.');
}

return prod / (magnitudeA * magnitudeB);
}
Insert cell
cosineSimilarityList = (vector, listOfVectors) => {
const dotProduct = (a, b) => a.map((x, i) => a[i] * b[i]).reduce((m, n) => m + n);
const magnitude = (v) => Math.sqrt(v.map((x, i) => v[i] * v[i]).reduce((m, n) => m + n));
if (!Array.isArray(listOfVectors) || listOfVectors.length === 0) {
throw new Error('The list of vectors must be a non-empty array.');
}

if (listOfVectors.some(v => v.length !== vector.length)) {
throw new Error('All vectors must be of equal length.');
}

const magnitudeA = magnitude(vector);

return listOfVectors.map(b => {
const prod = dotProduct(vector, b);
const magnitudeB = magnitude(b);

if (magnitudeA === 0 || magnitudeB === 0) {
throw new Error('Vectors must be non-zero.');
}

return prod / (magnitudeA * magnitudeB);
});
}
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