Week 01 · Vectors, norms, and dot products

Read vectors as coordinates or features, calculate lengths and angles, and decide when magnitude matters.

Subject contents · Week 2

Read vectors as coordinates or features, calculate lengths and angles, and decide when magnitude matters.

Decide what similarity should mean

Suppose two movie profiles count action and comedy tags in that order. The profile (3, 4) means three action tags and four comedy tags. The profile (6, 8) has twice as many tags in both categories. If you are comparing the mix, the two movies have the same direction. If you are planning how much data to process, the second profile contains more tags. The same vectors support different answers because the question changes.

By the end of this lesson, you should be able to choose a comparison, calculate it by hand, and explain what information it ignores. This choice comes up in nearest-neighbor search, document retrieval, and any model that represents one example as a row of features.

The idea

A vector is an ordered list of numbers. In geometry, (3, 4) describes an arrow that moves three units right and four up. In a dataset, those coordinates could be counts from two features. The order is part of the meaning. Two vectors with the same length can describe different observations.

The dot product multiplies matching coordinates and adds the products. The Euclidean norm measures the distance from a vector to the origin. It is the square root of the dot product of the vector with itself.

The dot product includes both direction and length. Dividing by the two lengths leaves the cosine of the angle. If feature columns use different units, the choice of scale changes these comparisons. Decide what one unit represents before you measure distance.

Read the notation one piece at a time

The subscript in uᵢ means “entry i of u.” The symbol Σ means “add over all the entries.” A dot product of two two-entry vectors is therefore u₁v₁ + u₂v₂. Both vectors must have the same number of entries, and entries in the same position must represent the same feature. Multiplying action by comedy would answer a different question even if the code ran.

The subscript 2 in ‖u‖₂ names the Euclidean norm. Square each entry, add the squares, and take the square root. This is the Pythagorean theorem in two dimensions. Distance uses that same norm on a difference vector. For example, moving from (3, 4) to (6, 8) requires moving (3, 4), so the distance is 5.

Cosine similarity divides the dot product by both lengths. The angle θ is the angle between the two arrows. A cosine of 1 means the same direction, 0 means perpendicular, and −1 means opposite directions. A raw dot product also rewards length. Compare (3, 4) with itself and with (6, 8). The dot products are 25 and 50, while the two cosines are both 1.

Work it out

Let u = (3, 4), v = (6, 8), and w = (−4, 3). The first vector has length √(9 + 16) = 5. The second has length 10, and u · v = 18 + 32 = 50. The cosine is 50/(5 × 10) = 1. These two arrows point in the same direction even though the points at their ends are five units apart.

For w, the dot product is 3(−4) + 4(3) = 0. Both vectors have nonzero length, so zero dot product means a right angle. If one vector is zero, there is no angle to measure. The code rejects that input explicitly.

Three arrows from the origin. u is at (3, 4), v at (6, 8) along the same line, and w at (−4, 3) perpendicular to u.

Direction and magnitude. u and v have cosine 1, while u and w have cosine 0.

Run the Python lab

import numpy as np

def cosine(u, v):
    scale = np.linalg.norm(u) * np.linalg.norm(v)
    if scale == 0:
        raise ValueError("Cosine needs two nonzero vectors")
    return (u @ v) / scale

u = np.array([3., 4.])
v = np.array([6., 8.])
w = np.array([-4., 3.])

print(f"lengths: {np.linalg.norm(u):.0f}, {np.linalg.norm(v):.0f}")
print(f"u dot v: {u @ v:.0f}")
print(f"distance: {np.linalg.norm(u - v):.0f}")
print(f"cos(u,v): {cosine(u, v):.1f}")
print(f"cos(u,w): {cosine(u, w):.1f}")

assert np.isclose(cosine(u, v), 1)
assert np.isclose(cosine(u, w), 0)
try:
    cosine(u, np.zeros(2))
except ValueError:
    pass
else:
    raise AssertionError("Zero vector should be rejected")

Expected output

lengths: 5, 10
u dot v: 50
distance: 5
cos(u,v): 1.0
cos(u,w): 0.0

Read the lab as three different comparisons

The operator @ multiplies matching entries and adds them here because both arrays are one-dimensional. np.linalg.norm(u - v) first constructs the difference and then measures its length. The two calls to cosine test direction separately. The zero-vector assertion checks the assumption behind the division, so undefined direction does not silently enter a similarity ranking.

As a diagnostic, multiply the first coordinate of both (1, 1) and (1, −1) by 10. The dot product moves from 0 to 99 and the product of the lengths moves from 2 to 101. The cosine becomes 99/101. That is a change in the representation, even though both rows went through the same rescaling. When features use different units, decide whether to rescale them before choosing a distance or angle.

Try it yourself

  1. Replace v by −2u. Predict its cosine and distance from u before running the code.
  2. Use vectors (1, 1) and (1, −1). Multiply the first feature of both vectors by ten. What changes?

Check your work. For −2u, the cosine is −1 and the distance is 15. In the second exercise the original cosine is zero. After rescaling it becomes 99/101. The two-feature scale has changed the angle.

Further reading

NumPy documentation

Subject contents · Week 2