Semantic comparison
Compare embedding vectors for two pieces of text or other embedded values.
AI Tools · Function
Calculates the cosine similarity between two numeric vectors. Its signed result ranges from -1 to 1, with values near 1 indicating greater similarity.
cosineSimilarity compares two numeric vectors using the cosine of the angle between them. It returns a score from -1 to 1: values near 1 indicate strong similarity, while values near -1 indicate that the vectors differ.
cosineSimilarity(vector1: number[], vector2: number[]): number| Name | Type | Description |
|---|---|---|
vector1 | number[] | The first vector to compare |
vector2 | number[] | The second vector to compare |
A number between -1 and 1 representing the cosine similarity between the two vectors.
import { cosineSimilarity } from 'ai';
const first = [1, 0, 0];
const second = [0.8, 0.2, 0];
console.log(cosineSimilarity(first, second));Compares two numeric vectors and prints their cosine similarity.
Compare embedding vectors for two pieces of text or other embedded values.
Order items by their similarity score to a reference embedding.
Keep only dataset entries whose similarity score meets a chosen threshold.
It accepts two number arrays and returns their cosine similarity as a number. A result close to 1 means the vectors are very similar, whereas a result close to -1 means they are different.
Follow-up: How would you use it with generated embeddings? Embed the values first, then pass the resulting embedding arrays to cosineSimilarity.
The function is imported from the ai package. Its two inputs are vector1, the first vector to compare, and vector2, the second vector to compare.
Follow-up: What should the inputs represent? They should be numeric vectors whose values encode the items being compared, such as embeddings.
It is useful after creating embeddings when comparing the semantic similarity of text or other represented values. The documentation demonstrates calculating a score between two embeddings.
Follow-up: What can be done with multiple scores? Similarity scores can support ranking or filtering related items in a dataset.
embedManyembed