All formulas

Linear algebra

Cosine similarity

linalg.cosine-similarityAlso called cosine similarity, cosine, cos sim, cossim

cos⁡θ=∑i=1nxiyi∑i=1nxi2∑i=1nyi2\cos\theta = \frac{\sum_{i=1}^{n} x_i y_i}{\sqrt{\sum_{i=1}^{n} x_i^2}\sqrt{\sum_{i=1}^{n} y_i^2}}

Cosine of the angle between two nonzero vectors: their dot product divided by the product of their norms. Ranges from −1 to 1.

Notation

xx

first vector

x ∈ ℝn

yy

second vector

y ∈ ℝn

nn

vector length

Size, at least 1

cos⁡θ\cos\theta

Result: the similarity

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    x=[1,0],y=[0,1]x = [1, 0], y = [0, 1]

    Result

    cos⁡θ=0\displaystyle \cos\theta = 0
  2. Given

    x=[1,2],y=[2,4]x = [1, 2], y = [2, 4]

    Result

    cos⁡θ=1\displaystyle \cos\theta = 1
  3. Given

    x=[1,1],y=[1,0]x = [1, 1], y = [1, 0]

    Result

    cos⁡θ=22\displaystyle \cos\theta = \frac{\sqrt{2}}{2}

    ≈ 0.707106781187

  4. Given

    x=[1,2,3],y=[4,5,6]x = [1, 2, 3], y = [4, 5, 6]

    Result

    cos⁡θ=162277\displaystyle \cos\theta = \frac{16 \sqrt{22}}{77}

    ≈ 0.974631846197

Common mistakes

  • Divides by one norm only

    The dot product is divided by the norm of x but not of y.

    Fix: Divide by the product of both norms.

  • Divides by squared norms

    The denominator uses the sums of squares without their square roots.

    Fix: Divide by ‖x‖‖y‖.

Source

  • Manning et al. 2008

    Manning, Christopher D.; Raghavan, Prabhakar; Schütze, Hinrich. Introduction to Information Retrieval. Cambridge University Press, 2008.