Type at least 2 letters. Enter opens the first result, Esc closes.

    Start here: notation and Python · Lesson 6 · First looks at the main tracks

    A gentle tour of vectors: arrows, lists, length and the dot product

    Beginner 55 min 4 interactive figures 3 videos Colab notebook

    Before this lesson: lesson 02 (the notation Rn\R^n, indices and ∑\sum) and lesson 03 (NumPy arrays). From school you need the theorem of Pythagoras and the cosine of an angle. Time: about 55 minutes, plus the notebook.


    Why this matters #

    • Data are vectors. A data set with nn features stores each sample as a vector x∈Rnx \in \R^n. An 8×88 \times 8 grey image is a vector in R64\R^{64}. A language model stores each word piece (token) as an embedding, a vector with hundreds or thousands of entries (768 in BERT-base).
    • Models are dot products. A linear model, and every neuron of a neural network, computes w⊤x+bw^\top x + b before its activation function. In a transformer, the attention score of a query qq and a key kk is the dot product q⊤kq^\top k, scaled by 1/d1/\sqrt{d}.
    • Similarity is geometry. kk-nearest neighbours uses the distance ∥x−y∥\|x - y\|. Retrieval for chatbots (RAG), recommendation and face recognition compare embeddings with cosine similarity.
    • Size is a norm. Weight decay and ridge regression add λ∥w∥2\lambda \|w\|^2 to the loss, so they keep the weights short.

    This lesson is a first look. The Linear Algebra track starts where it ends.

    1. Predict first #

    2. The picture #

    Two views of one vector #

    The vector u=(3,1)u = (3, 1) is a list of two numbers. Draw it as an arrow: start at the origin, go 3 to the right and 1 up. The numbers are the entries (or components) u1=3u_1 = 3 and u2=1u_2 = 1.

    The two views help in different ways. The arrow gives intuition in 2-D and 3-D. The list works in any number of dimensions. A house with area 120 m², 3 rooms and age 15 years is the vector (120,3,15)∈R3(120, 3, 15) \in \R^3. An 8×88 \times 8 image is a list of 64 grey values, so it is a vector in R64\R^{64}. We cannot draw R64\R^{64}. But every operation in this lesson is defined by the entries, so it works for any nn. We draw the 2-D case only as a guide.

    Adding, subtracting and scaling #

    • Addition is entry by entry: (3,1)+(1,2)=(4,3)(3, 1) + (1, 2) = (4, 3). As arrows: put the tail of vv at the tip of uu ("tip to tail"). The sum goes from the origin to the new tip. It is the diagonal of the parallelogram with sides uu and vv.
    • Scalar multiplication multiplies every entry by one number cc (a scalar): 2⋅(3,1)=(6,2)2 \cdot (3, 1) = (6, 2). The arrow gets 2 times longer. A negative cc flips the arrow to the opposite direction.
    • Subtraction is u−v=u+(−1)vu - v = u + (-1)v. As arrows, u−vu - v goes from the tip of vv to the tip of uu, because v+(u−v)=uv + (u - v) = u.
    Interactive figure: loading…

    Drag the tips of uu (blue) and vv (orange). The violet arrow is the result, and the panel writes it entry by entry. Switch to u−vu - v: the violet arrow now runs from the tip of vv to the tip of uu (its dashed copy starts at the origin). In c⋅uc \cdot u, move the slider below 0 and watch the arrow flip.

    A sum of scaled vectors, such as c1u+c2vc_1 u + c_2 v, is a linear combination of uu and vv. Linear combinations are the main object of Linear Algebra lesson 1.

    Because the operations work entry by entry, they work on data too. Mixing two images, (1−t) a+t b(1 - t)\,a + t\,b, is one scaling of each image and one addition:

    Interactive figure: loading…

    Move the slider tt from 0 to 1. The mix mm fades from image aa to image bb. Below the images, mm is written as 64 numbers, one row of the image per line. Each pixel is one entry, so each entry of the mix is the same mix of two numbers. The images are real samples from scikit-learn's load_digits (grey values 0 to 16).

    Length and distance #

    The arrow (3,4)(3, 4) is the long side (hypotenuse) of a right triangle with the sides 3 and 4. By Pythagoras, its length is 32+42=25=5\sqrt{3^2 + 4^2} = \sqrt{25} = 5. We write the length of xx as ∥x∥\|x\| (the norm of xx).

    In 3-D, use Pythagoras twice. For x=(1,2,2)x = (1, 2, 2), the shadow of xx on the floor is (1,2,0)(1, 2, 0), with length 12+22=5\sqrt{1^2 + 2^2} = \sqrt 5. The vertical part has length 2, and it is at a right angle to the floor. So ∥x∥=(5)2+22=9=3\|x\| = \sqrt{(\sqrt 5)^2 + 2^2} = \sqrt{9} = 3. The same pattern continues in any dimension: square the entries, add them, take the square root.

    The distance between two points xx and yy is the length of the arrow between them, ∥x−y∥\|x - y\|. For (1,1)(1, 1) and (4,5)(4, 5): (4,5)−(1,1)=(3,4)(4, 5) - (1, 1) = (3, 4), so the distance is 5.

    The dot product as a shadow #

    The dot product of uu and vv multiplies the entries pair by pair and adds the products: u⊤v=u1v1+u2v2u^\top v = u_1 v_1 + u_2 v_2. For u=(3,1)u = (3, 1) and v=(1,2)v = (1, 2): 3⋅1+1⋅2=53 \cdot 1 + 1 \cdot 2 = 5.

    There is a second way to get the same number. Let θ\theta be the angle between the two arrows. Drop vv straight down (at a right angle) onto the line of uu. The result is the shadow, or projection, of vv on uu. Its signed length is ∥v∥cos⁡θ\|v\| \cos\theta. Then

    u⊤v=∥u∥ ∥v∥cos⁡θ.u^\top v = \|u\| \, \|v\| \cos\theta .

    In words: u⊤vu^\top v is the length of uu times the signed length of the shadow of vv.

    Interactive figure: loading…

    Drag the tips of uu and vv and compare the two readouts: the sum of products and ∥u∥∥v∥cos⁡θ\|u\|\|v\|\cos\theta are always equal. The thick segment is the shadow of vv on the line of uu: aqua when θ<90°\theta < 90°, magenta when θ>90°\theta > 90°. Press right angle: the shadow disappears and the dot product is 0.

    So the sign of the dot product tells you the type of angle:

    u⊤vu^\top v angle θ\theta the two arrows
    >0> 0 0°≤θ<90°0° \le \theta < 90° (acute) point roughly the same way
    =0= 0 θ=90°\theta = 90° (right) are orthogonal (perpendicular)
    <0< 0 90°<θ≤180°90° < \theta \le 180° (obtuse) point roughly opposite ways

    The table assumes that uu and vv are not the zero vector. For the zero vector the angle is not defined.

    Quick check

    What is the length of x=(3,4)x = (3, 4), and what is the distance between (1,1)(1, 1) and (4,5)(4, 5)?

    Quick check

    u=(1,2)u = (1, 2) and v=(3,−1)v = (3, -1). What is u⊤vu^\top v, and what kind of angle do uu and vv make?

    3. Definitions and main results #

    Vectors and their operations #

    A vector x∈Rnx \in \R^n is an ordered list of nn real numbers x1,…,xnx_1, \dots, x_n. We write it as a column, and x⊤x^\top (the transpose) is the same numbers as a row:

    x=(x1⋮xn),x⊤=(x1,…,xn).x = \begin{pmatrix} x_1 \\ \vdots \\ x_n \end{pmatrix}, \qquad x^\top = (x_1, \dots, x_n).

    In running text we write x=(x1,…,xn)x = (x_1, \dots, x_n); it still means a column. The zero vector 00 has all entries 0. For x,y∈Rnx, y \in \R^n and a scalar c∈Rc \in \R:

    x+y=(x1+y1,…,xn+yn),c x=(cx1,…,cxn).\begin{aligned} x + y &= (x_1 + y_1, \dots, x_n + y_n), \\ c\,x &= (c x_1, \dots, c x_n). \end{aligned}

    Both operations work entry by entry, so they follow the rules of ordinary numbers: x+y=y+xx + y = y + x, (x+y)+z=x+(y+z)(x + y) + z = x + (y + z), c(x+y)=cx+cyc(x + y) = cx + cy, and x+0=xx + 0 = x. Only vectors of the same size can be added.

    Norm, unit vector, distance #

    Definition. The norm (Euclidean length) of x∈Rnx \in \R^n is

    ∥x∥=x12+x22+⋯+xn2=∑i=1nxi2.\|x\| = \sqrt{x_1^2 + x_2^2 + \dots + x_n^2} = \sqrt{\textstyle\sum_{i=1}^n x_i^2}.

    Other norms exist (the Linear Algebra lesson on norms compares them). In this track, ∥x∥\|x\| always means this one, also written ∥x∥2\|x\|_2. Do not confuse it with ∣a∣|a|, the absolute value of one number.

    Two properties follow directly from the definition.

    1. ∥x∥≥0\|x\| \ge 0, and ∥x∥=0\|x\| = 0 only for x=0x = 0. A sum of squares is zero only if every square is zero.
    2. ∥c x∥=∣c∣ ∥x∥\|c\,x\| = |c|\,\|x\|. Proof: ∥cx∥=∑ic2xi2=c2∑ixi2=∣c∣ ∥x∥\|cx\| = \sqrt{\sum_i c^2 x_i^2} = \sqrt{c^2}\sqrt{\sum_i x_i^2} = |c|\,\|x\|, because c2=∣c∣\sqrt{c^2} = |c| (for example (−2)2=2\sqrt{(-2)^2} = 2). ■\blacksquare

    A unit vector has norm 1. For x≠0x \ne 0, the vector x^=x/∥x∥\hat x = x / \|x\| is a unit vector in the direction of xx: by property 2, ∥x/∥x∥∥=∥x∥/∥x∥=1\|x / \|x\|\| = \|x\| / \|x\| = 1. For example (3,4)/5=(0.6,0.8)(3, 4)/5 = (0.6, 0.8). Dividing by the norm is called normalizing.

    The (Euclidean) distance between xx and yy is ∥x−y∥\|x - y\|.

    The dot product #

    Definition. The dot product (or inner product) of x,y∈Rnx, y \in \R^n is the number

    x⊤y=x1y1+x2y2+⋯+xnyn=∑i=1nxiyi.x^\top y = x_1 y_1 + x_2 y_2 + \dots + x_n y_n = \sum_{i=1}^n x_i y_i .

    Books also write x⋅yx \cdot y or ⟨x,y⟩\langle x, y \rangle. The notation x⊤yx^\top y is "row times column": a 1×n1 \times n row times an n×1n \times 1 column gives a 1×11 \times 1 result, one number. In NumPy it is x @ y or np.dot(x, y).

    Rules. For vectors x,y,zx, y, z and a scalar cc:

    • symmetric: x⊤y=y⊤xx^\top y = y^\top x;
    • linear in each vector: x⊤(y+z)=x⊤y+x⊤zx^\top (y + z) = x^\top y + x^\top z and x⊤(cy)=c x⊤yx^\top (c y) = c\, x^\top y;
    • length: x⊤x=∑ixi2=∥x∥2x^\top x = \sum_i x_i^2 = \|x\|^2.

    Each rule follows from the same rule for numbers, applied to every term of the sum.

    Expanding a squared length. The rules give a formula that we use again and again:

    ∥x+y∥2=∥x∥2+∥y∥2+2 x⊤y,∥x−y∥2=∥x∥2+∥y∥2−2 x⊤y.\begin{aligned} \|x + y\|^2 &= \|x\|^2 + \|y\|^2 + 2\,x^\top y, \\ \|x - y\|^2 &= \|x\|^2 + \|y\|^2 - 2\,x^\top y . \end{aligned}

    Proof (for the minus sign; the plus sign is the same with −y-y replaced by yy).

    1. Use the length rule: ∥x−y∥2=(x−y)⊤(x−y)\|x - y\|^2 = (x - y)^\top (x - y).
    2. Use linearity to multiply out, like (a−b)(a−b)(a - b)(a - b) for numbers: x⊤x−x⊤y−y⊤x+y⊤yx^\top x - x^\top y - y^\top x + y^\top y.
    3. Use symmetry, y⊤x=x⊤yy^\top x = x^\top y, and the length rule: ∥x∥2−2 x⊤y+∥y∥2\|x\|^2 - 2\,x^\top y + \|y\|^2. ■\blacksquare

    It is the vector version of (a−b)2=a2−2ab+b2(a - b)^2 = a^2 - 2ab + b^2.

    The geometric formula #

    Theorem. Let x,y∈Rnx, y \in \R^n be nonzero, and let θ∈[0°,180°]\theta \in [0°, 180°] be the angle between them. Then

    x⊤y=∥x∥ ∥y∥cos⁡θ.x^\top y = \|x\|\,\|y\| \cos\theta .

    Why this is true, in one picture. The arrows xx, yy and x−yx - y form a triangle. The expansion above gives the length of the third side from the dot product. The law of cosines gives the length of the same side from the angle. The two formulas must agree, and that forces x⊤y=∥x∥∥y∥cos⁡θx^\top y = \|x\|\|y\|\cos\theta.

    Proof with the law of cosines
    1. Draw the triangle with corners 00, xx and yy. Its sides have the lengths a=∥x∥a = \|x\| and b=∥y∥b = \|y\|, and the side from the tip of yy to the tip of xx is the arrow x−yx - y, with length c=∥x−y∥c = \|x - y\|. The angle at the corner 00 is θ\theta.
    2. The law of cosines (school geometry; it is Pythagoras when θ=90°\theta = 90°) says c2=a2+b2−2abcos⁡θc^2 = a^2 + b^2 - 2ab\cos\theta, that is, ∥x−y∥2=∥x∥2+∥y∥2−2∥x∥∥y∥cos⁡θ\|x - y\|^2 = \|x\|^2 + \|y\|^2 - 2\|x\|\|y\|\cos\theta.
    3. The expansion of the previous section says ∥x−y∥2=∥x∥2+∥y∥2−2 x⊤y\|x - y\|^2 = \|x\|^2 + \|y\|^2 - 2\,x^\top y.
    4. The left sides of steps 2 and 3 are equal. Subtract ∥x∥2+∥y∥2\|x\|^2 + \|y\|^2 from both right sides and divide by −2-2: x⊤y=∥x∥∥y∥cos⁡θx^\top y = \|x\|\|y\|\cos\theta. ■\blacksquare

    If xx and yy lie on one line, the "triangle" is flat (θ=0°\theta = 0° or 180°180°). The formula still holds: for y=cxy = cx with c>0c > 0, x⊤y=c∥x∥2=∥x∥ ∥y∥cos⁡0°x^\top y = c\|x\|^2 = \|x\|\,\|y\|\cos 0°, and the case c<0c < 0 is the same with cos⁡180°=−1\cos 180° = -1.

    In Rn\R^n with n>3n > 3 we cannot measure the angle with a protractor. There, we turn the theorem around and use it to define the angle:

    cos⁡θ=x⊤y∥x∥ ∥y∥.\cos\theta = \frac{x^\top y}{\|x\|\,\|y\|} .

    This is a valid definition because the fraction is always between −1-1 and 11 (the Cauchy–Schwarz inequality, in the folded block below).

    Consequences.

    • x⊤y>0x^\top y > 0, =0= 0 or <0< 0 exactly when the angle is acute, right or obtuse (for nonzero xx, yy), because ∥x∥∥y∥>0\|x\|\|y\| > 0 and cos⁡θ\cos\theta has the same sign as x⊤yx^\top y.
    • xx and yy are orthogonal (perpendicular) when x⊤y=0x^\top y = 0. Then ∥x+y∥2=∥x∥2+∥y∥2\|x + y\|^2 = \|x\|^2 + \|y\|^2: this is Pythagoras in Rn\R^n.
    • The scalar projection of yy on the direction of xx is ∥y∥cos⁡θ=x⊤y/∥x∥\|y\|\cos\theta = x^\top y / \|x\|, and the projection vector is x⊤y∥x∥2 x\dfrac{x^\top y}{\|x\|^2}\,x. This is the "shadow" of the figure.
    Quick check

    For two nonzero vectors, ∥u∥=2\|u\| = 2, ∥v∥=3\|v\| = 3 and u⊤v=−3u^\top v = -3. What is the angle between them?

    Cosine similarity #

    Definition. The cosine similarity of two nonzero vectors is

    cos⁡(x,y)=x⊤y∥x∥ ∥y∥∈[−1,1].\cos(x, y) = \frac{x^\top y}{\|x\|\,\|y\|} \in [-1, 1].

    It is 1 when xx and yy point in the same direction, 0 when they are orthogonal, and −1-1 when they point in opposite directions. It ignores length: for c>0c > 0, cos⁡(cx,y)=c x⊤yc∥x∥ ∥y∥=cos⁡(x,y)\cos(cx, y) = \dfrac{c\,x^\top y}{c\|x\|\,\|y\|} = \cos(x, y).

    This is why it is used for texts and embeddings. A long article and a short note about the same topic have word-count vectors that point the same way but have different lengths. Cosine similarity calls them similar. The distance ∥x−y∥\|x - y\| calls them far apart, because it also compares the lengths.

    Interactive figure: loading…

    Drag the query qq (blue). Each orange point is a document, written as the counts of two words. The left table ranks the documents by cosine similarity and the right table by distance. The best match by cosine has a violet ring, and the best match by distance has an aqua ring. D1 =(4,2)= (4, 2) and D2 =(8,4)= (8, 4) point in the same direction: cosine gives them the same score, distance does not. Drag qq far out along that direction and watch only the distance ranking change.

    For unit vectors the two measures agree. If ∥x∥=∥y∥=1\|x\| = \|y\| = 1, the expansion gives

    ∥x−y∥2=1+1−2 x⊤y=2−2cos⁡(x,y).\|x - y\|^2 = 1 + 1 - 2\,x^\top y = 2 - 2\cos(x, y).

    So a smaller distance means a larger cosine. This is why many systems normalize all embeddings to length 1 first and then use either measure.

    A linear model is a dot product #

    A linear model predicts a number from the feature vector x∈Rnx \in \R^n with weights w∈Rnw \in \R^n and a bias b∈Rb \in \R:

    y^=w⊤x+b=w1x1+w2x2+⋯+wnxn+b.\hat y = w^\top x + b = w_1 x_1 + w_2 x_2 + \dots + w_n x_n + b .

    Each weight wjw_j says how much feature jj counts: if xjx_j grows by 1 and the other features stay the same, y^\hat y changes by wjw_j. For a house with x=(1.2,4)x = (1.2, 4) (area in 100 m², rooms) and w=(3,0.5)w = (3, 0.5), b=1b = 1 (prices in 100 000 CHF): y^=3⋅1.2+0.5⋅4+1=6.6\hat y = 3 \cdot 1.2 + 0.5 \cdot 4 + 1 = 6.6.

    The geometric formula gives a second reading. For a fixed length of xx, the score w⊤xw^\top x is largest when xx points in the direction of ww. So a neuron "looks for" inputs that point like its weight vector.

    Cauchy–Schwarz, and angles in high dimension

    Cauchy–Schwarz inequality. For all x,y∈Rnx, y \in \R^n: ∣x⊤y∣≤∥x∥ ∥y∥|x^\top y| \le \|x\|\,\|y\|.

    Proof. If y=0y = 0 both sides are 0. Otherwise, for every number tt, a squared length is not negative: 0≤∥x−ty∥2=∥x∥2−2t x⊤y+t2∥y∥20 \le \|x - t y\|^2 = \|x\|^2 - 2t\,x^\top y + t^2 \|y\|^2. Choose t=x⊤y/∥y∥2t = x^\top y / \|y\|^2 (the tt that makes the right side smallest). This gives 0≤∥x∥2−(x⊤y)2/∥y∥20 \le \|x\|^2 - (x^\top y)^2 / \|y\|^2, so (x⊤y)2≤∥x∥2∥y∥2(x^\top y)^2 \le \|x\|^2\|y\|^2. Take square roots. ■\blacksquare

    So x⊤y/(∥x∥∥y∥)x^\top y / (\|x\|\|y\|) always lies in [−1,1][-1, 1], and the definition of the angle above makes sense. It does not need a picture, so it works for every nn.

    Random vectors in high dimension are almost orthogonal. Draw two vectors with independent standard normal entries. In R2\R^2 their angle can be anything from 0° to 180°. In R1000\R^{1000} it is almost always close to 90°: in a simulation with 2000 pairs, the angles had mean 90.0° and standard deviation 1.8°. The dot product is a sum of nn random terms with mean 0, so it grows like n\sqrt n, while ∥x∥∥y∥\|x\|\|y\| grows like nn. The notebook draws the histogram. Linear Algebra lesson 18 uses this fact.

    Answers to section 1. (1) 45°45°: cos⁡θ=1⋅1+0⋅11⋅2=12\cos\theta = \dfrac{1 \cdot 1 + 0 \cdot 1}{1 \cdot \sqrt 2} = \dfrac{1}{\sqrt 2}. (2) ∥2x∥=2∥x∥=2⋅5=10\|2x\| = 2\|x\| = 2 \cdot 5 = 10; directly, 36+64=10\sqrt{36 + 64} = 10. (3) Exactly 1: cosine similarity ignores length, and 2x2x points in the same direction as xx.

    4. Worked example #

    Take x=(2,1)x = (2, 1) and y=(1,3)y = (1, 3).

    (a) Operations.

    x+y=(2+1, 1+3)=(3,4),x−y=(2−1, 1−3)=(1,−2),2x=(2⋅2, 2⋅1)=(4,2).\begin{aligned} x + y &= (2 + 1,\ 1 + 3) = (3, 4), \\ x - y &= (2 - 1,\ 1 - 3) = (1, -2), \\ 2x &= (2 \cdot 2,\ 2 \cdot 1) = (4, 2). \end{aligned}

    (b) Lengths and distance.

    ∥x∥=22+12=5≈2.236,∥y∥=12+32=10≈3.162,∥x−y∥=12+(−2)2=5≈2.236.\begin{aligned} \|x\| &= \sqrt{2^2 + 1^2} = \sqrt 5 \approx 2.236, \\ \|y\| &= \sqrt{1^2 + 3^2} = \sqrt{10} \approx 3.162, \\ \|x - y\| &= \sqrt{1^2 + (-2)^2} = \sqrt 5 \approx 2.236 . \end{aligned}

    The unit vector in the direction of xx is x/∥x∥=(2,1)/5≈(0.894,0.447)x / \|x\| = (2, 1)/\sqrt 5 \approx (0.894, 0.447).

    (c) Dot product and angle.

    x⊤y=2⋅1+1⋅3=5,cos⁡θ=55⋅10=550=552=12≈0.707,\begin{aligned} x^\top y &= 2 \cdot 1 + 1 \cdot 3 = 5, \\ \cos\theta &= \frac{5}{\sqrt 5 \cdot \sqrt{10}} = \frac{5}{\sqrt{50}} = \frac{5}{5\sqrt 2} = \frac{1}{\sqrt 2} \approx 0.707, \end{aligned}

    so θ=45°\theta = 45°.

    (d) Check with the expansion. ∥x−y∥2=∥x∥2+∥y∥2−2 x⊤y=5+10−2⋅5=5\|x - y\|^2 = \|x\|^2 + \|y\|^2 - 2\,x^\top y = 5 + 10 - 2 \cdot 5 = 5. This matches (b): (5)2=5(\sqrt 5)^2 = 5. ✓

    (e) Projection. The projection of yy on the direction of xx is

    x⊤y∥x∥2 x=55 (2,1)=(2,1),\frac{x^\top y}{\|x\|^2}\, x = \frac{5}{5}\,(2, 1) = (2, 1),

    with scalar projection x⊤y/∥x∥=5/5=5≈2.236x^\top y / \|x\| = 5/\sqrt 5 = \sqrt 5 \approx 2.236. The rest, y−(2,1)=(−1,2)y - (2, 1) = (-1, 2), is orthogonal to xx: (2,1)⊤(−1,2)=−2+2=0(2, 1)^\top(-1, 2) = -2 + 2 = 0. ✓

    (f) Cosine versus distance. The query q=(2,1)q = (2, 1) is compared with two documents of the figure: D2 =(8,4)= (8, 4) and D6 =(1,1)= (1, 1).

    • D2 =(8,4)= (8, 4):   q⊤D2=2⋅8+1⋅4=20\;q^\top D2 = 2 \cdot 8 + 1 \cdot 4 = 20 and ∥D2∥=80\|D2\| = \sqrt{80}, so cos⁡(q,D2)=205⋅80=20400=1\cos(q, D2) = \dfrac{20}{\sqrt 5 \cdot \sqrt{80}} = \dfrac{20}{\sqrt{400}} = 1. The difference is q−D2=(−6,−3)q - D2 = (-6, -3), so the distance is 36+9=45≈6.708\sqrt{36 + 9} = \sqrt{45} \approx 6.708.
    • D6 =(1,1)= (1, 1):   q⊤D6=2+1=3\;q^\top D6 = 2 + 1 = 3 and ∥D6∥=2\|D6\| = \sqrt 2, so cos⁡(q,D6)=35⋅2=310≈0.949\cos(q, D6) = \dfrac{3}{\sqrt 5 \cdot \sqrt 2} = \dfrac{3}{\sqrt{10}} \approx 0.949. The difference is q−D6=(1,0)q - D6 = (1, 0), so the distance is 11.

    Cosine similarity prefers D2 (same direction: D2=4qD2 = 4q). Distance prefers D6 (close to the tip of qq).

    5. In code #

    NumPy checks the hand computations above. The notebook for this lesson has these cells and the exercises.

    import numpy as np
    
    x = np.array([2., 1.])
    y = np.array([1., 3.])
    
    print(x + y, x - y, 2 * x)                 # [3. 4.] [ 1. -2.] [4. 2.]
    print(np.linalg.norm(x), np.linalg.norm(y))  # 2.236... 3.162...
    print(np.linalg.norm(x - y))               # 2.236...  (distance)
    print(x / np.linalg.norm(x))               # [0.894 0.447]  (unit vector)
    
    dot = x @ y                                # same as np.dot(x, y) and np.sum(x * y)
    cos = dot / (np.linalg.norm(x) * np.linalg.norm(y))
    print(dot, cos, np.degrees(np.arccos(cos)))  # 5.0 0.7071... 45.0...
    
    # the expansion ||x - y||^2 = ||x||^2 + ||y||^2 - 2 x.y
    print(np.isclose(np.sum((x - y)**2), x @ x + y @ y - 2 * (x @ y)))  # True
    
    # projection of y on the direction of x, and the orthogonal rest
    p = (x @ y) / (x @ x) * x
    print(p, (y - p) @ x)                      # [2. 1.] 0.0
    
    # cosine similarity versus distance
    q, D2, D6 = np.array([2., 1.]), np.array([8., 4.]), np.array([1., 1.])
    cosine = lambda a, b: a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
    print(cosine(q, D2), cosine(q, D6))        # 1.0 0.9486...
    print(np.linalg.norm(q - D2), np.linalg.norm(q - D6))  # 6.708... 1.0
    

    The angle may print as 45.00000000000001: floats are not exact (lesson 03). Compare floats with np.isclose.

    6. Where it shows up #

    • Features and embeddings. A row of a data matrix XX is a feature vector x(i)x^{(i)}. Word embeddings place words with similar meaning at similar directions, so cosine similarity finds related words. Sentence embeddings and vector databases do the same for whole texts; this is the retrieval step of RAG.
    • Nearest neighbours. kk-NN classification and clustering with kk-means compute distances ∥x−y∥\|x - y\| between feature vectors. The notebook finds the nearest neighbour of a digit image by cosine similarity.
    • Neurons and attention. A neuron computes w⊤x+bw^\top x + b. Scaled dot-product attention computes q⊤k/dq^\top k / \sqrt d for every query and key, then a softmax (lesson 05). A large dot product means "this key matches this query".
    • Regularization. Ridge regression and weight decay add λ∥w∥2=λ w⊤w\lambda\|w\|^2 = \lambda\, w^\top w to the loss.
    • ML for science. A molecule or a material is often stored as a fingerprint vector, and similar compounds are found with a similarity of these vectors. A wind field is a 2-D or 3-D vector at each grid point, and the speed is its norm.

    7. Common mistakes #

    • Adding the entries to get a length. ∥(3,4)∥=5\|(3, 4)\| = 5, not 3+4=73 + 4 = 7. Square, add, then take the square root.
    • Forgetting the square root. x⊤x=∥x∥2x^\top x = \|x\|^2, not ∥x∥\|x\|.
    • Confusing ∥x∥\|x\| and ∣x∣|x|. ∥x∥\|x\| is the length of a vector. ∣a∣|a| is the absolute value of a number. They agree only for n=1n = 1.
    • Thinking that the dot product is a vector. x⊤yx^\top y is one number. The entrywise product x * y in NumPy is a vector; its sum is the dot product.
    • Asking for the angle with the zero vector. cos⁡θ=x⊤y/(∥x∥∥y∥)\cos\theta = x^\top y / (\|x\|\|y\|) divides by 0. The zero vector has no direction.
    • Using cosine similarity when length matters. Two shopping baskets with 1 apple and 100 apples point in the same direction, so their cosine similarity is 1. If the amount matters, use a distance (or compare the norms too).

    8. Check yourself #

    1. Compute u+vu + v, u−vu - v and −2u-2u for u=(1,−2,3)u = (1, -2, 3) and v=(4,0,−1)v = (4, 0, -1).
      Answeru+v=(5,−2,2)u + v = (5, -2, 2), u−v=(−3,−2,4)u - v = (-3, -2, 4), −2u=(−2,4,−6)-2u = (-2, 4, -6).
    2. Find the unit vector in the direction of (1,2,2)(1, 2, 2).
      Answer∥(1,2,2)∥=1+4+4=3\|(1, 2, 2)\| = \sqrt{1 + 4 + 4} = 3, so the unit vector is (1/3,2/3,2/3)(1/3, 2/3, 2/3).
    3. For which number aa are (2,a)(2, a) and (3,−6)(3, -6) orthogonal?
      Answer2⋅3+a⋅(−6)=6−6a=02 \cdot 3 + a \cdot (-6) = 6 - 6a = 0, so a=1a = 1. Check: (2,1)⊤(3,−6)=6−6=0(2, 1)^\top (3, -6) = 6 - 6 = 0.
    4. ∥x∥=3\|x\| = 3, ∥y∥=4\|y\| = 4 and x⊤y=0x^\top y = 0. What is ∥x+y∥\|x + y\|?
      Answer∥x+y∥2=∥x∥2+∥y∥2+2x⊤y=9+16+0=25\|x + y\|^2 = \|x\|^2 + \|y\|^2 + 2x^\top y = 9 + 16 + 0 = 25, so ∥x+y∥=5\|x + y\| = 5 (Pythagoras).
    5. Two embeddings are normalized to length 1, and their distance is ∥x−y∥=1\|x - y\| = 1. What is their cosine similarity, and what is the angle?
      Answer∥x−y∥2=2−2cos⁡(x,y)\|x - y\|^2 = 2 - 2\cos(x, y) gives 1=2−2cos⁡1 = 2 - 2\cos, so cos⁡(x,y)=0.5\cos(x, y) = 0.5 and θ=60°\theta = 60°.
    6. A linear model has w=(2,−1)w = (2, -1) and b=0.5b = 0.5. Compute y^\hat y for x=(3,4)x = (3, 4). Which change of xx increases y^\hat y fastest, for a step of length 1?
      Answery^=2⋅3+(−1)⋅4+0.5=2.5\hat y = 2 \cdot 3 + (-1) \cdot 4 + 0.5 = 2.5. A step ss changes y^\hat y by w⊤s=∥w∥∥s∥cos⁡θw^\top s = \|w\|\|s\|\cos\theta. For ∥s∥=1\|s\| = 1 this is largest when ss points along ww: s=w/∥w∥=(2,−1)/5s = w/\|w\| = (2, -1)/\sqrt 5, and y^\hat y grows by ∥w∥=5≈2.236\|w\| = \sqrt 5 \approx 2.236. Lesson 07 uses the same argument for the gradient.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is the norm (length) of x∈Rnx \in \R^n?

    2. Compute ∥(3,4)∥\|(3, 4)\| and the unit vector in its direction.

    3. Give the two formulas for the dot product x⊤yx^\top y.

    4. What does x⊤y=0x^\top y = 0 mean for two nonzero vectors?

    5. Expand ∥x−y∥2\|x - y\|^2 with dot products.

    6. What is the cosine similarity of xx and yy, and what range does it have?

    7. Why is the cosine similarity of xx and 3x3x equal to 1?

    8. How are distance and cosine similarity related for unit vectors?

    9. Compute (1,2)⊤(3,−1)(1, 2)^\top (3, -1).

    10. Write a linear model as a dot product. What does the weight wjw_j mean?

    Open the review →

    9. Interview angle #

    • "What is the difference between cosine similarity and Euclidean distance? When do you use which?" — Cosine compares directions and ignores length; distance compares positions. Use cosine for texts and embeddings where length reflects size, not meaning. For unit vectors they give the same ranking, because ∥x−y∥2=2−2cos⁡(x,y)\|x - y\|^2 = 2 - 2\cos(x, y).
    • "Why is the dot product ∥x∥∥y∥cos⁡θ\|x\|\|y\|\cos\theta?" — Expand ∥x−y∥2=∥x∥2+∥y∥2−2x⊤y\|x - y\|^2 = \|x\|^2 + \|y\|^2 - 2x^\top y and compare with the law of cosines on the triangle 0,x,y0, x, y.
    • "Why does attention divide by d\sqrt{d}?" — For random vectors with independent entries of variance 1, q⊤kq^\top k is a sum of dd terms with variance 1 each, so its standard deviation is d\sqrt d. Dividing keeps the scores in a range where the softmax is not saturated.
    • "Two random vectors in 1000 dimensions: what angle do you expect?" — Close to 90°90°; the cosine is of size 1/n1/\sqrt n.

    10. Practice #

    The notebook for this lesson runs in Colab or in your browser. Four exercises, each with a check cell and a folded solution:

    1. Write norm, dot and angle_deg with a loop or np.sum, and check them against np.linalg.norm and @.
    2. Check ∥u+v∥2=∥u∥2+∥v∥2+2u⊤v\|u + v\|^2 = \|u\|^2 + \|v\|^2 + 2u^\top v on random vectors.
    3. Build the cosine-similarity matrix of the rows of a matrix with broadcasting, and find the nearest neighbour of a digit image from load_digits.
    4. Draw random vectors in n=2,10,1000n = 2, 10, 1000 dimensions and plot the histogram of their angles.

    11. Watch and read #

    The arrow view and the list view of a vector, addition tip to tail, and scaling.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The dot product as a projection (the "shadow" of this lesson). The duality part is optional for now.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Cosine similarity on word counts of short texts, the same setting as the cosine figure above.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play