|
| 1 | +/** |
| 2 | + * Calculates the cosine similarity between two vectors. This is a useful metric for |
| 3 | + * comparing the similarity of two vectors such as embeddings. |
| 4 | + * |
| 5 | + * @param vector1 - The first vector. |
| 6 | + * @param vector2 - The second vector. |
| 7 | + * |
| 8 | + * @returns The cosine similarity between vector1 and vector2. |
| 9 | + * @throws {Error} If the vectors do not have the same length. |
| 10 | + */ |
| 11 | +export function cosineSimilarity(vector1: number[], vector2: number[]) { |
| 12 | + if (vector1.length !== vector2.length) { |
| 13 | + throw new Error( |
| 14 | + `Vectors must have the same length (vector1: ${vector1.length} elements, vector2: ${vector2.length} elements)`, |
| 15 | + ); |
| 16 | + } |
| 17 | + |
| 18 | + return ( |
| 19 | + dotProduct(vector1, vector2) / (magnitude(vector1) * magnitude(vector2)) |
| 20 | + ); |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Calculates the dot product of two vectors. |
| 25 | + * @param vector1 - The first vector. |
| 26 | + * @param vector2 - The second vector. |
| 27 | + * @returns The dot product of vector1 and vector2. |
| 28 | + */ |
| 29 | +function dotProduct(vector1: number[], vector2: number[]) { |
| 30 | + return vector1.reduce( |
| 31 | + (accumulator: number, value: number, index: number) => |
| 32 | + accumulator + value * vector2[index]!, |
| 33 | + 0, |
| 34 | + ); |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Calculates the magnitude of a vector. |
| 39 | + * @param vector - The vector. |
| 40 | + * @returns The magnitude of the vector. |
| 41 | + */ |
| 42 | +function magnitude(vector: number[]) { |
| 43 | + return Math.sqrt(dotProduct(vector, vector)); |
| 44 | +} |
0 commit comments