Loading...
function cosine(a, b) {
const dot = a.reduce((s, x, i) => s + x * b[i], 0);
const norm = (v) => Math.sqrt(v.reduce((s, x) => s + x * x, 0));
return dot / (norm(a) * norm(b));
}function cosine(a, b) {
if (a.length !== b.length) throw new Error('Vector sizes differ');
const dot = a.reduce((s, x, i) => s + x * b[i], 0);
const norm = (v) => Math.sqrt(v.reduce((s, x) => s + x * x, 0));
const denom = norm(a) * norm(b);
return denom === 0 ? 0 : dot / denom;
}The fixed version rejects vectors of different sizes and returns 0 for zero vectors instead of NaN.
It depends on the model. Scores are only comparable within one model, so pick thresholds from your own data.
For vectors normalized to length 1 they give the same ranking. Without normalization, the dot product also grows with vector length.
From '-1' to '1': '1' means the same direction, '0' means unrelated, and '-1' means opposite.