Cosine distance is defined as 1 minus the cosine similarity, the cosine of the angle between two vectors, so two vectors pointing in exactly the same direction have a cosine distance of 0, regardless of how long each vector actually is, while two perpendicular vectors have a cosine distance of 1. This makes it especially popular for comparing text documents represented as word-frequency vectors, or other high-dimensional data, where the overall magnitude of a vector, like a document's total length, shouldn't affect how similar two things are considered to be, only their relative proportions/direction.
1Understanding spatial.distance.cosine()
Cosine distance is defined as 1 minus the cosine similarity, the cosine of the angle between two vectors, so two vectors pointing in exactly the same direction have a cosine distance of 0, regardless of how long each vector actually is, while two perpendicular vectors have a cosine distance of 1. This makes it especially popular for comparing text documents represented as word-frequency vectors, or other high-dimensional data, where the overall magnitude of a vector, like a document's total length, shouldn't affect how similar two things are considered to be, only their relative proportions/direction.
Use cosine distance instead of Euclidean distance specifically when the relative proportions/direction of a vector matter more than its absolute magnitude — like comparing two documents' word-frequency vectors, where a long document and a short document covering the same topics in the same proportions should be considered similar, not distant.
from scipy.spatial import distance
v1 = (1, 0)
v2 = (0, 1)
print(distance.cosine(v1, v2))2Practical Example
Here is a real-world application of spatial.distance.cosine() showing how it is used in production SciPy code.
from scipy.spatial import distance
v1 = (1, 2, 3)
v2 = (2, 4, 6)
print(distance.cosine(v1, v2))3Best Practices
Follow these guidelines when working with spatial.distance.cosine():
1. Use cosine distance for text/document similarity and other high-dimensional data where the direction, not the magnitude, of a vector is what actually matters
2. Use Euclidean distance instead when the actual magnitude/scale of the data is meaningful and should factor into the notion of similarity
3. Remember cosine distance ranges from 0, identical direction, to 2, exactly opposite direction, unlike Euclidean distance, which has no fixed upper bound
Tip: Use cosine distance instead of Euclidean distance specifically when the relative proportions/direction of a vector matter more than its absolute magnitude — like comparing two documents' word-frequency vectors, where a long document and a short document covering the same topics in the same proportions should be considered similar, not distant.
from scipy.spatial import distance
v1 = (1, 0)
v2 = (0, 1)
print(distance.cosine(v1, v2))