Discord

INAIO Guide Stage 1 10Coordinate Geometry and Vectors

10.4 Dot product and cosine similarity

Use dot products and norms to measure alignment, then normalize to compare directions with cosine similarity.

Two vectors can have similar directions even when their lengths differ greatly. The dot product combines their components; cosine similarity removes the effect of length. These ideas appear in geometry and in comparing numeric feature vectors.

This is intermediate vector algebra. Study the dot-product section of OpenStax's vector lesson after practising vector components and norms.

A basic idea: alignment

For u=(u1,…,un)u=(u_1,\ldots,u_n) and v=(v1,…,vn)v=(v_1,\ldots,v_n),

u⋅v=∑i=1nuivi,∥u∥=∑i=1nui2.u\cdot v=\sum_{i=1}^{n}u_i v_i,\qquad \|u\|=\sqrt{\sum_{i=1}^{n}u_i^2}.

For nonzero vectors, u⋅v=∥u∥∥v∥cos⁡θu\cdot v=\|u\|\|v\|\cos\theta, where θ\theta is the angle between them. A positive dot product means the angle is acute, zero means perpendicular, and a negative one means obtuse.

Three pairs of arrows from one origin show acute alignment with positive dot product, perpendicular vectors with zero dot product, and obtuse alignment with negative dot product.Three pairs of arrows from one origin show acute alignment with positive dot product, perpendicular vectors with zero dot product, and obtuse alignment with negative dot product.
The sign of the dot product describes the angle between nonzero vectors.

A quick tour of properties

For nonzero vectors, cosine similarity is (u⋅v)/(∥u∥∥v∥)(u\cdot v)/(\|u\|\|v\|), from −1-1 to 11 inclusive. It is undefined if either vector is zero. Scaling a vector by a positive number leaves its cosine similarity with another unchanged; the dot product is multiplied by that number. Dot product is symmetric and distributes over addition.

Application 1: geometric projection

Let u=(3,4)u=(3,4) and v=(1,0)v=(1,0). Then u⋅v=3u\cdot v=3 and ∥u∥=5\|u\|=5, ∥v∥=1\|v\|=1. Cosine similarity is 3/5=0.63/5=0.6. Because vv is a unit horizontal vector, the dot product 33 is also the signed horizontal component of uu.

Application 2: compare feature directions

Let a query feature vector be q=(1,1)q=(1,1), and two candidates be a=(2,2)a=(2,2) and b=(3,0)b=(3,0). The dot products are q⋅a=4q\cdot a=4 and q⋅b=3q\cdot b=3. Their cosine similarities are 11 for aa and 3/(32)=1/2≈0.7073/(3\sqrt2)=1/\sqrt2\approx0.707 for bb. Candidate aa points in exactly the query's direction. If bb were (30,0)(30,0), its dot product with qq would be 3030, far above aa's 44, but its cosine similarity would still be 1/21/\sqrt2. Similarity alone does not tell you whether either candidate is useful for the real task.

Resources

SourceTitleWhy read it
OpenStaxVectorsLearn the dot product and angle interpretation.

Finished this module? Mark it done.

Comments

Stuck on something, spotted a mistake, or found a resource that helped you? Tell us below.

Loading comments