Overview
cosine_similarity is a utility function for calculating the cosine similarity between two embedding vectors. It’s dependency-free and provides a quick way to measure semantic similarity between texts.
Basic usage
cosine_similarity.py
Parameters
Return value
Returns afloat between -1 and 1:
- 1.0: Vectors are identical (perfect similarity)
- 0.0: Vectors are orthogonal (no similarity)
- -1.0: Vectors are opposite (perfect dissimilarity)
- 0.7-0.9: High semantic similarity
- 0.3-0.7: Moderate similarity
- 0.0-0.3: Low similarity
Examples
Basic similarity calculation
Finding most similar text
Semantic search example
Comparing multiple vectors
Error handling
Mathematical details
Cosine similarity is calculated as:A · Bis the dot product of vectors A and B||A||and||B||are the magnitudes (L2 norms) of vectors A and B
Performance considerations
- Dependency-free: No external libraries required
- Efficient: O(n) time complexity where n is vector dimension
- Memory: Low memory footprint
- Accuracy: Provides reliable similarity scores for normalized embeddings