Neural Mastery
← Back to Practice

Pairwise Cosine Similarity Matrix

Difficulty: Medium · Concept: Word Embeddings — The Distributional Hypothesis

Cosine Similarity From Scratch compared exactly two vectors. A real embedding search or clustering step needs every pair at once: given nn vectors, produce the full n×nn \times n matrix where entry (i,j)(i, j) is the cosine similarity between vector ii and vector jj — exactly the computation underneath comparing a batch of query embeddings against a batch of candidates, or building the similarity graph a vector database index is organized around.

The genuine edge case: a vector with zero magnitude (all-zero) makes cosine similarity undefined for every pair it's involved in — 0\frac{\cdot}{0} has no answer, so the whole computation has to fail loudly rather than silently produce a nan-filled row.

Your task: implement cosine_similarity_matrix(vectors), returning a list of lists (the matrix). Raise ValueError if any vector has zero magnitude.

Implement it yourself
assert cosine_similarity_matrix([[1, 0], [0, 1]]) == [[1.0, 0.0], [0.0, 1.0]] assert cosine_similarity_matrix([[1, 0], [1, 0], [0, 1]]) == [[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]] assert cosine_similarity_matrix([[3, 4]]) == [[1.0]] assert check_raises(ValueError, cosine_similarity_matrix, [[0, 0], [1, 1]]) == True

Next: TF-IDF Weight From Scratch

Last updated Sep 5, 2026Edit this pageReport an issue