All problems
Cosine Similarity Matrix
Problem
Given a matrix X whose rows are vectors, return the Gram-style cosine similarity matrix:
S[i][j] = (X[i] . X[j]) / (||X[i]||_2 * ||X[j]||_2)
If either row is the zero vector, set the corresponding entry to 0.0.
Hint
Compute pairwise cosine similarities; the diagonal is 1 for nonzero rows.
Test cases
case 1
in: [[[1,0],[0,1]]]
expected: [[1,0],[0,1]]
case 2
in: [[[1,0],[1,0]]]
expected: [[1,1],[1,1]]
case 3
in: [[[1,1],[1,-1]]]
expected: [[1,0],[0,1]]
case 4
in: [[[0,0],[1,1]]]
expected: [[0,0],[0,1]]
Starter codePython
def cosine_similarity_matrix(X):
# Your code here
pass4 test cases · run your code against them in the editor