skip to content

Linear Algebra for ML

The vector and matrix machinery ML is written in: multiplication, rank, eigendecomposition, SVD, norms and projections. Interviewers probe it to see whether you know what embeddings and PCA do.

on this pageshow

explore

questions

page 1 of 2

How does cosine similarity differ from Euclidean distance between two vectors?

level: juniorimportance: must knowfreq 80%

answer

  1. angle versus gap
  2. one is scale invariant
  3. dot product over both lengths
  4. same word mix, different document length
  5. unit vectors make the two agree

basics

~20 s

Cosine similarity measures only the angle between two vectors; Euclidean distance also reacts to their magnitudes. Two term-count vectors with the same word mix but different document lengths score cosine 1.0 while sitting far apart in Euclidean distance.

solid answer

~50 s

Cosine similarity is `cos(theta) = (a . b) / (||a|| * ||b||)` — the dot product divided by both lengths, so it depends only on direction. It runs from 1 (same direction) through 0 (orthogonal) to -1 (opposite direction). Euclidean distance is `||a - b||`, which grows when either vector gets longer even if the direction is unchanged. Take raw term counts `a = (1, 2, 1)` for a short document and `b = (3, 6, 3)` for a longer one with the same word mix: cosine similarity is exactly 1.0, but the Euclidean distance is `||(2, 4, 2)|| = sqrt(24)`, about 4.9. Use cosine when only composition or direction is meaningful and magnitude is an artefact of size; use Euclidean when magnitude carries real information. If both vectors are first scaled to unit length the two agree, since `||a - b||^2 = 2 - 2 * cos(theta)`.

go deeper

for a junior

Be ready to write both formulas from memory and say in one line what each ignores. Knowing that cosine looks at angle and Euclidean looks at position is the answer most screens are checking for.

for a middle

Expect to prove the scale invariance rather than assert it, and to show that on unit-length vectors the squared distance equals 2 minus twice the cosine, so the two rankings coincide.

for a senior

Show judgment about when magnitude is signal and when it is an artefact of size, and flag the trap that cosine removes per-vector length but never fixes coordinates measured in mismatched units.

for a principal

Own the framing decision: whether magnitude should influence similarity at all is a modelling choice with downstream consequences, and it should be stated explicitly rather than inherited from whatever the first implementation happened to use.

