Linear Algebra and Numerical Computing Questions
The linear algebra and numerical methods that machine-learning and scientific code rest on. Covers vectors, matrices and their operations, eigenvalues and eigenvectors and their geometry, singular value decomposition and PCA as linear algebra (variance explained, randomized SVD), least squares, the normal equations and rank deficiency, matrix calculus and gradients of quadratic objectives, conditioning and its effect on solvers, feature scaling and gradient descent, ill-conditioned covariance matrices and the fixes for them (shrinkage, truncated pseudo-inverse, dimension reduction), floating-point error and numerically stable algorithms (compensated and pairwise summation), iterative methods such as power iteration, and the mathematics of optimization: convexity, smoothness, strong convexity, convergence rates of gradient descent, preconditioning, saddle points and Hessian tests for stationary points, Lagrange multipliers and KKT conditions. Questions are about deriving, computing and reasoning about precision and convergence. Probability and statistical inference, learning-theory bounds, neural-network training practice, and library API mechanics are covered elsewhere.
Why does standardizing input features usually speed up gradient-based training? Explain it in terms of the Hessian of a quadratic objective and the step size.
Sample Answer
The idea in plain words
Gradient descent takes steps of size (learning rate) times the negative gradient. How well it does depends on the curvature of the loss, which for a quadratic objective is the Hessian (the matrix of second derivatives). Directions in which the loss bends sharply force a small step; directions in which it is nearly flat then move very slowly under that small step. Features on very different scales create exactly that mix. Standardizing (subtract the mean, divide by the standard deviation) evens out the curvature along the feature axes, so one step size suits them far better (correlation between features can still leave some imbalance, which standardizing alone does not remove).
The mechanism
Take linear regression with weights w (n samples, matrix X of size n×d) and loss
f(w)=2n1∥Xw−y∥2,∇f(w)=n1X⊤(Xw−y),H=n1X⊤X
H is the Hessian (the same everywhere, since the loss is quadratic). Its diagonal entry for feature j is the mean of xj2, so a feature measured in dollars rather than thousands of dollars raises its entry by a million. An eigenvector of H is a direction along which H only stretches, and its eigenvalue is that stretch factor; for the loss it is the curvature along that direction, so along it the loss looks like a one-dimensional parabola 21λe2 in the distance e from the minimum. Let λmax and λmin be the largest and smallest eigenvalues of H (the sharpest and flattest curvature), and define the condition number κ=λmax/λmin.
Gradient descent with step size η obeys, in the eigenbasis of H (the coordinate system whose axes are the eigenvectors), an independent update for each direction i: the error along it is multiplied by (1−ηλi) each step.
- Stability needs ∣1−ηλi∣<1 for all i, so η<2/λmax. The steepest direction caps the step size.
- Progress along the flattest direction then has factor 1−ηλmin. With the natural choice η=1/λmax that factor is 1−1/κ. For large κ this is almost 1: thousands of steps per factor-of-e reduction. The number of steps to reduce the error by a fixed factor grows in proportion to κ.
Standardization brings κ down, to near 1 when the features are only weakly correlated, because every diagonal entry of H becomes 1 (the correlation matrix of the features), and the means no longer couple the columns.
A tiny case by hand
Take a loss whose Hessian is diag(1,100): curvature 1 along one axis and 100 along the other, so κ=100. The largest safe step is below 2/100, so use η=1/100. Each step multiplies the error along an axis by 1−ηλi, which is 0.99 on the flat axis and 0 on the sharp one.
import numpy as np
# Tiny quadratic: Hessian diag(1, 100) has curvature 1 along one direction and 100 along the other
lams = np.array([1.0, 100.0])
eta = 1 / lams.max() # step size 1/lambda_max = 0.01
err = np.array([1.0, 1.0]) # starting error along each direction
for step in range(1, 3):
err = (1 - eta * lams) * err
print(f"step {step}: error along the curvature-1 direction = {err[0]:.4f}, along the curvature-100 direction = {err[1]:.4f}")
print("per-step factor on the flat direction 1 - 1/kappa =", 1 - 1 / 100)
Output:
step 1: error along the curvature-1 direction = 0.9900, along the curvature-100 direction = 0.0000
step 2: error along the curvature-1 direction = 0.9801, along the curvature-100 direction = 0.0000
per-step factor on the flat direction 1 - 1/kappa = 0.99
The sharp direction is solved in one step while the flat one loses only 1 percent per step, so the flat direction sets the pace: about 230 steps to cut its error by a factor of 10 (since 0.99230≈0.1), whatever the sharp direction does. If the curvatures were equal, one step would solve both.
Centering is a separate effect from scaling. Take two columns that are mostly constant offsets, x1 = [9, 10, 11, 10] and x2 = [19, 20, 19, 22]. The off-diagonal entry of H is the mean of x1x2, which is dominated by the product of the means (10×20=200), so the raw columns look strongly coupled even though their fluctuations are small. Subtracting the means removes that coupling.
import numpy as np
x1 = np.array([9.0, 10.0, 11.0, 10.0])
x2 = np.array([19.0, 20.0, 19.0, 22.0])
X = np.column_stack([x1, x2])
for name, M in (("raw", X), ("centered", X - X.mean(0))):
H = M.T @ M / len(M)
print(name, "H =", np.round(H, 3).tolist(), " eigenvalues =", np.round(np.linalg.eigvalsh(H), 3))
Output:
raw H = [[100.5, 200.0], [200.0, 401.5]] eigenvalues = [ 0.7 501.3]
centered H = [[0.5, 0.0], [0.0, 1.5]] eigenvalues = [0.5 1.5]
The raw eigenvalues 0.7 and 501.3 give κ≈716 before any scaling; after centering, κ=3.
Worked example
Two features, a height in centimetres (mean 170, standard deviation 10) and an income in dollars (mean 50000, standard deviation 15000), with 1000 samples. The program reports the Hessian eigenvalues, the step size 1/λmax and the step count needed to shrink the slowest direction's error 1000-fold, for three versions of the inputs: raw, scaled to unit variance without centering, and fully standardized. Then it actually runs gradient descent for 40 steps on the raw and standardized versions and measures the distance to the exact least-squares solution.
import numpy as np
rng = np.random.default_rng(0)
n = 1000
# Two features on very different scales: height in centimetres, income in dollars
x1 = rng.normal(170.0, 10.0, size=n)
x2 = rng.normal(50000.0, 15000.0, size=n)
X = np.column_stack([x1, x2])
w_true = np.array([0.5, 0.0004])
y = X @ w_true + rng.normal(0, 1.0, size=n)
def hessian(X):
return X.T @ X / len(X) # Hessian of f(w) = ||Xw - y||^2 / (2n)
def gd(X, y, steps, lr):
w = np.zeros(X.shape[1])
for _ in range(steps):
w -= lr * X.T @ (X @ w - y) / len(X)
return w
def report(name, X, y):
H = hessian(X)
ev = np.linalg.eigvalsh(H)
lr = 1.0 / ev.max() # largest safe step is below 2/lambda_max; use 1/lambda_max
kappa = ev.max() / ev.min()
print(f"{name}: eigenvalues {ev[0]:.4g} and {ev[1]:.4g}, condition number {kappa:.4g}")
print(f" step size 1/lambda_max = {lr:.3e}, per-step factor on the flattest direction = {1 - 1/kappa:.6f}")
# the error along the flattest direction shrinks by (1 - lr*lambda_min) per step; steps to cut it 1000-fold:
steps = np.log(1e-3) / np.log(1 - lr * ev.min())
print(f" steps to cut the slow-direction error by 1000x: {steps:.0f}")
return lr
# Raw features (no standardization)
report("raw features", X, y)
# Scaled to unit variance but NOT centred: the feature means still couple the two columns
report("scaled, not centred", X / X.std(0), y)
# Standardized features (zero mean, unit variance); target centred to match
mu, sd = X.mean(0), X.std(0)
Xs = (X - mu) / sd
ys = y - y.mean()
lr = report("standardized", Xs, ys)
# Measured check: run gradient descent on standardized data for the predicted number of steps
w_hat = gd(Xs, ys, 40, lr)
w_ls = np.linalg.lstsq(Xs, ys, rcond=None)[0]
print("standardized: distance to least-squares solution after 40 steps:", f"{np.linalg.norm(w_hat - w_ls):.2e}")
# Same on raw features, with its own safe step size and 40 steps
H = hessian(X)
lr_raw = 1.0 / np.linalg.eigvalsh(H).max()
w_raw = gd(X, y, 40, lr_raw)
w_ls_raw = np.linalg.lstsq(X, y, rcond=None)[0]
print("raw: relative distance to least-squares solution after 40 steps:",
f"{np.linalg.norm(w_raw - w_ls_raw) / np.linalg.norm(w_ls_raw):.4f}")
Output:
raw features: eigenvalues 2524 and 2.723e+09, condition number 1.079e+06
step size 1/lambda_max = 3.672e-10, per-step factor on the flattest direction = 0.999999
steps to cut the slow-direction error by 1000x: 7453452
scaled, not centred: eigenvalues 0.9787 and 312.8, condition number 319.6
step size 1/lambda_max = 3.197e-03, per-step factor on the flattest direction = 0.996871
steps to cut the slow-direction error by 1000x: 2204
standardized: eigenvalues 0.9412 and 1.059, condition number 1.125
step size 1/lambda_max = 9.445e-01, per-step factor on the flattest direction = 0.111079
steps to cut the slow-direction error by 1000x: 3
standardized: distance to least-squares solution after 40 steps: 6.76e-15
raw: relative distance to least-squares solution after 40 steps: 1.0000
Reading the output:
- Raw. Condition number about 1.079e6, so the safe step is about 3.7e-10 and the slow direction needs about 7.45 million steps for a 1000-fold error reduction. After 40 real steps the weights are still at a relative distance of 1.0000 from the solution.
- Scaled but not centred. Unit variance alone brings κ down to about 320, and 2204 steps. The remaining conditioning comes from the large means, which make the two columns nearly parallel (both are mostly constant offsets, as in the tiny centering case above, where the off-diagonal entry of H is close to the product of the means). Centering is therefore not optional.
- Standardized. κ=1.125, the per-step factor on the slow direction is 0.111, about 3 steps cut its error 1000-fold, and 40 real steps reach the least-squares solution to within floating-point rounding (the printed 6.76e-15 is rounding noise, not a convergence rate: its digits change with the data, and the 40 steps are far more than the 3 the formula needs).
The step counts are the formula's predictions for the quadratic; only the last two lines of the output are measured runs.
Trade-offs, limits and mistakes
- A typical interview round asks for the condition-number argument and fitting the scaler on training data only; whitening, adaptive optimizers and normalization layers are deeper reading.
- Fit the scaler on training data only and reuse its mean and standard deviation on validation and test data; otherwise information leaks from the evaluation set.
- Correlated features stay ill-conditioned after standardizing: it fixes scale but not correlation. Whitening (rotating to uncorrelated features and then scaling each to variance 1, so the covariance becomes the identity) fixes both at the cost of an eigen-decomposition of the feature covariance, and is rarely done at large dimension.
- Adaptive optimizers such as Adam rescale the step per parameter, which compensates for per-feature scale to a degree, but not for correlation between features.
- Not every model needs it. Decision trees split on thresholds, so monotone rescaling does not change them. Distance-based methods and regularized models do care: a regularized model adds a penalty such as λ∥w∥2 that charges every weight the same rate, so a feature measured in large units needs a tiny weight and is barely penalized, while one in small units needs a large weight and is penalized heavily.
- Neural networks are not quadratic, so the analysis is a local picture near a minimum (the Hessian there) and an argument for well-scaled inputs and activations (the idea behind normalization layers such as batch norm and layer norm, which standardize activations inside the network), not a theorem about deep networks.
You fit a linear regression with an intercept and one-hot encode a categorical feature with all of its levels, and the solver complains the design matrix is singular. In linear-algebra terms (rank, column space, null space), what went wrong, what does it mean for the coefficients, and how do you fix it?
Sample Answer
The idea in plain words
A one-hot encoding with every level plus an intercept contains the same information twice. In every row exactly one level column is 1, so the level columns add up to the intercept column (a column of ones). One column is then a combination of the others, so the columns are linearly dependent, and the least-squares problem no longer has a single answer. The solver complains because the square matrix it must invert, the Gram matrix G=X⊤X (the table of dot products between every pair of columns of X), is singular: a singular matrix has no inverse, and that is exactly what happens when one column is a combination of the others. The predictions are still well defined, but the individual coefficients are not.
Three terms, each in half a sentence. The rank of a matrix is the number of linearly independent columns. The column space is the set of all vectors Xβ, that is, every prediction vector the model can produce. The null space is the set of vectors d with Xd=0, the coefficient changes that the predictions cannot see. (The letter d is used so it is not confused with the number of rows.)
What happens in linear-algebra terms
Let X have columns intercept, basic, plus, pro. Then intercept = basic + plus + pro, which says Xd=0 for d=(1,−1,−1,−1). A hand check on one row: a customer on the plus plan has the row (1,0,1,0), and 1⋅1+(−1)⋅0+(−1)⋅1+(−1)⋅0=0. Every row gives zero for the same reason: exactly one of its three level entries is 1, and that 1 cancels the intercept's 1. So:
- The null space is not empty, so the rank is 3, not 4. This is the rank-nullity theorem: the rank plus the dimension of the null space equals the number of columns, because each column direction either survives in the output or is flattened to zero, and the two counts add up to 4.
- The column space has dimension 3. The fitted values are the projection of y onto that column space, meaning the point of the space closest to y. A closest point is unique, just as the foot of the perpendicular from a point to a line in the plane is one point however the line is described, so predictions and residuals are unique.
- If β minimises the squared error, so does β+cd for every number c, because X(β+cd)=Xβ. There is a whole line of solutions. A tiny case shows it: with three customers (one on basic, two on plus) and columns intercept, basic, plus, the coefficient vectors (0,10,20) and (5,5,15) differ by 5(1,−1,−1) and give the same three predictions, as the first program below prints.
- The Gram matrix G=X⊤X satisfies Gd=X⊤(Xd)=0, so it has a zero eigenvalue and no inverse. An eigenvalue says how much a matrix stretches one special direction; zero means that direction is flattened to nothing, and a flattened direction cannot be undone, which is why there is no inverse. The singular values of X are the same kind of stretch factors for X itself (their squares are the eigenvalues of G). The normal equations Gβ=X⊤y (what you get by setting the gradient of the squared error to zero) have infinitely many solutions, and a solver that factorises or inverts G fails or returns noise.
A worked example with six customers
Three plans, two customers each, target is monthly usage. First the three-customer case from above, small enough to check by eye.
import numpy as np
# Three customers: one on basic, two on plus. Columns: intercept, basic, plus.
X = np.array([[1, 1, 0], [1, 0, 1], [1, 0, 1]], dtype=float)
b1 = np.array([0.0, 10.0, 20.0])
b2 = b1 + 5.0 * np.array([1.0, -1.0, -1.0]) # shifted along the null direction
print("rank:", np.linalg.matrix_rank(X), "of", X.shape[1], "columns")
print("b2 =", b2)
print("predictions with b1:", X @ b1)
print("predictions with b2:", X @ b2)
Output:
rank: 2 of 3 columns
b2 = [ 5. 5. 15.]
predictions with b1: [10. 20. 20.]
predictions with b2: [10. 20. 20.]
Now six customers. The next program builds the full-level design, shows the rank, the null vector, two different coefficient vectors with identical predictions, and the two standard fixes.
import numpy as np
# Six customers, one categorical feature "plan" with three levels, target = monthly usage
plan = np.array(["basic", "basic", "plus", "plus", "pro", "pro"])
y = np.array([10.0, 14.0, 20.0, 24.0, 31.0, 35.0])
levels = ["basic", "plus", "pro"]
onehot = np.array([[1.0 if p == lv else 0.0 for lv in levels] for p in plan])
X_full = np.column_stack([np.ones(6), onehot]) # intercept + all three levels
print("X_full shape:", X_full.shape, " rank:", np.linalg.matrix_rank(X_full))
print("singular values:", np.round(np.linalg.svd(X_full, compute_uv=False), 4))
# The null space: intercept column minus the three level columns is the zero vector
d = np.array([1.0, -1.0, -1.0, -1.0])
print("X_full @ [1,-1,-1,-1] =", X_full @ d)
# Normal equations on a singular matrix
G = X_full.T @ X_full
try:
G_inv = np.linalg.inv(G)
print("inv(G) returned a matrix; largest entry above 1e10:", bool(np.abs(G_inv).max() > 1e10))
except np.linalg.LinAlgError as e:
print("inv(G) raised LinAlgError:", e)
print("smallest eigenvalue of G is zero up to rounding:", bool(abs(np.linalg.eigvalsh(G)[0]) < 1e-12))
# Infinitely many solutions: the minimum-norm one, and the same one shifted along the null space
beta_min, _, rank, _ = np.linalg.lstsq(X_full, y, rcond=None)
beta_alt = beta_min + 5.0 * d
print("min-norm beta :", np.round(beta_min, 4))
print("shifted beta :", np.round(beta_alt, 4))
print("same predictions:", np.allclose(X_full @ beta_min, X_full @ beta_alt))
# Fix 1: drop one level (basic becomes the reference level)
X_drop = np.column_stack([np.ones(6), onehot[:, 1:]])
b_drop = np.linalg.solve(X_drop.T @ X_drop, X_drop.T @ y)
print("drop 'basic': rank", np.linalg.matrix_rank(X_drop), " beta (intercept, plus, pro) =", np.round(b_drop, 4))
print("group means (basic, plus, pro) =", [float(y[plan == lv].mean()) for lv in levels])
# Fix 2: drop the intercept, keep all levels
b_noint = np.linalg.solve(onehot.T @ onehot, onehot.T @ y)
print("no intercept: beta (basic, plus, pro) =", np.round(b_noint, 4))
print("fits identical:", np.allclose(X_drop @ b_drop, onehot @ b_noint) and np.allclose(X_drop @ b_drop, X_full @ beta_min))
Output:
X_full shape: (6, 4) rank: 3
singular values: [2.8284 1.4142 1.4142 0. ]
X_full @ [1,-1,-1,-1] = [0. 0. 0. 0. 0. 0.]
inv(G) returned a matrix; largest entry above 1e10: True
smallest eigenvalue of G is zero up to rounding: True
min-norm beta : [16.75 -4.75 5.25 16.25]
shifted beta : [21.75 -9.75 0.25 11.25]
same predictions: True
drop 'basic': rank 3 beta (intercept, plus, pro) = [12. 10. 21.]
group means (basic, plus, pro) = [12.0, 22.0, 33.0]
no intercept: beta (basic, plus, pro) = [12. 22. 33.]
fits identical: True
Reading it:
- The rank is 3 and the smallest singular value is 0 (the stretch factor along the flattened direction), so the fourth column adds nothing. Expect one singular value per column, with a zero last when the columns are dependent. Multiplying by (1,−1,−1,−1) gives the zero vector.
- Whether
invraises an error or returns a matrix of enormous entries depends on rounding; here it returned a matrix whose largest entry exceeds 1010. An invertible matrix built from small, well-scaled counts like these would have an inverse with entries of modest size, so entries that huge are rounding noise and show that G has no inverse. The check on the smallest eigenvalue says the same thing directly. - The minimum-norm solution has intercept 16.75 and the shifted one has 21.75, yet the predictions are identical. Which one a program reports is an accident of the solver.
- What is the same in both solutions: the difference plus minus basic is 10 in both (5.25−(−4.75) and 0.25−(−9.75)), pro minus basic is 21 in both, and intercept plus basic coefficient is 12 in both, the mean of the basic group. Quantities that do not change along the null direction are the identifiable ones (the data pin them to one value): group means and differences between levels.
What it means for the coefficients
Individual coefficients are not identified, so they cannot be interpreted and their standard errors are meaningless. A coefficient's standard error is the typical amount it would move if you refit on fresh data; along the null direction the data say nothing, so that wobble is unbounded. Predictions, residuals and R-squared are fine. Some packages detect the dependency and silently drop or zero a column; others report a singular-matrix error. Both are signals that the encoding is redundant, not that the data is bad.
Fixes
Fixes 1 and 2 are the standard ones in an interview, and dropping one level is the everyday answer. Constraints and penalties (fix 3) are deeper material that a follow-up question may reach.
- Drop one level (reference coding). Keep the intercept and K−1 dummies. The intercept becomes the mean of the reference level (12) and each coefficient is a difference from it (10 and 21). The fit is identical whichever level is dropped; only the meaning of the coefficients moves. Choose a common, meaningful level as the reference so the differences have small standard errors.
- Drop the intercept. Keep all K level columns. Coefficients are the group means (12, 22, 33). With a second categorical feature you still must drop one of its levels, because its columns also add up to a column of ones.
- Constrain or penalise (deeper material). Effect coding forces the level coefficients to sum to zero and so picks one point on the line of solutions. A ridge penalty adds λI with λ>0 to G, which lifts the zero eigenvalue to λ and makes the answer unique, at the price of shrinking coefficients. Minimum-norm least squares (the solution with the smallest coefficient vector length, which is what
numpy.linalg.lstsqreturns) is the limit of ridge as the penalty goes to zero.
Common mistakes
- Saying the model "predicts badly". It predicts exactly as well as the reduced model.
- Treating exact dependence and near dependence alike. Exact dependence means no unique answer; near dependence gives a unique but very noisy answer (a conditioning problem: the answer exists but moves a lot when the data change slightly).
- Reading the coefficient of "plus" after dropping "basic" as the effect of plus alone. It is the effect of plus compared with basic.
Users move between the pages of a product according to a transition matrix. Show that the long-run share of users on each page is an eigenvector of that matrix, explain what guarantees it exists and is unique, and explain why PageRank adds a damping factor.
Sample Answer
The short answer
Put the users' distribution over pages in a row vector x (entry j is the share of users on page j). One click moves it to xP, where P is the transition matrix: entry Pij is the probability that a user on page i goes next to page j, so every row sums to 1 (a row-stochastic matrix; rows are the "from" pages throughout). This model is a Markov chain: the next page depends only on the current page, not on how the user got there. A stationary distribution π is a distribution that one more click leaves unchanged:
πP=π,πj≥0,j∑πj=1That is exactly the statement "π is a left eigenvector of P with eigenvalue 1" (an eigenvector is a direction a matrix only stretches, and the eigenvalue is the stretch factor; "left" means it multiplies from the left; equivalently π⊤ is an ordinary eigenvector of P⊤). It exists because P1=1 (each row sums to 1, so the all-ones vector has eigenvalue 1, and P and P⊤ share eigenvalues). It is unique, and the shares converge to it from any starting distribution, when the chain is irreducible (every page can be reached from every page by following clicks) and aperiodic (the chain does not cycle with a fixed period). PageRank adds a damping factor because the web violates these conditions: it has pages with no outgoing links and separate clusters, and damping repairs all of it in one move.
Why the eigenvector is the long-run share
Three facts about a row-stochastic P:
- Eigenvalue 1 exists (P1=1, above).
- No eigenvalue is larger than 1 in magnitude: ∥Pv∥∞≤∥v∥∞ because each entry of Pv is an average of entries of v.
- The Perron-Frobenius theorem says a matrix with non-negative entries has a non-negative eigenvector for its largest eigenvalue, and if the matrix is irreducible that eigenvalue is simple (appears once) and its eigenvector can be taken strictly positive. The intuition: multiplying a vector with non-negative entries by a non-negative matrix can never create a negative entry, so repeated multiplication cannot flip signs, and the direction it settles on has non-negative entries. For P the largest eigenvalue is 1, so an irreducible chain has exactly one stationary distribution, with every page having positive share.
If the chain is also aperiodic, every other eigenvalue has magnitude strictly below 1. Writing the start distribution in the eigenvectors of P (assuming P is diagonalizable, meaning it has a full set of independent eigenvectors vi), x0Pk=π+∑i≥2ciλikvi, so the error shrinks like ∣λ2∣k, with λ2 the eigenvalue of second-largest magnitude. This is power iteration applied to P⊤: multiply a vector by the same matrix again and again, and it settles on the eigenvector with the largest eigenvalue magnitude.
A two-page chain solved by hand
Two pages, Home and Search, with P=(0.90.50.10.5) (from Home, 90% stay and 10% go to Search; from Search, 50% go back to Home). Write π=(π1,π2). The first coordinate of πP=π says π1=0.9π1+0.5π2, so 0.1π1=0.5π2 and π1=5π2. With π1+π2=1 this gives π=(5/6,1/6). The eigenvalues of P are 1 and 0.9+0.5−1=0.4 (the trace is the sum of the eigenvalues), so each click should cut the distance to π by the factor 0.4.
import numpy as np
P = np.array([[0.9, 0.1], [0.5, 0.5]]) # rows: from Home, from Search; columns: to Home, to Search
pi = np.array([5 / 6, 1 / 6])
print("pi P =", np.round(pi @ P, 4), " pi =", np.round(pi, 4), " equal:", np.allclose(pi @ P, pi))
x = np.array([1.0, 0.0])
for k in (1, 2, 3):
x = x @ P
print(f" shares after {k} clicks: {np.round(x, 4)} error on Home {abs(x[0] - 5 / 6):.4f}")
print(" eigenvalues of P:", np.round(np.sort(np.linalg.eigvals(P))[::-1], 4), "-> the error shrinks by |lambda_2| = 0.4 per click")
Output:
pi P = [0.8333 0.1667] pi = [0.8333 0.1667] equal: True
shares after 1 clicks: [0.9 0.1] error on Home 0.0667
shares after 2 clicks: [0.86 0.14] error on Home 0.0267
shares after 3 clicks: [0.844 0.156] error on Home 0.0107
eigenvalues of P: [1. 0.4] -> the error shrinks by |lambda_2| = 0.4 per click
Starting with everyone on Home, the error on the Home share is 0.0667, 0.0267, 0.0107: each is 0.4 times the one before.
A five-page worked example
Pages: Home, Search, Product, Cart, Checkout. Row i lists where users on page i go next (for example, from Home 10% stay, 50% go to Search, 30% to Product, 10% to Cart; Checkout always returns to Home). The program finds π from the eigenvector of P⊤, checks πP=π, checks irreducibility (every entry of (I+P)4 is positive, since 5 pages need at most 4 clicks), then starts all users on Home and clicks 30 times. It also simulates one walker for 200000 clicks as an independent check, and in section 2 shows three ways the guarantee fails. Section 3 builds a six-page web with a cluster and a page with no links and applies damping. Section 4 estimates P from simulated clicks.
import numpy as np
pages = ["Home", "Search", "Product", "Cart", "Checkout"]
# P[i, j] = probability that a user on page i goes next to page j (rows sum to 1)
P = np.array([[0.10, 0.50, 0.30, 0.10, 0.00],
[0.20, 0.10, 0.60, 0.10, 0.00],
[0.20, 0.30, 0.20, 0.30, 0.00],
[0.30, 0.00, 0.30, 0.00, 0.40],
[1.00, 0.00, 0.00, 0.00, 0.00]])
assert np.allclose(P.sum(axis=1), 1.0)
def stationary(P):
"""Left eigenvector of P for eigenvalue 1, scaled to sum to 1 (a right eigenvector of P transposed)."""
w, V = np.linalg.eig(P.T)
i = np.argmin(np.abs(w - 1.0))
v = np.real(V[:, i])
return v / v.sum()
pi = stationary(P)
w = np.linalg.eigvals(P)
mods = np.sort(np.abs(w))[::-1]
print("1) Stationary distribution of the 5-page chain")
print(" pi =", np.round(pi, 4), " sums to", round(pi.sum(), 4))
print(" pi @ P =", np.round(pi @ P, 4), " equal to pi:", np.allclose(pi @ P, pi))
print(" eigenvalue moduli:", np.round(mods, 4))
reach = np.linalg.matrix_power(np.eye(5) + P, 4) > 0
print(" every page reaches every page (irreducible):", bool(reach.all()), "| has self-loops (aperiodic):", bool((np.diag(P) > 0).any()))
x = np.array([1.0, 0, 0, 0, 0]) # everyone starts on Home
for k in range(1, 31):
x = x @ P
if k in (1, 5, 10, 30):
print(f" share after {k:2d} clicks: {np.round(x, 4)} max error vs pi {np.abs(x - pi).max():.1e}")
print(f" |lambda_2|^30 = {mods[1]**30:.1e} (the error is of this size, up to a constant)")
rng = np.random.default_rng(0)
state, counts = 0, np.zeros(5)
for _ in range(200000):
state = rng.choice(5, p=P[state]); counts[state] += 1
print(" one walker, 200000 clicks, share of time:", np.round(counts / counts.sum(), 4), " within 0.01 of pi:", bool(np.abs(counts / counts.sum() - pi).max() < 0.01))
print("\n2) What breaks the guarantee")
Pper = np.array([[0.0, 1.0], [1.0, 0.0]])
x = np.array([1.0, 0.0]); seq = []
for _ in range(4):
x = x @ Pper; seq.append(x.copy())
print(" periodic chain: shares over 4 clicks", [s.tolist() for s in seq], "; pi = (0.5, 0.5) exists but is never approached")
Ptwo = np.array([[0.5, 0.5, 0, 0], [0.5, 0.5, 0, 0], [0, 0, 0.5, 0.5], [0, 0, 0.5, 0.5]])
print(" two separate groups of pages: eigenvalues equal to 1:", int(np.sum(np.abs(np.linalg.eigvals(Ptwo) - 1) < 1e-9)),
"-> both (0.5, 0.5, 0, 0) and (0, 0, 0.5, 0.5) are stationary")
with_exit = np.array([[0.0, 0.7, 0.3], [0.5, 0.0, 0.5], [0.0, 0.0, 1.0]]) # Home, Product, Exit (absorbing)
print(" chain with an absorbing Exit page: stationary =", np.round(stationary(with_exit), 4))
restart = np.array([1.0, 0.0, 0.0]) # a new session always starts on Home
G_exit = 0.85 * with_exit + 0.15 * restart[None, :]
print(" same chain, but each click starts a new session on Home with probability 0.15:", np.round(stationary(G_exit), 4))
print("\n3) Damping: G = d * P_fixed + (1 - d) * (1/n) 11^T (teleport to a uniformly random page)")
def google(P, d):
n = len(P)
Pf = P.copy()
dangling = Pf.sum(axis=1) == 0
Pf[dangling] = 1.0 / n # a page with no links jumps anywhere
return d * Pf + (1 - d) / n
n = 6
A = np.zeros((n, n)); A[0, 1] = A[1, 0] = 1; A[1, 2] = 1; A[2, 1] = 1; A[3, 4] = A[4, 3] = 1; A[4, 5] = 1 # page 5: no outgoing links
Pweb = np.divide(A, A.sum(axis=1, keepdims=True), out=np.zeros_like(A), where=A.sum(axis=1, keepdims=True) > 0)
print(" rows of the link matrix sum to:", Pweb.sum(axis=1), "(the 0 is a page with no links)")
G = google(Pweb, 0.85)
pr = stationary(G)
print(" PageRank, d=0.85:", np.round(pr, 4), "all positive:", bool((pr > 0).all()), " pi G = pi:", np.allclose(pr @ G, pr))
x = np.ones(n) / n
for k in range(200):
x_new = x @ G
if np.abs(x_new - x).sum() < 1e-12: break
x = x_new
print(f" power iteration stopped after {k + 1} steps, matches eigenvector: {np.allclose(x_new, pr, atol=1e-9)}")
worst, at_bound = 0.0, 0
for seed in range(200):
r = np.random.default_rng(seed); m = int(r.integers(5, 40))
Ar = (r.random((m, m)) < 0.15).astype(float)
s = Ar.sum(axis=1, keepdims=True)
Pr = np.divide(Ar, s, out=np.zeros_like(Ar), where=s > 0)
ev = np.sort(np.abs(np.linalg.eigvals(google(Pr, 0.85))))[::-1]
worst = max(worst, ev[1] / 0.85); at_bound += int(ev[1] / 0.85 > 1 - 1e-6)
assert worst <= 1 + 1e-9
print(f" 200 random graphs, d = 0.85: largest |lambda_2| / d = {worst:.4f}; graphs where |lambda_2| equals d: {at_bound}; never above d")
print(" iterations to reach L1 change < 1e-10 on that 6-page web, versus ln(1e-10)/ln(d):")
for d in (0.5, 0.85, 0.99):
G = google(Pweb, d); x = np.ones(n) / n; it = 0
while True:
x_new = x @ G; it += 1
if np.abs(x_new - x).sum() < 1e-10: break
x = x_new
print(f" d={d:<5} iterations={it:4d} ln(1e-10)/ln(d) = {np.log(1e-10)/np.log(d):7.1f}")
print("\n4) Estimating P from clicks, then the long-run share")
state, C = 0, np.zeros((5, 5))
for _ in range(20000):
nxt = rng.choice(5, p=P[state]); C[state, nxt] += 1; state = nxt
Phat = C / C.sum(axis=1, keepdims=True)
print(" max |Phat - P| =", round(np.abs(Phat - P).max(), 3), "; max |pi_hat - pi| =", round(np.abs(stationary(Phat) - pi).max(), 4))
Output (Python 3.12, NumPy 2.1.3):
1) Stationary distribution of the 5-page chain
pi = [0.2369 0.239 0.3222 0.1442 0.0577] sums to 1.0
pi @ P = [0.2369 0.239 0.3222 0.1442 0.0577] equal to pi: True
eigenvalue moduli: [1. 0.4167 0.4167 0.384 0.384 ]
every page reaches every page (irreducible): True | has self-loops (aperiodic): True
share after 1 clicks: [0.1 0.5 0.3 0.1 0. ] max error vs pi 2.6e-01
share after 5 clicks: [0.2424 0.2414 0.3164 0.1446 0.0552] max error vs pi 5.8e-03
share after 10 clicks: [0.2369 0.2391 0.3221 0.1442 0.0577] max error vs pi 7.4e-05
share after 30 clicks: [0.2369 0.239 0.3222 0.1442 0.0577] max error vs pi 1.1e-12
|lambda_2|^30 = 3.9e-12 (the error is of this size, up to a constant)
one walker, 200000 clicks, share of time: [0.2372 0.2388 0.3224 0.1441 0.0574] within 0.01 of pi: True
2) What breaks the guarantee
periodic chain: shares over 4 clicks [[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0]] ; pi = (0.5, 0.5) exists but is never approached
two separate groups of pages: eigenvalues equal to 1: 2 -> both (0.5, 0.5, 0, 0) and (0, 0, 0.5, 0.5) are stationary
chain with an absorbing Exit page: stationary = [0. 0. 1.]
same chain, but each click starts a new session on Home with probability 0.15: [0.2008 0.1195 0.6798]
3) Damping: G = d * P_fixed + (1 - d) * (1/n) 11^T (teleport to a uniformly random page)
rows of the link matrix sum to: [1. 1. 1. 1. 1. 0.] (the 0 is a page with no links)
PageRank, d=0.85: [0.1877 0.3556 0.1877 0.0815 0.1059 0.0815] all positive: True pi G = pi: True
power iteration stopped after 163 steps, matches eigenvector: True
200 random graphs, d = 0.85: largest |lambda_2| / d = 1.0000; graphs where |lambda_2| equals d: 10; never above d
iterations to reach L1 change < 1e-10 on that 6-page web, versus ln(1e-10)/ln(d):
d=0.5 iterations= 32 ln(1e-10)/ln(d) = 33.2
d=0.85 iterations= 134 ln(1e-10)/ln(d) = 141.7
d=0.99 iterations=2167 ln(1e-10)/ln(d) = 2291.1
4) Estimating P from clicks, then the long-run share
max |Phat - P| = 0.018 ; max |pi_hat - pi| = 0.0025
Reading the output:
- Section 1. π=(0.2369,0.2390,0.3222,0.1442,0.0577): Product holds the largest long-run share and Checkout the smallest. The eigenvalue moduli are 1,0.4167,0.4167,0.384,0.384, so ∣λ2∣=0.4167. Starting from Home, the largest error against π is 2.6×10−1 after 1 click, 5.8×10−3 after 5, 7.4×10−5 after 10 and 1.1×10−12 after 30, the same order as ∣λ2∣30=3.9×10−12. The simulated walker spends the same shares of time on each page, within 0.01 of π (for an irreducible chain, the fraction of time one walker spends on a page converges to that page's stationary share).
- Section 2. Three failures. A periodic chain (two pages that only click to each other) has π=(0.5,0.5) but the shares flip between (0,1) and (1,0) forever. A chain made of two separate groups of pages has two eigenvalues equal to 1, so there are many stationary distributions. A chain with an absorbing page (users who reach Exit never leave) has the degenerate π=(0,0,1).
- The last line of section 2 previews damping: letting each click restart a session on Home with probability 0.15 turns the absorbing chain into one with a unique, positive stationary distribution (0.2008,0.1195,0.6798).
Why PageRank adds a damping factor
PageRank scores web pages by the long-run share of time a random surfer spends on each page, using the link graph as P (row i spreads probability equally over the pages that page i links to). The raw link matrix has exactly the failures of section 2: dangling pages with no outgoing links (a row of zeros, which is not a probability distribution), separate clusters or closed loops that trap the surfer (reducible, many stationary vectors or all mass collecting in a trap), and cycles (periodicity). The fix has two parts:
G=dP~+(1−d)n111⊤Here P~ is P with each all-zero row replaced by the uniform row 1/n (a page with no links jumps anywhere), 11⊤ is the n×n matrix of ones, and d∈(0,1) is the damping factor, commonly set near 0.85. In words: with probability d follow a link, with probability 1−d jump to a page chosen uniformly at random (the teleport).
- Existence and uniqueness. Every entry of G is at least (1−d)/n>0, so G is irreducible and aperiodic: one stationary vector, all entries positive, and power iteration converges from any start.
- Speed. The second eigenvalue of G is bounded by ∣λ2(G)∣≤d (a result of Haveliwala and Kamvar, 2003), so the error shrinks at least like dk and reaching tolerance ε takes about lnε/lnd iterations. In section 3, 200 random graphs with d=0.85 never exceeded the bound, and 10 of them reached it exactly. On the six-page web, the iteration counts to an L1 change (the sum of absolute differences between two successive share vectors) below 10−10 were 32, 134 and 2167 for d=0.5,0.85,0.99, against ln(10−10)/lnd = 33.2, 141.7 and 2291.1. The formula is an upper estimate, so it is close but not exact. The reason for the bound: take an eigenvector v of G⊤ with eigenvalue λ=1. Since G1=1, multiplying G⊤v=λv on the left by 1⊤ gives 1⊤v=λ1⊤v, so 1⊤v=0. The teleport part of G⊤ is proportional to 11⊤v=0 and vanishes, leaving G⊤v=dP~⊤v. So λ is d times an eigenvalue of P~, and every eigenvalue of P~ has magnitude at most 1. What to remember is the conclusion: damping caps the convergence rate at d.
- The price of damping. The result is a slightly different answer than the pure link structure would give: as d→1 the ranking follows the links more faithfully but convergence slows and small structural changes matter more; as d→0 every page tends to the same score. d is a modelling choice.
- The teleport need not be uniform. Using a non-uniform jump distribution (for example, always back to the home page) gives a personalised ranking, as in the restart example above.
What this means for a product-analytics model
- Estimate P from logs by counting transitions and dividing each row by its total (section 4: from 20000 simulated clicks the largest entry error is 0.018 and the largest error in the long-run shares is 0.0025, for that one sample). Pages with few visits give noisy rows, which is the diagnostic to check first.
- The long-run share is not the share of page views in a real session. Real sessions end, which is an absorbing Exit state, and a chain with an absorbing state has the degenerate π above. Use the stationary distribution for continuous behaviour (a feed, a long-lived session) and, for finite sessions, the expected number of visits before exit, computed from the part of P among non-exit pages as (I−Q)−1. Here Q keeps only the rows and columns of the non-exit pages, so Qij is the probability of going directly from page i to page j without exiting. The expected number of visits to j starting from i is ∑k≥0(Qk)ij (the k-th term is the chance of being on j after k clicks without having exited), and this geometric-style series sums to ((I−Q)−1)ij. For the Home, Product, Exit chain of section 2, Q=(00.50.70):
import numpy as np
Q = np.array([[0.0, 0.7], [0.5, 0.0]]) # Home, Product among the non-exit pages
N = np.linalg.inv(np.eye(2) - Q)
print("(I - Q)^-1 =", np.round(N, 3).tolist(), " (det(I - Q) = 1 - 0.7*0.5 = 0.65)")
print("expected pages viewed before exit, starting from Home / Product:", np.round(N.sum(axis=1), 3))
Output:
(I - Q)^-1 = [[1.538, 1.077], [0.769, 1.538]] (det(I - Q) = 1 - 0.7*0.5 = 0.65)
expected pages viewed before exit, starting from Home / Product: [2.615 2.308]
A session that starts on Home views about 2.6 pages, counting the starting page, before leaving.
- Check the Markov assumption. The model says the next page depends only on the current page. If the previous page matters (a user who came from Search behaves differently on Product), the first-order chain misstates the shares and you need a state that includes the previous page.
Common mistakes
- Solving Pv=v (a right eigenvector, which is the all-ones vector) instead of πP=π, or forgetting to normalise so that ∑jπj=1 (an eigenvector comes with arbitrary scale and sign).
- Asserting convergence without aperiodicity: an irreducible but periodic chain has a unique π that the shares never approach.
- Describing damping as "making the matrix stochastic": the dangling-row fix does that; the teleport term is what makes the chain irreducible and aperiodic and bounds ∣λ2∣.
What are eigenvalues and eigenvectors, and what is the geometric intuition? Where do they show up in machine learning?
Sample Answer
The idea in plain words
A matrix A is a machine that takes a vector and returns another vector: it can stretch, squash, rotate and shear. Most input vectors come out pointing in a new direction. An eigenvector is a special nonzero direction that comes out pointing along the same line (or exactly the opposite way), only longer or shorter. The eigenvalue is the factor by which it is scaled:
Av=λv
Here v is the eigenvector and λ is its eigenvalue. A negative λ flips the vector; a λ of 0 collapses it to the zero vector. The geometric picture: feed every point of a unit circle through a symmetric matrix (one equal to its own transpose, so entry row i, column j equals entry row j, column i) and you get an ellipse whose axes lie along the eigenvectors, with semi-axis lengths equal to the absolute eigenvalues.
Worked example
Take the symmetric matrix with rows (3, 1) and (1, 2).
By hand first. Av=λv can be rewritten (A−λI)v=0, where I is the identity matrix. A nonzero v can satisfy that only if A−λI squashes some direction to nothing, which is the case exactly when its determinant (a single number that is zero for such a matrix; for a 2 by 2 matrix with rows (a,b) and (c,d) it is ad−bc) is zero:
det(3−λ112−λ)=(3−λ)(2−λ)−1=λ2−5λ+5=0
The 5 in the middle is the trace (sum of the diagonal, 3 + 2) and the last 5 is the determinant of A itself (3 times 2 minus 1 times 1). The quadratic formula gives λ=(5±5)/2, which is 1.382 and 3.618. For the eigenvector of each λ, the first row of (A−λI)v=0 reads (3−λ)v1+v2=0, so v=(1,λ−3), and dividing by its length gives a vector of length 1.
The program repeats that arithmetic, computes the eigenpairs with a library routine, checks Av=λv numerically, checks that the eigenvalues sum to the trace and multiply to the determinant, and then shows the ML uses. The sign of an eigenvector is arbitrary, so the code fixes it (largest component positive); the hand-built direction for 1.382 comes out with the opposite sign, which is the same line.
import numpy as np
np.set_printoptions(precision=4, suppress=True)
# 1. Geometry: a symmetric 2x2 matrix, its eigenpairs, and what it does to vectors.
A = np.array([[3.0, 1.0], [1.0, 2.0]])
vals, vecs = np.linalg.eigh(A) # eigenvalues in ascending order
for i in range(2): # fix the arbitrary sign: largest component positive
if vecs[np.argmax(np.abs(vecs[:, i])), i] < 0:
vecs[:, i] = -vecs[:, i]
print("eigenvalues:", vals)
for i in range(2):
v = vecs[:, i]
print(f"eigenvector {i}:", v, " A@v:", A @ v, " lambda*v:", vals[i] * v)
print("trace:", np.trace(A), " sum of eigenvalues:", vals.sum())
print("det:", round(np.linalg.det(A), 4), " product of eigenvalues:", round(vals.prod(), 4))
x = np.array([1.0, 0.0])
print("generic x:", x, " A@x:", A @ x, " (direction changed)")
# By hand: det(A - lambda*I) = lambda^2 - trace*lambda + det = 0, solved with the quadratic formula.
tr, dt = np.trace(A), np.linalg.det(A)
roots = (tr + np.array([-1.0, 1.0]) * np.sqrt(tr**2 - 4 * dt)) / 2
print("roots of lambda^2 - 5*lambda + 5:", roots)
for lam in roots:
# first row of (A - lam*I) v = 0 is (3 - lam)*v1 + v2 = 0, so v = (1, lam - 3); scale to length 1
v = np.array([1.0, lam - 3.0])
print(f"lambda={lam:.4f}: direction (1, {lam - 3:.4f}) scaled to length 1 ->", v / np.linalg.norm(v))
# 2. ML use 1: PCA directions are eigenvectors of the covariance matrix.
rng = np.random.default_rng(0)
Z = rng.normal(size=(500, 2)) * np.array([3.0, 0.5])
c, s = np.cos(0.6), np.sin(0.6)
R = np.array([[c, -s], [s, c]])
X = Z @ R.T # stretched cloud, rotated by 0.6 radians
C = np.cov(X, rowvar=False) # 2x2 sample covariance (divisor n-1)
cv, cV = np.linalg.eigh(C)
print("covariance eigenvalues:", cv, " variance share of top direction:", round(cv[1] / cv.sum(), 4))
top = cV[:, 1] * np.sign(cV[0, 1])
print("top eigenvector:", top, " true long axis:", np.array([c, s]))
# 3. ML use 2/3: Hessian eigenvalues set gradient-descent speed (f = 0.5 x^T H x, step 1/lambda_max).
def steps_to_converge(H, tol=1e-6, lr=None):
x = np.array([1.0, 1.0])
if lr is None:
lr = 1.0 / np.linalg.eigvalsh(H).max()
k = 0
while np.linalg.norm(x) > tol:
x = x - lr * (H @ x)
k += 1
return k
for name, H in [("eigenvalues 1 and 1", np.diag([1.0, 1.0])),
("eigenvalues 1 and 10", np.diag([10.0, 1.0])),
("eigenvalues 1 and 100", np.diag([100.0, 1.0]))]:
print(f"{name}: condition number {np.linalg.cond(H):.0f}, steps to reach 1e-6: {steps_to_converge(H)}")
# Why those step counts: each coordinate is multiplied by (1 - lambda_i/lambda_max) per step.
for kappa in (10, 100):
shrink = 1 - 1 / kappa
print(f"condition number {kappa}: flat coordinate shrinks by {shrink} per step; ceil(ln(1e-6)/ln({shrink})) = {int(np.ceil(np.log(1e-6) / np.log(shrink)))}")
# A larger step helps only a little: compare 1/lambda_max with the best fixed step 2/(lambda_max + lambda_min).
for kappa in (10, 100):
H = np.diag([float(kappa), 1.0])
best = 2.0 / (kappa + 1.0)
print(f"condition number {kappa}: step 1/lambda_max takes {steps_to_converge(H)}, step 2/(lambda_max+lambda_min) takes {steps_to_converge(H, lr=best)}")
Output:
eigenvalues: [1.382 3.618]
eigenvector 0: [-0.5257 0.8507] A@v: [-0.7265 1.1756] lambda*v: [-0.7265 1.1756]
eigenvector 1: [0.8507 0.5257] A@v: [3.0777 1.9021] lambda*v: [3.0777 1.9021]
trace: 5.0 sum of eigenvalues: 5.0
det: 5.0 product of eigenvalues: 5.0
generic x: [1. 0.] A@x: [3. 1.] (direction changed)
roots of lambda^2 - 5*lambda + 5: [1.382 3.618]
lambda=1.3820: direction (1, -1.6180) scaled to length 1 -> [ 0.5257 -0.8507]
lambda=3.6180: direction (1, 0.6180) scaled to length 1 -> [0.8507 0.5257]
covariance eigenvalues: [0.2344 8.7383] variance share of top direction: 0.9739
top eigenvector: [0.8247 0.5656] true long axis: [0.8253 0.5646]
eigenvalues 1 and 1: condition number 1, steps to reach 1e-6: 1
eigenvalues 1 and 10: condition number 10, steps to reach 1e-6: 132
eigenvalues 1 and 100: condition number 100, steps to reach 1e-6: 1375
condition number 10: flat coordinate shrinks by 0.9 per step; ceil(ln(1e-6)/ln(0.9)) = 132
condition number 100: flat coordinate shrinks by 0.99 per step; ceil(ln(1e-6)/ln(0.99)) = 1375
condition number 10: step 1/lambda_max takes 132, step 2/(lambda_max+lambda_min) takes 71
condition number 100: step 1/lambda_max takes 1375, step 2/(lambda_max+lambda_min) takes 709
Reading the output:
- Same direction. For both eigenvectors,
A@vequalslambda*v. For the generic vector (1, 0),A@xis (3, 1), which points elsewhere. - Hand and library agree. The roots of λ2−5λ+5 are the same 1.382 and 3.618, and the direction (1,λ−3) scaled to length 1 is (0.8507, 0.5257) for 3.618, as in the library output. For 1.382 it is (0.5257, -0.8507), the library's vector with both signs flipped.
- Sanity checks. The eigenvalues 1.382 and 3.618 sum to the trace 5 and multiply to the determinant 5, which matches the coefficients of the quadratic above.
- Symmetric matrices are the friendly case. A real symmetric matrix has real eigenvalues and mutually orthogonal eigenvectors (perpendicular: their dot product is zero; here −0.5257×0.8507+0.8507×0.5257=0). A set of vectors that are perpendicular and each of length 1 is called orthonormal. This is why
eigh(the routine for symmetric matrices) is the right call for covariances and Hessians. A general matrix, such as a rotation, can have complex eigenvalues or too few independent eigenvectors.
Where eigenvalues show up in machine learning
- PCA (principal component analysis). The covariance matrix C of centered data (data with each feature's average subtracted) has the variance of each feature on its diagonal (the average squared distance from the mean) and, off the diagonal, how each pair of features moves together; it is symmetric. Its eigenvectors are the directions of the principal components, and its eigenvalues are the variance along each direction, meaning the spread of the data after every point is projected onto that direction. In the program the cloud was built by stretching one axis and rotating by 0.6 radians; the top eigenvector (0.8247, 0.5656) recovers the long axis (0.8253, 0.5646), and that direction carries 0.9739 of the total variance.
- The Hessian of a loss. The Hessian is the matrix of second derivatives, and it measures curvature. Near a minimum its eigenvectors are the perpendicular directions along which the loss curves independently, and its eigenvalues are the curvature along each. Large eigenvalue means a steep direction; small means a flat one. All eigenvalues positive (the matrix is called positive definite) means the loss curves upward in every direction, a bowl with a minimum at the bottom. Mixed signs mean a saddle point: a flat spot that curves up in some directions and down in others, like a mountain pass.
- Conditioning of a linear system or a quadratic. The condition number is the ratio of the largest to the smallest eigenvalue magnitude (for a symmetric positive definite matrix, meaning one with all eigenvalues positive). A value of 1 means every direction is equally curved, a round bowl; the larger it is, the longer and narrower the valley, and the harder it is for gradient descent (and for solving linear systems accurately) to treat all directions at once. Gradient descent on f(x)=21x⊤Hx with the standard step size 1/λmax (any step below 2/λmax still converges) moves slowly along the flat directions. The output counts the steps needed to bring the starting point (1, 1) within 1e-6 of the minimum: 1 step with condition number 1, 132 with condition number 10, and 1375 with condition number 100.
Why a flat direction slows things down: for this quadratic, one step multiplies each coordinate (measured along an eigenvector) by 1−λi/λmax. The steepest direction is multiplied by 0 and vanishes at once. The flattest direction is multiplied by 1−1/κ, where κ is the condition number: 0.9 per step at κ=10 and 0.99 at κ=100. Shrinking by a factor of 10−6 takes ln(10−6)/ln(0.9)=131.1, so 132 steps, and ln(10−6)/ln(0.99)=1374.6, so 1375 steps, exactly the counts printed. A larger step helps only a little. Above 2/λmax the steepest coordinate blows up, and the best fixed step, 2/(λmax+λmin), cuts the count from 132 to 71 at κ=10 and from 1375 to 709 at κ=100, as the last two output lines show. That is about half the steps, not a cure: the flat direction still shrinks by roughly 1−2/κ per step, so the count still grows in proportion to κ.
Trade-offs and common mistakes
- Saying "an eigenvector is a direction that does not change". It can flip (negative λ) or shrink to zero; what does not change is the line it lies on.
- Treating eigenvectors as unique. Any nonzero multiple is also an eigenvector, so only the direction counts; when two eigenvalues are equal, any direction in their shared plane works.
- Using a general-purpose eigen solver on a covariance matrix. Use the symmetric routine: it is faster and guarantees real, sorted eigenvalues with orthonormal vectors.
- Forgetting that eigenvalues exist only for square matrices. For a rectangular data matrix, the analogue is the singular value decomposition (SVD), which factors any matrix into a rotation, a stretch along the axes and another rotation.
Your sample covariance matrix is ill-conditioned because the data is high-dimensional with few samples. What goes wrong downstream, and how would you fix or work around it?
Sample Answer
The idea in plain words
A sample covariance matrix S for d features is estimated from n samples. After centering, the data matrix has rank at most n−1, so when n≤d the d×d matrix S has at least d−n+1 eigenvalues that are exactly zero. A matrix with a zero eigenvalue is singular, and with a near-zero one it is ill-conditioned: the condition number (ratio of largest to smallest eigenvalue for a symmetric positive semidefinite matrix, one whose eigenvalues are all zero or positive, as every covariance matrix is) is huge, and tiny errors in the data are amplified enormously when you invert it or solve with it.
Symptoms, with the numbers
The program draws 20 samples in 50 dimensions from a Gaussian whose true covariance is diagonal with eigenvalues from 4.0 down to 0.25 (true condition number 16). It prints the rank, the conditioning, and a held-out test of several repairs. Held-out data is fresh data from the same distribution that was not used to build the estimate, so it shows how well the estimate generalizes. The score used is the mean Gaussian log-likelihood: for each held-out row it asks how plausible that row is under a Gaussian with the fitted covariance, then averages. Higher means the fitted covariance describes new data better (the constant dropped from the score shifts every value by the same amount, so only differences between scores matter, and the values are not required to be negative); the true covariance gives the best score that is attainable on average, so the gap to it is the damage done by estimation error.
import numpy as np
from sklearn.covariance import LedoitWolf
rng = np.random.default_rng(0)
n, d = 20, 50 # fewer samples than features
true_eigs = np.linspace(4.0, 0.25, d) # true covariance: diagonal, condition number 16
scale = np.sqrt(true_eigs)
X = rng.normal(size=(n, d)) * scale
Xnew = rng.normal(size=(2000, d)) * scale # held-out data from the same distribution
S = np.cov(X, rowvar=False) # d x d sample covariance (divisor n-1)
ev = np.linalg.eigvalsh(S)[::-1] # descending
print("shape of S:", S.shape, " rank:", np.linalg.matrix_rank(S), " (at most n-1 =", n - 1, ")")
print("nonzero eigenvalues:", int((ev > 1e-10).sum()), " of", d)
print("true condition number:", true_eigs.max() / true_eigs.min(), " sample condition number:", f"{np.linalg.cond(S):.2e}")
print("largest sample eigenvalue:", round(ev[0], 3), "(true largest 4.0)")
def shrink(S, a):
# (1 - a) * S + a * mu * I, with mu = trace(S) / d
mu = np.trace(S) / S.shape[0]
return (1 - a) * S + a * mu * np.eye(S.shape[0])
def gaussian_loglik(Sigma, Z):
# mean Gaussian log-likelihood of the rows of Z, dropping the constant -d/2 * log(2 pi)
sign, logdet = np.linalg.slogdet(Sigma)
P = np.linalg.inv(Sigma)
return float(-0.5 * np.mean(np.einsum("ij,jk,ik->i", Z, P, Z)) - 0.5 * logdet)
print("\ntrue covariance, held-out log-likelihood:", round(gaussian_loglik(np.diag(true_eigs), Xnew), 3))
print("\nshrinkage a | cond(S_a) | held-out mean log-likelihood")
for a in (0.01, 0.1, 0.3, 0.6, 0.9, 1.0):
Sa = shrink(S, a)
print(f"{a:11.2f} | {np.linalg.cond(Sa):9.2e} | {gaussian_loglik(Sa, Xnew):10.3f}")
lw = LedoitWolf().fit(X) # scikit-learn centers the data and divides by n
print("\nLedoit-Wolf shrinkage chosen from the data:", round(lw.shrinkage_, 3),
" held-out:", round(gaussian_loglik(lw.covariance_, Xnew), 3))
Output:
shape of S: (50, 50) rank: 19 (at most n-1 = 19 )
nonzero eigenvalues: 19 of 50
true condition number: 16.0 sample condition number: 1.35e+18
largest sample eigenvalue: 15.735 (true largest 4.0)
true covariance, held-out log-likelihood: -38.983
shrinkage a | cond(S_a) | held-out mean log-likelihood
0.01 | 7.83e+02 | -1437.922
0.10 | 7.21e+01 | -143.218
0.30 | 1.94e+01 | -60.995
0.60 | 6.27e+00 | -46.183
0.90 | 1.88e+00 | -43.686
1.00 | 1.00e+00 | -43.914
Ledoit-Wolf shrinkage chosen from the data: 0.764 held-out: -44.455
- Rank. S is 50 by 50 with rank 19 = n-1, so 31 of its 50 eigenvalues are zero (to rounding). Its sample condition number is about 1e18, which is set by rounding error in the zero eigenvalues, not by the data.
- Distorted spectrum. The true largest eigenvalue is 4.0 but the sample one is 15.735. Sample eigenvalues spread out: the large ones are overestimated and the small ones underestimated. This happens even when it is full rank.
Reading the helper code: np.linalg.slogdet returns the sign and the logarithm of the determinant without overflowing, and np.einsum("ij,jk,ik->i", Z, P, Z) computes z⊤Pz for every row z of the held-out matrix Z at once, where P is the inverse covariance (also called the precision matrix). The score is the average of −21z⊤Pz−21logdetΣ.
What goes wrong downstream
Check these in order; the first three all contain the inverse or the determinant of S.
- Inversion fails or returns garbage. All of these use S−1: linear and quadratic discriminant analysis (classifiers that model each class as a Gaussian and score a point with the inverse covariance), Mahalanobis distance (distance measured in units of the data's own spread, (x−μ)⊤S−1(x−μ)), Gaussian likelihoods, generalized least squares (regression that down-weights noisy, correlated errors using the inverse of their covariance) and minimum-variance portfolio weights (asset weights proportional to S−11, the mix with the lowest variance). With a zero eigenvalue the inverse does not exist; with a tiny one, the inverse has huge entries (a direction with eigenvalue 0.001 counts a unit move 1000 times as heavily as one with eigenvalue 1) and the result is dominated by noise directions.
- The log-determinant diverges. logdetS=∑logλi goes to −∞ as an eigenvalue goes to 0, which wrecks any likelihood comparison.
- Noisy small-eigenvalue directions get all the weight. Those directions have the least data support but the largest weight in S−1, so the model chases noise (overfits).
- Iterative solvers slow down, since convergence depends on the condition number.
Fixes, in the order to try them
| Fix | What it does | Cost / caveat |
|---|---|---|
| Shrinkage Sa=(1−a)S+aμI with μ=tr(S)/d | Blends the sample matrix with a well-conditioned target, lifting every eigenvalue | Biased, but lower variance; needs a |
| Ledoit-Wolf | Picks a from the data by a closed-form formula that estimates which a minimizes the expected squared distance to the true covariance, no tuning loop | Assumes the identity-like target is sensible |
| Dimension reduction (PCA, principal component analysis, to k<n components, then work in that subspace) | Discards the zero and noisy small directions | Loses variance outside the subspace; k must be chosen |
| Structured estimate (diagonal; a factor model, where covariance comes from a few shared factors plus independent noise per feature; or a sparse precision matrix, where most entries of S−1 are forced to zero, meaning most feature pairs are unrelated once the others are known) | Fewer parameters than d(d+1)/2 | Wrong if the structure is wrong |
| Truncated pseudo-inverse (an inverse that ignores the zero or tiny eigenvalue directions) | Invert only eigenvalues above a threshold | Threshold is arbitrary and discards signal |
| More data | Fixes the root cause | Often not available |
The first two rows are the ones to reach for first because they cost one line and always give an invertible matrix. PCA comes next when size is the obstacle, structure when there is domain knowledge, and the truncated pseudo-inverse is a last resort because its threshold is a guess. More data is the cleanest fix but rarely on offer.
In the output, the held-out mean log-likelihood (higher is better, constant dropped) is -1437.922 at a=0.01, which is nearly unregularized and badly conditioned (condition number 7.83e2), and improves steadily to -43.686 at a=0.9. The true covariance scores -38.983, the ceiling. Full shrinkage to the identity (a=1) scores -43.914, slightly worse than a=0.9, because the true covariance is not the identity. Ledoit-Wolf chose a=0.764 and scored -44.455. That is a one-seed comparison, so what it supports is that heavy shrinkage helps enormously when n<d, not a ranking of the last three settings. scikit-learn's LedoitWolf centers the data and divides by n rather than n−1, a minor difference from np.cov.
Recommendation
Default to Ledoit-Wolf shrinkage for a Gaussian-style model, because it needs no tuning loop and its output is always invertible and well conditioned. Use PCA first when d is so large that even a d×d matrix is too big to store. Choose a structured estimate when you have domain knowledge (for example independent sensors). If you only need S−1y, solve the linear system with a Cholesky factorization of the shrunk matrix (writing it as LL⊤ with L triangular, after which two cheap triangular solves give the answer) instead of forming the inverse.
Common mistakes
- Adding a tiny constant like 1e-10 to the diagonal and calling it fixed. It makes the code run but the smallest retained eigenvalue is then about that constant, so the condition number stays enormous and the noise directions still dominate.
- Using
np.linalg.pinvsilently, which hides the problem and still amplifies the smallest retained directions. - Judging the fix on the training data, where the unregularized estimate looks perfect. Always judge on held-out data.
Unlock Full Question Bank
Get access to all 20 Linear Algebra and Numerical Computing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.