Build a cosine similarity matrix for a set of embeddings
Embedding search ranks documents by cosine similarity: the dot product of two vectors divided by both lengths. It ignores vector length and keeps only direction.
Write cosine_matrix(X) for X of shape (n, d). Return the (n, n) matrix where [i, j] is the cosine similarity of rows i and j.
A row of all zeros has no direction: treat its similarity with everything as 0.
def cosine_matrix(X)Understand the idea
Cosine similarity measures whether two vectors point the same way, ignoring how long they are. It is like comparing the direction two people are walking, not how fast. The value is 1 for the same direction, 0 for right angles and -1 for opposite. Once every row is scaled to length 1, the dot product of two rows is their cosine, so one matrix product gives the full table. Worked example: rows [1, 0] and [1, 1]. Lengths are 1 and sqrt(2) = 1.414. Unit rows are [1, 0] and [0.707, 0.707]. Their dot product is 0.707. The matrix is [[1, 0.707], [0.707, 1]]. A row of all zeros has no direction and would cause division by zero, so its similarities must be 0. Rule: cos(a, b) = (a . b) / (|a| |b|); normalise rows, then X_n X_n^T. Semantic search and RAG retrieval rank documents with this.