## The two quantities Given two real vectors `a` and `b` of the same dimension, there are two natural ways to ask how alike they are. **Euclidean distance** is the length of the difference: `d(a, b) = ||a - b|| = sqrt(sum over i of (a_i - b_i)^2)` It answers *how far apart are these two points*. Smaller is more similar; the minimum is 0, and there is no upper bound. **Cosine similarity** is the dot product normalised by both lengths: `cos(theta) = (a . b) / (||a|| * ||b||)`, where `a . b = sum over i of a_i * b_i` It answers *do these two arrows point the same way*. Larger is more similar; for real vectors it always lies in `[-1, 1]`, with 1 for the same direction, 0 for perpendicular vectors, and -1 for exactly opposite directions. It is undefined when either vector is the zero vector, because you would divide by zero. ## Where they disagree The difference is entirely about magnitude. Cosine similarity is **scale invariant**: multiply `a` by any positive number `c` and both `a . b` and `||a||` scale by `c`, so the ratio is unchanged. Euclidean distance has no such property — stretching one vector moves it away from the other. The canonical demonstration uses raw term counts. Suppose a short document has counts `a = (1, 2, 1)` over three words, and a longer document with exactly the same word mix has `b = (3, 6, 3)`. Then: - `a . b = 3 + 12 + 3 = 18` - `||a|| = sqrt(1 + 4 + 1) = sqrt(6)`, and `||b|| = sqrt(9 + 36 + 9) = sqrt(54) = 3 * sqrt(6)` - `cos(theta) = 18 / (sqrt(6) * 3 * sqrt(6)) = 18 / 18 = 1.0` Cosine calls them identical, which is what you want if the question is *are these about the same thing*. Euclidean distance calls them quite different: `b - a = (2, 4, 2)`, so `d = sqrt(4 + 16 + 4) = sqrt(24)`, roughly 4.9. Here the distance is mostly measuring that one document is three times as long. ## Sign and range in practice For vectors with only non-negative entries — raw counts, frequencies, non-negative features — every product `a_i * b_i` is at least 0, so the dot product is non-negative and cosine similarity lands in `[0, 1]`. Negative cosine requires components of opposite sign, which appears once values have been centred or can be negative for other reasons. Candidates who assert *cosine is always between 0 and 1* have quietly assumed non-negative data. People often speak of **cosine distance**, usually defined as `1 - cos(theta)`. That reverses the ordering so that smaller means more similar, which is convenient when a system expects a dissimilarity. It is a transformation of the similarity, not a new measurement. ## The unit-length bridge If both vectors are rescaled to length 1 — replace `a` with `a / ||a||` — then `||a|| = ||b|| = 1` and the cosine formula collapses to the plain dot product: `cos(theta) = a . b`. That is why normalisation is such a common preprocessing step: after it, one cheap dot product gives you the angle. Normalisation also reconciles the two measures. Expanding the squared distance between unit vectors: `||a - b||^2 = ||a||^2 + ||b||^2 - 2 * (a . b) = 1 + 1 - 2 * cos(theta) = 2 - 2 * cos(theta)` So `||a - b|| = sqrt(2 - 2 * cos(theta))`, which strictly decreases as cosine increases. On unit-length vectors, ranking by Euclidean distance and ranking by cosine similarity produce the *same order*. The two only diverge when lengths are allowed to vary. ## Choosing between them Ask what the magnitude of your vector means. - If length is an artefact — document length, how many events a user generated, the units a feature happens to be recorded in — cosine similarity strips it out and compares composition. - If length is signal — a physical measurement, a spend amount, a count you genuinely care about — Euclidean distance keeps that information and cosine throws it away. A common failure is applying cosine to features on wildly different scales without any standardisation. Cosine removes the *overall* length of each vector, but it does nothing about one coordinate dominating because it is measured in a larger unit; that coordinate still drives the dot product. Scale invariance per vector is not the same as per-feature comparability.

  • What happens to cosine similarity if you multiply one of the two vectors by 10?
    Nothing. Both `a . b` and `||a||` scale by 10, so the ratio is unchanged — cosine similarity is invariant to multiplication by any positive scalar. A negative scalar is different: it reverses the direction, so multiplying by -10 flips the sign of the similarity. Euclidean distance, by contrast, changes a great deal under either.
  • If both vectors are rescaled to unit length, does Euclidean distance rank pairs the same way as cosine similarity?
    Yes. For unit vectors, `||a - b||^2 = 2 - 2 * (a . b)`, and `a . b` is exactly the cosine. Distance is therefore a strictly decreasing function of cosine similarity, so the two produce identical orderings — only the scores differ. This equivalence is why normalisation is often applied before a distance-based comparison.
  • Can cosine similarity be negative between two vectors of raw word counts?
    No. Counts are non-negative, so every term `a_i * b_i` in the dot product is at least 0 and the similarity lies in `[0, 1]`; the worst case is 0, meaning the two documents share no words. Negative values need coordinates of opposite sign, which only arises once the data can take negative values.

Cosine similarity is a compass bearing: two hikers heading due north match perfectly whether one walked one kilometre or ten. Euclidean distance is the gap between where they ended up, so the ten-kilometre hiker looks far away.

saying these in an interview costs you the question

  • Claims cosine similarity changes when one vector is scaled up
  • Says cosine similarity is always between 0 and 1 for any real vectors
  • Reports the raw dot product as similarity without dividing by the norms
  • Treats a higher cosine value as meaning greater distance
  • Thinks cosine similarity fixes features being on different units

context

open as a page

What does it mean for a vector to be an eigenvector of a matrix A?

level: juniorimportance: must knowfreq 84%

basics

~20 s

A nonzero vector v is an eigenvector of A when Av = lambda v. Multiplying by A leaves v on its own line through the origin, only stretching, shrinking or flipping it; the scalar lambda is that scale factor.

open as a page

What does a determinant of zero tell you about a square matrix?

level: juniorimportance: must knowfreq 76%

basics

~20 s

A zero determinant means the matrix is singular: no inverse exists. For a 2x2 matrix [[a, b], [c, d]] the determinant is ad - bc, so ad - bc = 0 is the exact test for non-invertibility.

open as a page

For the matrix product AB, what shapes must A and B have, and what shape is the result?

level: juniorimportance: must knowfreq 86%

basics

~20 s

Matrix multiplication needs matching inner dimensions: if A is m x n and B is n x p, then AB is m x p. Entry (i,j) is the dot product of row i of A with column j of B.

