Implement Cosine Similarity
Exit

Implement Cosine Similarity

Write the function that scores how similar two vectors are

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

From formula to Python

You know the cosine similarity formula from the previous chapter. Now translate it to Python using numpy.

numpy gives you two functions that map directly to the formula:

  • np.dot(a, b) — computes the dot product of two vectors
  • np.linalg.norm(a) — computes the norm of a vector

Divide the dot product by the product of the two norms. That gives you the similarity score.

import numpy as np

def cosine_similarity(vec_a, vec_b):
    return np.dot(vec_a, vec_b) / (np.linalg.norm(vec_a) * np.linalg.norm(vec_b))

Instructions

Complete the cosine_similarity function. The starter code provides the signature.

  1. Create a variable named dot. Assign it np.dot(vec_a, vec_b).
  2. Create a variable named norm. Assign it np.linalg.norm(vec_a) * np.linalg.norm(vec_b).
  3. Return dot / norm.