Cosine Similarity
algebrica.org
algebrica.org
Also FYI to any Postgres users: the pgvector operator is for cosine distance, which is 1 - cosine similarity, and thus ranges from 0 to 2 or 0 to 1.
1) If you have an n-dimensional space where each dimension means/measures something, then points close together in that space will of course be similar in these dimensional qualities.
2) One way to measure closeness/similarity between two points is to consider them as vectors from the origin to the points, then compare the angle (cosine similarity) between the vectors. If the vectors point in the same direction (small angle between them) then the points lie in that same directional region of the n-dimensional space.
3) There are also other ways to measure closeness of points such as the euclidean distance between the points. Cosine similarity tends to work well for high dimensional embedding spaces such as for text embeddings or face embeddings, where distances between different dimensions (e.g. eye-shape vs size-of-nose) are meaningless since these are not euclidian spaces.
I think its true that using TfIdf to calculate the vectors doesnt scale, but we’ve seen that the OpenAi embedding models are pretty capable of encoding semantics of a longer document.
But that is almost of negative help in describing what's going on here: the vectors in question have hundreds (or more!) dimensions, and are (except very abstractly) impossible for humans to visualize. Cosine similarity only becomes useful, and interestingly becomes counterintuitively useful, when used at these higher dimensions.
My point was that the article doesn't describe the above.
The similarity between the strings “dog” and “cat” is qualitatively different from (and substantially more meaningful than) the similarity between the full contents of War and Peace and Anna Karenina, despite both being described by a single value.
In practice, you would never try to calculate the similarity between such long texts. You would use a chunking strategy to break them into pieces more likely to yield meaningful similarity values.
(TF-IDF vectors are largely viewed as a cute trick but ultimately a bit of a dead end in classic information retrieval.)
That said, cosine similarity is definitely still useful for large vectors of things that aside from tf-idf.
I’d imagine speed would