open as a page

When does the linear system Ax = b have no solution, exactly one, or infinitely many?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Run Gaussian elimination on the augmented matrix. A row that is all zeros on the left but nonzero on the right means no solution. Otherwise, one pivot per unknown means exactly one solution; any free unknown means infinitely many.

open as a page

In a feature matrix, what does it mean for the columns to be linearly dependent?

level: juniorimportance: must knowfreq 60%

basics

~20 s

Linearly dependent columns means one column equals a weighted combination of the others, adding no new direction. A table holding hours_weekday, hours_weekend and their exact total is the classic case; that matrix is rank deficient.

open as a page

What does the singular value decomposition A = U S V^T tell you about a matrix A?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Every real matrix factors as A = U S V^T. U and V hold orthonormal directions in the output and input spaces, S is diagonal with non-negative singular values in descending order, and the number of nonzero ones equals the rank.

open as a page

How do the L1, L2 and L-infinity norms of a vector differ?

level: juniorimportance: must knowfreq 80%

basics

~20 s

All three measure a vector's size differently. L1 adds the absolute values of the coordinates, L2 is the square root of the sum of squares, and L-infinity is the largest absolute coordinate. For (3, 4) they give 7, 5 and 4.

open as a page

How do you find the eigenvalues of the matrix [[2,1],[1,2]] by hand?

level: middleimportance: must knowfreq 68%

basics

~20 s

Solve det(A - lambda I) = 0. For [[2,1],[1,2]] that is (2 - lambda)^2 - 1 = 0, giving lambda = 3 and 1. Substituting each back into (A - lambda I)v = 0 yields eigenvectors (1,1) and (1,-1).

open as a page

Why can the matrix products AB and BA differ, even when both are defined?

level: middleimportance: must knowfreq 71%

basics

~20 s

A matrix product is a composition of linear maps, and composition depends on order. In AB the right factor acts first, so rotating then stretching is a different transformation from stretching then rotating. Only special pairs commute.

open as a page

How do you solve an overdetermined system Ax = b when no exact solution exists?

level: middleimportance: must knowfreq 66%

basics

~20 s

Choose the x that makes the residual b - Ax as short as possible instead of demanding equality. That least-squares x satisfies A transpose A x = A transpose b, a small square system that always has a solution.

open as a page

What does the rank-nullity theorem give for a 5x3 matrix of rank 2?

level: middleimportance: must knowfreq 55%

basics

~20 s

Rank-nullity says rank plus nullity equals the number of columns. A 5x3 matrix of rank 2 therefore has nullity 3 - 2 = 1: the vectors it sends to zero form a line through the origin in three-dimensional space.

open as a page

Why is the truncated SVD the best rank-k approximation of a matrix?

level: middleimportance: must knowfreq 62%

basics

~20 s

The Eckart-Young theorem guarantees it: keeping the k largest singular values and their vectors minimizes the approximation error over all matrices of rank at most k, in both Frobenius and spectral norm. The discarded singular values fix the error exactly.

open as a page

Why does the L1 norm push coordinates to exactly zero while the L2 norm only shrinks them?

level: middleimportance: must knowfreq 68%

basics

~20 s

The L1 unit ball is a diamond with corners on the coordinate axes, so a constrained solution tends to land on a corner where some coordinates are exactly zero. The round L2 ball has no corners, so it only shrinks.

open as a page

Why can coordinates in an orthonormal basis be read off with dot products alone?

level: middleimportance: should knowfreq 42%

basics

~20 s

Because the basis vectors are mutually perpendicular and of unit length, dotting a vector with one basis vector cancels every other term and leaves that coordinate directly. No system of equations has to be solved.

open as a page

How do you compute the orthogonal projection of one vector b onto another vector a?

level: middleimportance: should knowfreq 55%

basics

~20 s

The projection of b onto a is (a . b / a . a) times a: scale a by the dot product of a and b over a with itself. The residual, b minus that projection, is perpendicular to a.

open as a page

What do the eigenvectors of a 2x2 covariance matrix represent geometrically?

level: middleimportance: should knowfreq 56%

basics

~20 s

They are the principal axes of the data's elliptical cloud: orthogonal directions along which the data spreads independently. Each eigenvalue is the variance measured along its own eigenvector, and the eigenvalues sum to the total variance, the matrix trace.

open as a page

