Skip to content
DeepForgeby svx
All problems
MediumML Fundamentalsproj-024

User Cosine Similarity

Problem

Compute pairwise cosine similarities between users.

matrix is a user x item rating matrix. Return an n x n matrix where entry [a][b] = dot(row_a, row_b) / (norm_a * norm_b), or 0.0 when either row has zero norm. A user with any ratings has similarity 1.0 with themselves.

Hint

The zero vector has no direction, so its cosine with anything is defined as 0.0.

Test cases

case 1
in: [[[1,0],[1,0]]]
expected: [[1,1],[1,1]]
case 2
in: [[[1,0],[0,1]]]
expected: [[1,0],[0,1]]
case 3
in: [[[0,0],[1,1]]]
expected: [[0,0],[0,1]]
case 4
in: [[[1,0],[1,1]]]
expected: [[1,0.7071067811865475],[0.7071067811865475,1]]
Starter codePython
import math
def user_similarity(matrix):
    # Your code here
    pass

4 test cases · run your code against them in the editor