Similarity and Structure: Distances, Eigenvectors and the SVD
Measure how alike two feature vectors are with dot products, norms, Euclidean distance and cosine similarity, then find the dominant directions of a dataset with eigenvectors and compress a matrix with a truncated SVD whose error you can predict.
Contentsand lesson path
On this page
- Why it matters
- Dot products, norms and two ways to compare vectors
- Distances need features on comparable scales
- Eigenvectors: the directions in which data varies
- The SVD and low-rank approximation
- Check your understanding
- Apply it
- Review prompt
Lessons of Linear Algebra & Calculus for ML
- Data as Arrays: Vectors, Matrices and Shapes Concept · 20 min
- Similarity and Structure: Distances, Eigenvectors and the SVD Concept · 30 min
- From Slopes to Gradients: Derivatives, the Chain Rule and Jacobians Concept · 25 min
- Worked Example: Checking a Gradient Numerically Worked example · 15 min
- Lab: Fit a Linear Model with Hand-Written Gradient Descent Lab · 30 min
- Check: Shapes, Gradients and Step Sizes Knowledge check · 10 questions
What you will learn
- Compute dot products, norms, distances and cosine similarity and explain what each measures between feature vectors.
- Use eigendecomposition and the singular value decomposition to find a matrix's dominant directions, and build a truncated-SVD low-rank approximation whose reconstruction error you can explain by rank.
01. Why it matters
Many ML methods rest on one question: how similar are two examples? A k-nearest-neighbours model predicts from the most similar training rows, a search engine ranks documents by their similarity to a query, and a clustering algorithm groups rows that are close together. The answer depends on how you measure similarity, and the wrong measure gives confident but meaningless neighbours.
A second question is about the whole dataset: in which directions does it actually vary? Real data often has dozens of columns that move together, such as height, weight and shoe size. Eigenvectors and the singular value decomposition (SVD) find those few dominant directions. That is the basis of principal component analysis (PCA), image compression and many recommender systems.
This lesson builds both ideas with small NumPy examples (Python 3.12, NumPy 2.5, scikit-learn 1.9). It builds on Data as Arrays: shapes and the @ operator.
02. Dot products, norms and two ways to compare vectors
The dot product of two vectors multiplies them element by element and adds the results: [1, 2] · [3, 4] = 1·3 + 2·4 = 11. It is large when both vectors have big values in the same positions. On its own it mixes two things, direction and length, so a long vector gets large dot products with everything.
A norm measures the length of one vector. The L2 norm (Euclidean norm) is the square root of the sum of squares, the straight-line length you know from geometry: the vector [3, 4] has L2 norm 5. The L1 norm adds the absolute values, so [3, 4] has L1 norm 7; it is the distance you would walk on a grid of streets. np.linalg.norm(v) gives the L2 norm and np.linalg.norm(v, ord=1) the L1 norm.
From these come two common ways to compare vectors a and b:
- Euclidean distance is the L2 norm of the difference, ‖a − b‖. It is 0 for identical vectors and grows with any difference, in direction or in length.
- Cosine similarity is a · b / (‖a‖ ‖b‖), the cosine of the angle between the vectors. It is 1 when they point the same way, 0 when they are at right angles and −1 when they point in opposite directions. Dividing by the lengths removes the effect of length completely.
The example compares word counts. A short note and a long article about machine learning use the same words in similar proportions, while a gardening note uses different words.
import numpy as np
# Word counts for the words ["model", "data", "garden"] in three documents
short_ml = np.array([2.0, 1.0, 0.0]) # a short note about machine learning
long_ml = np.array([10.0, 6.0, 1.0]) # a long article on the same topic
gardening = np.array([0.0, 1.0, 3.0]) # a short note about gardening
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
print("dot(short, long):", short_ml @ long_ml)
print("L2 norm of long:", round(np.linalg.norm(long_ml), 3))
print("L1 norm of long:", np.linalg.norm(long_ml, ord=1))
for name, other in [("long_ml", long_ml), ("gardening", gardening)]:
dist = np.linalg.norm(short_ml - other)
print(f"short_ml vs {name:<9} euclidean {dist:6.3f} "
f"cosine {cosine(short_ml, other):.3f}")dot(short, long): 26.0
L2 norm of long: 11.705
L1 norm of long: 17.0
short_ml vs long_ml euclidean 9.487 cosine 0.993
short_ml vs gardening euclidean 3.606 cosine 0.141By Euclidean distance the gardening note is closer, because it is short too. Cosine similarity sees that the two machine-learning documents point in almost the same direction (0.993) and that the gardening note does not (0.141). This is why text search and embedding search usually rank by cosine similarity: the length of a document says little about its topic. Euclidean distance is the better choice when the length carries meaning, for example when the vector holds physical measurements.
A useful connection: if you first normalise every vector to length 1, then ‖a − b‖² = 2 − 2·cos(a, b). On unit vectors the two measures carry the same information, which is why many vector databases normalise embeddings once and then use the faster of the two.
03. Distances need features on comparable scales
A distance adds up differences across all features, so a feature measured in large units dominates the sum. Income in pounds varies by tens of thousands; age in years varies by tens. A difference of 37 years then counts for less than a difference of £1,000. The fix is to standardise each column first: subtract its mean and divide by its standard deviation, so that every feature is measured in "standard deviations from average".
import numpy as np
# Customers: [age in years, yearly income in pounds]
X = np.array([
[25.0, 30_000], # 0: the customer we look up
[62.0, 31_000], # 1: very different age, similar income
[27.0, 36_000], # 2: similar age, a bit more income
[45.0, 80_000], # 3
])
def nearest(data, i):
dists = np.linalg.norm(data - data[i], axis=1) # distance to every row
dists[i] = np.inf # ignore the row itself
return int(np.argmin(dists)), dists[1:].round(2)
print("raw nearest, distances to 1-3:", *nearest(X, 0))
Z = (X - X.mean(axis=0)) / X.std(axis=0) # standardise each column
print("standardised nearest, distances to 1-3:", *nearest(Z, 0))raw nearest, distances to 1-3: 1 [ 1000.68 6000. 50000. ]
standardised nearest, distances to 1-3: 2 [2.46 0.32 2.75]On raw values the nearest neighbour of a 25-year-old is a 62-year-old, because the age gap is invisible next to income. After standardising, customer 2 wins. Notice that switching to cosine similarity would not solve this: cosine removes the length of the whole vector, but inside the vector income still outweighs age. Neither would the L1 distance, which only softens the imbalance. Put features on comparable scales first, then choose the measure. In scikit-learn, StandardScaler does this step and remembers the training means and deviations for new data.
04. Eigenvectors: the directions in which data varies
A matrix multiplied by a vector usually turns it into a vector pointing somewhere else. An eigenvector v of a square matrix C is special: C turns it into a multiple of itself, C v = λ v. The number λ is the matching eigenvalue.
For data analysis the important matrix is the covariance matrix of the features. Entry (i, j) says how much features i and j vary together; the diagonal holds each variance. A covariance matrix is symmetric, so its eigenvectors are at right angles to each other and its eigenvalues are real and not negative. Each eigenvector is a direction in feature space, and its eigenvalue is the variance of the data along that direction. Sorting eigenvalues from large to small sorts directions from most to least informative. The total of the eigenvalues equals the total variance, so each eigenvalue divided by the total is the share of variance that direction explains. This is exactly what PCA reports.
The example generates 500 people whose weight and shoe size both depend on height, standardises the three columns and finds the eigenvectors with np.linalg.eigh, the NumPy routine for symmetric matrices.
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(7)
n = 500
height = rng.normal(170, 10, n)
weight = 0.9 * height - 85 + rng.normal(0, 6, n) # correlated with height
shoe = 0.15 * height + 13 + rng.normal(0, 1.5, n) # correlated with height
X = np.column_stack([height, weight, shoe])
Z = (X - X.mean(axis=0)) / X.std(axis=0, ddof=1) # ddof=1 matches np.cov
C = np.cov(Z, rowvar=False) # 3 x 3 covariance matrix
values, vectors = np.linalg.eigh(C) # eigh: for symmetric matrices
order = np.argsort(values)[::-1] # largest eigenvalue first
values, vectors = values[order], vectors[:, order]
print("eigenvalues:", values.round(3), "sum:", values.sum().round(3))
print("explained share:", (values / values.sum()).round(3))
top = vectors[:, 0] * np.sign(vectors[0, 0]) # an eigenvector's sign is arbitrary
print("top direction:", top.round(3))
v = vectors[:, 0]
print("check C v = lambda v:", np.allclose(C @ v, values[0] * v))
pca = PCA().fit(Z)
print("PCA explained_variance_ratio_:", pca.explained_variance_ratio_.round(3))eigenvalues: [2.349 0.501 0.15 ] sum: 3.0
explained share: [0.783 0.167 0.05 ]
top direction: [0.616 0.585 0.527]
check C v = lambda v: True
PCA explained_variance_ratio_: [0.783 0.167 0.05 ]Three standardised features have a total variance of 3, and one direction holds 2.349 of it: 78% of all the variation. That direction is not one of the original columns. It is a mix of all three with similar weights, which you can read as "overall body size". The smallest eigenvalue, 0.15, marks a direction in which the data hardly varies; dropping it loses about 5% of the variance. If the three features were uncorrelated, every eigenvalue would be close to 1 and no direction would stand out.
05. The SVD and low-rank approximation
Eigenvectors need a square matrix. The singular value decomposition works for any matrix: it writes an m × n matrix R as U · diag(s) · Vᵀ. The columns of U and the rows of Vᵀ are directions at right angles to each other, and the singular values in s are non-negative numbers sorted from largest to smallest. Each singular value says how much of the matrix lies along its pair of directions. If you centre the columns of a data matrix first, the rows of Vᵀ are its PCA directions and s² / (n − 1) are the eigenvalues of its covariance matrix (for the standardised Z of the previous section, exactly the values printed there).
Keeping only the first k singular values and their directions gives a rank-k approximation R_k. The rank of a matrix is the number of independent directions it contains, so R_k is built from k directions only. The Eckart–Young theorem says that no other rank-k matrix is closer to R, measured by the Frobenius norm (the square root of the sum of all squared entries). It also gives the error exactly: ‖R − R_k‖ equals the square root of the sum of the squares of the singular values you discarded. You can predict the error of every rank from s alone, before building any approximation.
The example builds a 40 × 30 "ratings" matrix from 3 hidden tastes plus noise, then compares the measured error with the prediction from s.
import numpy as np
rng = np.random.default_rng(0)
# A 40 x 30 "ratings" matrix: 3 hidden tastes, plus a little noise
users = rng.normal(size=(40, 3))
items = rng.normal(size=(3, 30))
R = users @ items + 0.3 * rng.normal(size=(40, 30))
U, s, Vt = np.linalg.svd(R, full_matrices=False)
print("shapes:", U.shape, s.shape, Vt.shape)
print("first 6 singular values:", s[:6].round(2))
for k in [1, 2, 3, 4, 6, 10]:
R_k = U[:, :k] * s[:k] @ Vt[:k] # keep the k largest directions
error = np.linalg.norm(R - R_k) # Frobenius norm of what is left
predicted = np.sqrt(np.sum(s[k:] ** 2)) # from the discarded values only
stored = U[:, :k].size + k + Vt[:k].size
print(f"rank {k:2d}: error {error:6.3f} from s {predicted:6.3f} "
f"numbers stored {stored:4d} of {R.size}")shapes: (40, 30) (30,) (30, 30)
first 6 singular values: [39.41 31.72 22.75 3.52 2.88 2.79]
rank 1: error 40.149 from s 40.149 numbers stored 71 of 1200
rank 2: error 24.609 from s 24.609 numbers stored 142 of 1200
rank 3: error 9.379 from s 9.379 numbers stored 213 of 1200
rank 4: error 8.691 from s 8.691 numbers stored 284 of 1200
rank 6: error 7.710 from s 7.710 numbers stored 426 of 1200
rank 10: error 5.911 from s 5.911 numbers stored 710 of 1200U[:, :k] * s[:k] scales each kept column of U by its singular value through broadcasting, and @ Vt[:k] rebuilds the matrix. The measured error matches the prediction from the discarded singular values at every rank.
The first three singular values are large and the rest are small, so the error falls steeply up to rank 3 and then flattens: three directions hold the structure, and the remaining 27 mostly hold noise. Extra rank still lowers the error a little, because the discarded values are small, not zero; error on the matrix you approximate can only go down as k grows. At rank 3 you store 213 numbers instead of 1,200. Choosing k where the curve bends is the usual compromise between size and accuracy, and on held-out data a smaller k often predicts better, because it ignores the noise.
06. Check your understanding
07. Apply it
The practice project for this skill ends by compressing an image or ratings matrix with truncated SVD. Start it now.
- Load the 8 × 8 digit images with
from sklearn.datasets import load_digitsandX = load_digits().data(shape (1797, 64)). - Compute the SVD, predict the reconstruction error for every rank from 1 to 64 using only
s, and check five of the predictions againstnp.linalg.norm(X - X_k). - Plot error against rank with Matplotlib, pick the rank where the curve bends, and note how many numbers that rank stores compared with the full matrix.
- Bonus: centre the columns, compute the SVD again and confirm that
s**2 / (n - 1)equalsPCA().fit(X).explained_variance_.
08. Review prompt
Without looking back, explain: what cosine similarity ignores that Euclidean distance does not, and when each is the better choice; why features must be on comparable scales before you compute distances; what an eigenvalue of a covariance matrix measures; and how to predict the Frobenius error of a rank-k truncated SVD from the singular values alone.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.