Why is the shear matrix [[1,1],[0,1]] not diagonalizable as A = P D P^-1?

level: middleimportance: should knowfreq 50%

basics

~20 s

Its characteristic equation (1 - lambda)^2 = 0 repeats lambda = 1, but the eigenspace is only the line through (1,0). One independent eigenvector instead of two means no eigenbasis, so no invertible P exists: the matrix is defective.

open as a page

Why does det(AB) equal det(A) times det(B) for square matrices?

level: middleimportance: should knowfreq 46%

basics

~10 s

Because the determinant is a volume scaling factor, and applying B and then A scales volume by det(B) and then by det(A). Scaling factors multiply, so det(AB) = det(A)det(B).

open as a page

Geometrically, what does the determinant of a 2x2 matrix measure?

level: middleimportance: should knowfreq 58%

basics

~20 s

The determinant is the signed area scaling factor of the map: the unit square is sent to a shape whose area is the absolute value of the determinant. A negative sign means orientation was flipped.

open as a page

Why does the trace satisfy tr(AB) = tr(BA) even when AB and BA differ?

level: middleimportance: should knowfreq 38%

basics

~20 s

The trace is the sum of a square matrix's diagonal entries, and both tr(AB) and tr(BA) expand to the same double sum over every pair of entries. The order of summation changes, so the totals match.

open as a page

What does the matrix-vector product Ax compute in terms of the columns of A?

level: middleimportance: should knowfreq 56%

basics

~20 s

Ax is a linear combination of the columns of A, weighted by the entries of x. Applying A to the basis vector with a single 1 in slot j returns column j, so the columns are where the axes go.

open as a page

Why does the transpose of a matrix product equal B^T A^T rather than A^T B^T?

level: middleimportance: should knowfreq 47%

basics

~20 s

Transposing swaps each matrix's row and column counts, so the factors must reverse for the shapes to line up. Entry (i,j) of (AB)^T is entry (j,i) of AB, which is row i of B^T dotted with column j of A^T.

open as a page

Why solve Ax = b with an LU factorization instead of computing the inverse of A?

level: middleimportance: should knowfreq 48%

basics

~20 s

Factoring A into lower and upper triangular factors costs about a third of what forming the inverse costs and is more accurate. It is also reusable: each new right-hand side then needs only two cheap triangular solves.

open as a page

How do the singular values of a matrix A relate to the eigenvalues of A^T A?

level: middleimportance: should knowfreq 52%

basics

~20 s

The singular values of A are the square roots of the eigenvalues of A^T A, which are always real and non-negative. The eigenvectors of A^T A are the right singular vectors, the columns of V.

open as a page

What is the Frobenius norm of a matrix and how does it relate to the vector L2 norm?

level: middleimportance: should knowfreq 44%

basics

~20 s

The Frobenius norm is the square root of the sum of a matrix's squared entries. It is the L2 norm of the matrix flattened into one vector, and it is the usual measure of a weight or residual matrix's size.

open as a page

How do eigenvalues distinguish a positive-definite matrix from a merely PSD one?

level: seniorimportance: should knowfreq 46%

basics

~20 s

For a symmetric matrix, positive definite means every eigenvalue is strictly greater than zero; positive semidefinite means every eigenvalue is greater than or equal to zero. A zero eigenvalue is exactly what separates them, and it makes the matrix singular.

open as a page

Solving Ax = b gives wildly different x for tiny changes in b - what is going on?

level: seniorimportance: should knowfreq 44%

basics

~20 s

The matrix is ill-conditioned, not the solver buggy. Its condition number - how much a relative change in b is magnified in x - is large, so noise in the last digits swings the answer.

open as a page

Two feature columns correlate at 0.999 - is that matrix rank deficient?

level: seniorimportance: should knowfreq 38%

basics

~20 s

No. A correlation of 0.999 is not an exact linear identity, so the two columns stay independent and the matrix is full rank. It sits a hair from rank deficiency, so arithmetic on it behaves almost as badly.

open as a page

For a 3x3 matrix whose columns span only a plane, what does its nullspace say about solutions of Ax = b?

level: seniorimportance: should knowfreq 42%

basics

~20 s

A 3x3 matrix whose columns span only a plane has rank 2 and a one-dimensional nullspace. If b lies in that plane, solutions form a line: one particular solution plus any multiple of the nullspace vector. Otherwise none exist.

open as a page

showing 1–30 of 40