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.
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.
Explain ridge regression through the singular value decomposition of the design matrix. What does the penalty do to each singular direction, why does that fix unstable coefficients under multicollinearity, and how does it compare with simply dropping the small singular values?
Sample Answer
The idea in plain words
Ridge regression minimises ∥y−Xβ∥2+λ∥β∥2, where λ≥0 is the penalty weight (features are standardised, rescaled to mean zero and unit spread so the penalty treats them alike, and the intercept is left unpenalised). Written in the singular value decomposition (SVD, a factorisation X=UΣV⊤ into orthonormal directions, meaning unit-length vectors at right angles to each other, and stretch factors σi, the singular values, one per direction) the penalty does one clean thing: it multiplies the ordinary least-squares answer along the i-th singular direction by the filter factor
fi=σi2+λσi2.Directions with σi2≫λ pass almost untouched (fi≈1); directions with σi2≪λ are squashed toward zero. Unstable coefficients come from the weak directions, where ordinary least squares divides by a tiny σi. Ridge damps exactly those, smoothly. Dropping small singular values (truncated SVD) does the same with a hard 0-or-1 filter.
In an interview the filter factor and the per-direction bias and variance carry the answer. Effective degrees of freedom, principal component regression, the Bayesian reading and the comparison of the best penalty with the best truncation level are deeper material that a follow-up question may reach.
Derivation
Take the thin SVD (the version that keeps only the p nonzero stretch directions) X=UΣV⊤ with U (n×p) having orthonormal columns, Σ=diag(σ1≥⋯≥σp), and V (p×p) orthogonal. The penalised normal equations are (X⊤X+λI)β=X⊤y. Since X⊤X=VΣ2V⊤ and λI=V(λI)V⊤,
β^ridge=V(Σ2+λI)−1V⊤VΣU⊤y=i=1∑pσi2+λσi(ui⊤y)vi,while ordinary least squares is the same sum with 1/σi in place of σi/(σi2+λ). The ratio of the two weights is fi. A weight of 1/σi is unbounded as σi→0; the ridge weight is at most 1/(2λ), because σi2+λ≥2σiλ (the square of σi−λ is nonnegative), so σi/(σi2+λ)≤1/(2λ), with equality at σi=λ.
Why multicollinearity makes coefficients unstable, and why ridge fixes it
Suppose the data are generated as y=Xβtrue+ε, where ε is random noise with standard deviation η (written η so it is not confused with the singular values σi). Two words are needed. The bias of an estimate is how far its average, over many fresh noisy data sets, sits from the true value. Its variance is how much it scatters around that average. The mean squared error (MSE) of a coefficient is bias squared plus variance.
Derivation per direction. Let αi=vi⊤βtrue be the true coefficient along direction i. Every estimator compared here (ordinary least squares, ridge, truncation) has the form β^=∑ifiσiui⊤yvi with a filter factor fi (fi=1 for ordinary least squares, σi2/(σi2+λ) for ridge, 0 or 1 for truncation). Substituting y gives ui⊤y=σiαi+ui⊤ε, so the coefficient along vi is
α^i=fiαi+fiσiui⊤ε.The noise term has average zero, so the average is fiαi and the bias is (fi−1)αi. For ridge, fi−1=−λ/(σi2+λ), which is the bias −σi2+λλαi. The scalar ui⊤ε has variance η2 (a unit vector applied to noise of standard deviation η), so the variance is fi2η2/σi2.
Now compare. Ordinary least squares has covariance (the matrix of variances and co-movements of the estimate) η2(X⊤X)−1=η2VΣ−2V⊤, so along vi the variance is η2/σi2. Nearly collinear columns mean a tiny σp, hence a huge variance in that direction: the coefficients swing wildly from one sample to the next, with large opposite-signed values that cancel in the predictions. Ridge replaces 1/σi2 by σi2/(σi2+λ)2 in that variance (this is fi2/σi2) and pays the bias above. Truncating to the top k directions keeps the variance η2/σi2 for i≤k, has no bias there, and loses the whole of αi for i>k. (Truncation in the PCA basis, the directions of largest variance of the centred data, is also called principal component regression.)
So per direction, with fi the filter factor of the method:
MSEi=(fi−1)2αi2+σi2η2fi2,and the total error of the coefficient vector is the sum over i (the directions are orthogonal). The effective degrees of freedom are ∑ifi: how many directions the fit effectively uses.
A two-direction case small enough to follow by hand: singular values 10 and 0.01, penalty λ=0.1, noise standard deviation η=0.5, true coefficients α=(3,1). The filter factors are 100/100.1≈0.999 and 0.0001/0.1001≈0.001. The next program prints them, the weights, and the bias and variance per direction.
import numpy as np
# Two singular directions: one strong (sigma 10), one weak (sigma 0.01)
sigma = np.array([10.0, 0.01])
lam, eta = 0.1, 0.5 # penalty weight, noise standard deviation
alpha = np.array([3.0, 1.0]) # true coefficient along each direction
f = sigma**2 / (sigma**2 + lam) # filter factors
print("filter factors f_i :", np.round(f, 4))
print("OLS weight 1/sigma_i :", 1.0 / sigma)
print("ridge weight sigma/(sigma^2+lam) :", np.round(sigma / (sigma**2 + lam), 4), " bound 1/(2*sqrt(lam)) =", round(1 / (2 * np.sqrt(lam)), 4))
for name, ff in (("OLS", np.ones(2)), ("ridge", f)):
bias = (ff - 1.0) * alpha # mean of the estimate minus the true value
var = eta**2 * ff**2 / sigma**2 # variance of the estimate along each direction
print(f"{name:5s} bias {np.round(bias, 4)} variance {np.round(var, 4)} total error {np.round((bias**2).sum() + var.sum(), 4)}")
Output:
filter factors f_i : [0.999 0.001]
OLS weight 1/sigma_i : [ 0.1 100. ]
ridge weight sigma/(sigma^2+lam) : [0.0999 0.0999] bound 1/(2*sqrt(lam)) = 1.5811
OLS bias [0. 0.] variance [2.5e-03 2.5e+03] total error 2500.0025
ridge bias [-0.003 -0.999] variance [0.0025 0.0025] total error 1.003
Reading it: ordinary least squares weights the weak direction by 100, so its noise is amplified by 100 and the variance there is 2500 against 0.0025 along the strong direction. Ridge weights both directions by about 0.0999, so the scatter is equal and small, and pays instead a bias of about −0.999 on the weak direction (it almost erases the true coefficient 1 there). Total error: 2500.0025 for ordinary least squares, 1.003 for ridge.
A fuller worked example
The design has singular values 10, 1 and 0.01 (50 rows, noise standard deviation η=0.5). Case A has true coefficient 0 along the weak direction; case B has 1 there. The tables are the exact bias and variance from the formulas above. The program works in blocks: it builds the design from chosen singular values and random orthonormal factors; prints the filter factors; prints the exact bias, variance and total error for six estimators in the two cases; checks the SVD formulas against sklearn.linear_model.Ridge and against numpy.linalg.pinv (the pseudo-inverse, which inverts the nonzero stretch factors; its rcond=1e-2 option treats singular values below 1e-2 times the largest as zero, which drops exactly the weak direction here); and confirms the variance formula by a Monte Carlo check, meaning 20000 repeated simulated noisy data sets whose average error is compared with the formula. The last two lines compare the best ridge penalty (searched over a grid) with the best truncation level for two spectra, with all true direction coefficients equal to 1.
import numpy as np
from sklearn.linear_model import Ridge
rng = np.random.default_rng(0)
n, noise_sd = 50, 0.5
sig = np.array([10.0, 1.0, 0.01]) # singular values of the design matrix
U, _ = np.linalg.qr(rng.normal(size=(n, 3))) # orthonormal columns
V, _ = np.linalg.qr(rng.normal(size=(3, 3))) # orthogonal 3x3
X = U @ np.diag(sig) @ V.T
# Filter factors: how much of the least-squares coefficient survives along each singular direction
def ridge_filter(lam): return sig**2 / (sig**2 + lam)
def tsvd_filter(k): return (np.arange(3) < k).astype(float)
print("sigma :", sig)
print("ridge lambda=0.1 :", np.round(ridge_filter(0.1), 4))
print("ridge lambda=1 :", np.round(ridge_filter(1.0), 4))
print("truncate to k=2 :", tsvd_filter(2))
print("effective degrees of freedom (sum of filter factors), ridge lambda=1:", round(ridge_filter(1.0).sum(), 4), "; truncation k=2:", tsvd_filter(2).sum())
# Exact bias and variance per direction. alpha_i = v_i^T beta_true is the true coefficient along direction i.
def mse_parts(f, alpha):
mean_coef = f * alpha # E[estimate] along each direction
bias2 = (mean_coef - alpha)**2
var = noise_sd**2 * f**2 / sig**2 # Var of (f_i / sigma_i) * u_i^T noise
return bias2.sum(), var.sum()
estimators = {"OLS": np.ones(3), "ridge 0.01": ridge_filter(0.01), "ridge 0.1": ridge_filter(0.1),
"ridge 1": ridge_filter(1.0), "truncate k=2": tsvd_filter(2), "truncate k=1": tsvd_filter(1)}
cases = {"A: no weight on the weak direction": np.array([3.0, 2.0, 0.0]),
"B: weight 1 on the weak direction": np.array([3.0, 2.0, 1.0])}
for name, alpha in cases.items():
print(f"\ncase {name}, alpha = {alpha}")
print("estimator bias^2 variance total MSE")
for en, f in estimators.items():
b2, v = mse_parts(f, alpha)
print(f"{en:14s} {b2:9.4f} {v:11.4f} {b2 + v:11.4f}")
# Check the SVD formulas against library solvers on one noisy data set
beta_true = V @ cases["B: weight 1 on the weak direction"]
y = X @ beta_true + noise_sd * rng.normal(size=n)
Uh, s, Vt = np.linalg.svd(X, full_matrices=False)
lam = 0.1
b_ridge_svd = Vt.T @ ((s / (s**2 + lam)) * (Uh.T @ y))
b_ridge_sk = Ridge(alpha=lam, fit_intercept=False).fit(X, y).coef_
b_trunc = Vt.T @ (np.array([1/s[0], 1/s[1], 0.0]) * (Uh.T @ y))
b_pinv = np.linalg.pinv(X, rcond=1e-2) @ y
b_ols = np.linalg.lstsq(X, y, rcond=None)[0]
print("\nridge via SVD matches sklearn Ridge:", np.allclose(b_ridge_svd, b_ridge_sk))
print("truncated SVD matches pinv(rcond=1e-2):", np.allclose(b_trunc, b_pinv))
print("true beta :", np.round(beta_true, 3))
print("OLS :", np.round(b_ols, 3))
print("ridge 0.1 :", np.round(b_ridge_svd, 3))
print("truncate k=2:", np.round(b_trunc, 3))
# Monte Carlo check of the variance formula for ridge lambda = 0.1 (case B)
draws = 20000
noise = noise_sd * rng.normal(size=(draws, n))
Y = (X @ beta_true)[None, :] + noise
B = Y @ (Vt.T @ np.diag(s / (s**2 + lam)) @ Uh.T).T
mc_mse = ((B - beta_true)**2).sum(axis=1).mean()
b2, v = mse_parts(ridge_filter(lam), cases["B: weight 1 on the weak direction"])
print(f"ridge 0.1, case B: simulated MSE {mc_mse:.3f} vs formula {b2 + v:.3f}")
# Best achievable MSE for ridge (over a lambda grid) and for truncation (over k), for two spectra
def best_mse(sigma, alpha):
def mse(f):
return ((f * alpha - alpha)**2).sum() + (noise_sd**2 * f**2 / sigma**2).sum()
grid = 10.0 ** np.arange(-6, 3, 0.05)
ridge = min((mse(sigma**2 / (sigma**2 + l)), l) for l in grid)
trunc = min((mse((np.arange(len(sigma)) < k).astype(float)), k) for k in range(1, len(sigma) + 1))
return ridge, trunc
for label, sigma in (("sharp gap ", np.array([10.0, 8.0, 6.0, 0.02, 0.01, 0.01])),
("smooth fall", 10.0 * 0.5 ** np.arange(6))):
alpha = np.ones(6)
(r, lam_best), (t, k_best) = best_mse(sigma, alpha)
print(f"{label} sigma={np.round(sigma, 2)}: best ridge MSE {r:.3f} (lambda {lam_best:.3g}), best truncation MSE {t:.3f} (k {k_best})")
Output:
sigma : [10. 1. 0.01]
ridge lambda=0.1 : [0.999 0.9091 0.001 ]
ridge lambda=1 : [9.901e-01 5.000e-01 1.000e-04]
truncate to k=2 : [1. 1. 0.]
effective degrees of freedom (sum of filter factors), ridge lambda=1: 1.4902 ; truncation k=2: 2.0
case A: no weight on the weak direction, alpha = [3. 2. 0.]
estimator bias^2 variance total MSE
OLS 0.0000 2500.2525 2500.2525
ridge 0.01 0.0004 0.4926 0.4930
ridge 0.1 0.0331 0.2116 0.2447
ridge 1 1.0009 0.0650 1.0659
truncate k=2 0.0000 0.2525 0.2525
truncate k=1 4.0000 0.0025 4.0025
case B: weight 1 on the weak direction, alpha = [3. 2. 1.]
estimator bias^2 variance total MSE
OLS 0.0000 2500.2525 2500.2525
ridge 0.01 0.9807 0.4926 1.4733
ridge 0.1 1.0311 0.2116 1.2427
ridge 1 2.0007 0.0650 2.0657
truncate k=2 1.0000 0.2525 1.2525
truncate k=1 5.0000 0.0025 5.0025
ridge via SVD matches sklearn Ridge: True
truncated SVD matches pinv(rcond=1e-2): True
true beta : [ 0.36 -3.655 0.717]
OLS : [40.896 -7.958 32.41 ]
ridge 0.1 : [-0.204 -3.87 -0.125]
truncate k=2: [-0.138 -4.021 -0.31 ]
ridge 0.1, case B: simulated MSE 1.240 vs formula 1.243
sharp gap sigma=[10. 8. 6. 0.02 0.01 0.01]: best ridge MSE 3.011 (lambda 0.251), best truncation MSE 3.013 (k 3)
smooth fall sigma=[10. 5. 2.5 1.25 0.62 0.31]: best ridge MSE 1.298 (lambda 0.251), best truncation MSE 1.853 (k 5)
Reading it:
- Filter factors: for λ=1 they are 0.990, 0.5 and 0.0001; the weak direction is removed almost completely, the middle one halved, and the effective degrees of freedom are 1.4902 against 2 for truncation to k=2.
- Ordinary least squares has variance 0.25/10−4=2500 along the weak direction, and 2500+0.25/1+0.25/100=2500.2525 in total (printed as 2500.25), so nearly all of it comes from the weak direction; one noisy fit gave a coefficient of 40.9 against a true 0.36. Ridge with λ=0.1 gives a total error of 0.2447 in case A and 1.2427 in case B; truncating to k=2 gives 0.2525 and 1.2525. In case B the weak direction carries a real signal that both methods give up (bias squared 1.0311 for ridge, 1.0000 for truncation); that is the price of stability.
- A penalty that is too large is also bad: λ=1 shrinks the middle direction too and ends at 1.0659 (case A) and 2.0657 (case B).
- With a sharp gap between large and tiny singular values, the best ridge and the best truncation tie (3.011 against 3.013). With a smoothly falling spectrum, the middle directions are partly informative, and shrinking them (ridge, 1.298) beats keeping or discarding them whole (best truncation, 1.853). These numbers are for the stated spectra, signal and noise level, with the penalty chosen using the true coefficients; in practice λ and k come from cross-validation (hold part of the data out, fit on the rest, and keep the value with the smallest error on the held-out part).
Comparing ridge with dropping small singular values
| Ridge | Truncated SVD | |
|---|---|---|
| Filter | smooth, σi2/(σi2+λ) | 1 for the top k, 0 after |
| Tuning parameter | λ, continuous | k, an integer |
| Bias | small shrinkage on every direction | none on kept directions, total loss on dropped ones |
| Rank-deficient (some directions have zero stretch) or p>n | unique solution for λ>0; tends to the minimum-norm solution (the shortest coefficient vector among the least-squares solutions) as λ→0+ | the pseudo-inverse with a cutoff |
| Coefficients | all nonzero, biased toward zero | restricted to the span (all combinations) of v1,…,vk |
A deeper point, the Bayesian reading: if you believe before seeing data that each coefficient is drawn from a bell-curve (Gaussian) prior with mean zero and variance τ2, the most probable coefficients after seeing the data (the posterior mode) are the ridge solution with λ=η2/τ2.
Pitfalls
- Penalty depends on feature scale, so standardise first; do not penalise the intercept.
- Ridge biases coefficients, so classical standard errors and p-values no longer apply directly.
- Neither method creates information. If the interpretation of an individual correlated coefficient is the goal, merge or drop features instead.
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.
Explain singular value decomposition. How is it used to compute PCA, and how do singular values relate to variance explained?
Sample Answer
The idea in plain words
The singular value decomposition (SVD) writes any matrix X (any shape, no square or symmetric requirement) as a rotation, a stretch along the axes, and another rotation:
X=UΣV⊤
For a data matrix with n rows (samples) and d columns (features), after dropping empty directions:
- U is n×r with orthonormal columns (each column has length 1 and any two columns are perpendicular, so U⊤U=I); these are the left singular vectors, one coordinate per sample.
- Σ is an r×r diagonal matrix of singular values σ1≥σ2≥⋯≥0 (how much the matrix stretches along each axis).
- V is d×r with orthonormal columns (the right singular vectors, directions in feature space).
- r is the rank: the number of independent directions the matrix really uses, which equals its number of nonzero singular values and is at most min(n,d).
PCA (principal component analysis) finds the orthogonal directions in feature space that carry the most variance. The insight: if Xc is the data with each column's mean subtracted, its SVD gives those directions directly. The columns of V are the principal directions, and each singular value gives the variance along its direction.
Mechanism, in order
- Center. Subtract each column's mean: Xc=X−1μ⊤, with μ the vector of column means. This step is not optional (see the last example below).
- Decompose. Xc=UΣV⊤.
- Relate to the covariance. The sample covariance matrix is C=n−11Xc⊤Xc, and substituting the SVD gives
C=n−11VΣU⊤UΣV⊤=Vn−1Σ2V⊤
since U⊤U=I. That is an eigendecomposition of C: the eigenvectors are the columns of V and the eigenvalues are σi2/(n−1).
Step 3 on four points: the program below takes four centered points in two features, computes Xc⊤Xc/(n−1) directly, and checks that Vdiag(σi2/(n−1))V⊤ gives the same matrix. It then builds a matrix with singular values 1 and 1e-9 to show the condition-number effect discussed under the cost heading.
import numpy as np
# four centered points in 2 features: check C = V diag(S^2/(n-1)) V^T by hand-sized numbers
Xc = np.array([[3.0, 2.0], [1.0, 0.0], [-1.0, 0.0], [-3.0, -2.0]])
n = len(Xc)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
C = Xc.T @ Xc / (n - 1)
print("Xc^T Xc / (n-1) =", C.tolist())
print("singular values:", np.round(S, 4), " S^2/(n-1):", np.round(S**2 / (n - 1), 4))
print("eigenvalues of C:", np.round(np.linalg.eigvalsh(C)[::-1], 4))
print("V diag(S^2/(n-1)) V^T equals C:", np.allclose(Vt.T @ np.diag(S**2 / (n - 1)) @ Vt, C))
print("columns of V have length 1 and are perpendicular (V^T V = I):", np.allclose(Vt @ Vt.T, np.eye(2)))
print("rank (number of nonzero singular values):", int((S > 1e-10).sum()))
# squaring the condition number: singular values 1 and 1e-9
rng = np.random.default_rng(0)
Q1, _ = np.linalg.qr(rng.normal(size=(50, 2)))
Q2, _ = np.linalg.qr(rng.normal(size=(2, 2)))
X = Q1 @ np.diag([1.0, 1e-9]) @ Q2.T
s = np.linalg.svd(X, compute_uv=False)
print("SVD of X, singular values:", s, " condition number:", f"{s[0] / s[1]:.2e}")
ev = np.linalg.eigvalsh(X.T @ X)[::-1]
print("eigenvalues of X^T X:", ev, " (true values 1 and 1e-18)")
print("sqrt of those eigenvalues:", np.sqrt(np.abs(ev)))
Output:
Xc^T Xc / (n-1) = [[6.666666666666667, 4.0], [4.0, 2.6666666666666665]]
singular values: [5.2361 0.7639] S^2/(n-1): [9.1388 0.1945]
eigenvalues of C: [9.1388 0.1945]
V diag(S^2/(n-1)) V^T equals C: True
columns of V have length 1 and are perpendicular (V^T V = I): True
rank (number of nonzero singular values): 2
SVD of X, singular values: [1.00000000e+00 1.00000001e-09] condition number: 1.00e+09
eigenvalues of X^T X: [1.00000000e+00 6.37266093e-17] (true values 1 and 1e-18)
sqrt of those eigenvalues: [1.0000000e+00 7.9828948e-09]
Reading it: the covariance matrix is (6.667442.667), its eigenvalues 9.1388 and 0.1945 equal σi2/(n−1) for the singular values 5.2361 and 0.7639 (5.23612/3=9.1388), the columns of V have length 1 and are perpendicular, and the rank is 2. The last block of the output is used in the cost section below.
- Variance explained. Variance along component i is λi=σi2/(n−1), and the explained variance ratio is λi/∑jλj. The divisor n−1 is the sample-variance convention (the one
np.covand scikit-learn's PCA use); with divisor n every variance scales by the same constant, so the ratios do not change. - Project. The component scores (coordinates of each sample in the new basis) are XcVk=UkΣk, using the first k columns.
Worked example
The program builds 200 samples in 5 features from 2 hidden factors plus small noise and a nonzero mean. It computes PCA three ways (SVD, eigendecomposition of the covariance, scikit-learn) and checks that they agree. It also prints a wrong-divisor check that is expected to fail, and shows what skipping the centering does.
import numpy as np
from sklearn.decomposition import PCA
rng = np.random.default_rng(0)
n, d = 200, 5
latent = rng.normal(size=(n, 2)) * np.array([4.0, 2.0])
W = rng.normal(size=(2, d))
X = latent @ W + 0.5 * rng.normal(size=(n, d)) + np.array([10.0, -3.0, 0.0, 5.0, 1.0])
# PCA through SVD of the CENTERED data matrix (n x d)
Xc = X - X.mean(axis=0)
U, S, Vt = np.linalg.svd(Xc, full_matrices=False) # U: n x d, S: d, Vt: d x d
print("shapes U, S, Vt:", U.shape, S.shape, Vt.shape)
# variance along component i = S_i^2 / (n - 1) (sample variance, divisor n-1)
var_svd = S**2 / (n - 1)
ratio = var_svd / var_svd.sum()
print("variance from SVD: ", np.round(var_svd, 4))
print("explained variance ratio:", np.round(ratio, 4))
# same thing via eigendecomposition of the covariance matrix (also divisor n-1)
evals, evecs = np.linalg.eigh(np.cov(X, rowvar=False))
evals = evals[::-1]
print("eigenvalues of covariance:", np.round(evals, 4))
print("S^2/(n-1) equals eigenvalues:", np.allclose(var_svd, evals))
print("S^2/n equals eigenvalues:", np.allclose(S**2 / n, evals))
# compare with scikit-learn (it centers internally; components match up to sign)
pca = PCA(n_components=d).fit(X)
print("sklearn explained_variance_:", np.round(pca.explained_variance_, 4))
print("matches SVD variances:", np.allclose(pca.explained_variance_, var_svd))
same_axes = np.allclose(np.abs(pca.components_), np.abs(Vt))
print("components match up to sign:", same_axes)
# scores: projecting onto the top k components, two equivalent ways
k = 2
scores_a = Xc @ Vt[:k].T
scores_b = U[:, :k] * S[:k]
print("scores via Xc @ V equal U*S:", np.allclose(scores_a, scores_b))
# skipping the centering step changes the answer
U2, S_unc, Vt2 = np.linalg.svd(X, full_matrices=False)
print("top singular value, centered vs uncentered:", round(S[0], 3), round(S_unc[0], 3))
mean_dir = X.mean(0) / np.linalg.norm(X.mean(0))
print("|cosine| of first component with the mean direction, centered: ", round(abs(Vt[0] @ mean_dir), 3))
print("|cosine| of first component with the mean direction, uncentered:", round(abs(Vt2[0] @ mean_dir), 3))
# truncated / randomized SVD: only the top 2 components, as used for large data
rp = PCA(n_components=2, svd_solver="randomized", random_state=0).fit(X)
print("randomized top-2 variances:", np.round(rp.explained_variance_, 4))
print("close to the full SVD's top 2:", np.allclose(rp.explained_variance_, var_svd[:2], rtol=1e-3))
Output:
shapes U, S, Vt: (200, 5) (5,) (5, 5)
variance from SVD: [139.5319 8.4273 0.2688 0.2384 0.2119]
explained variance ratio: [0.9385 0.0567 0.0018 0.0016 0.0014]
eigenvalues of covariance: [139.5319 8.4273 0.2688 0.2384 0.2119]
S^2/(n-1) equals eigenvalues: True
S^2/n equals eigenvalues: False
sklearn explained_variance_: [139.5319 8.4273 0.2688 0.2384 0.2119]
matches SVD variances: True
components match up to sign: True
scores via Xc @ V equal U*S: True
top singular value, centered vs uncentered: 166.634 169.18
|cosine| of first component with the mean direction, centered: 0.032
|cosine| of first component with the mean direction, uncentered: 0.718
randomized top-2 variances: [139.5319 8.4273]
close to the full SVD's top 2: True
What the output shows:
- Shapes: U is 200 by 5, Σ is stored as a length-5 vector, and V⊤ is 5 by 5.
- σi2/(n−1) equals the covariance eigenvalues (True), and equals scikit-learn's
explained_variance_(True). Dividing by n instead is False, which is the check that the divisor matters. - The first component carries 0.9385 of the variance and the second 0.0567, so two components keep about 0.9952 of it, as expected from 2 hidden factors.
- Components match scikit-learn up to sign. The sign of a singular vector is arbitrary, so comparisons use absolute values.
- Without centering, the top singular value changes from 166.634 to 169.18 and the first direction tilts toward the mean. Its absolute cosine with the mean direction is 0.718 uncentered versus 0.032 centered; how far it tilts depends on how large the mean is compared with the spread of the data. Uncentered, the first "component" is partly just the direction from the origin to the data cloud, not the direction of greatest spread.
Cost for large datasets
- Full SVD of an n×d matrix costs on the order of ndmin(n,d) operations. Forming the covariance first costs about nd2 and then a d×d eigendecomposition costs about d3. Squaring the data this way also squares the condition number (the ratio of the largest to the smallest singular value, a measure of how lopsided the matrix is), which loses precision for small singular values, so the SVD of the data matrix is the more accurate route. In the last block of the four-point program's output, a matrix with singular values 1 and 1e-9 (condition number 1e9) is decomposed correctly by the SVD (1 and 1.00000001e-09), but the eigenvalues of X⊤X come out as 1 and 6.37e-17 instead of 1e-18. The second value is rounding noise: 64-bit floats resolve about 16 digits, so against an eigenvalue of 1 anything near 1e-16 cannot be told from zero, and the squared condition number 1e18 is beyond that reach. Its size and even its sign change from matrix to matrix (200 other random matrices with the same singular values gave values between about -3e-16 and +3e-16, negative roughly half the time, which is why the code takes the absolute value before the square root). Here the square root, 7.98e-09, is nearly 8 times the true 1e-9, and on another matrix it could be larger, or zero.
- For ordinary data (up to thousands of columns) the full SVD of the centered matrix is the right default. When you need only the top k components (the number you want to keep) with k≪min(n,d), use a truncated SVD (iterative Lanczos-type methods, which find the few leading singular vectors using only products of the matrix with vectors) or a randomized SVD. Randomized SVD multiplies Xc by a random d×(k+p) matrix, where p is a small number of extra random columns (the oversampling, for example 5 to 10) that make a good approximation more likely; the product is a sketch, a much smaller matrix n×(k+p) that captures the dominant directions of Xc. An exact SVD of the small sketch then gives the answer. Cost drops to roughly nd(k+p). In the program, scikit-learn's randomized solver with
random_state=0returns top-2 variances that match the full SVD to the printed precision. - Randomized methods are approximate. They are most accurate when singular values decay quickly; with a flat spectrum (singular values that decay slowly), add oversampling p or power iterations (multiplying by Xc⊤Xc a few times before sketching, which widens the gap between large and small singular values).
Common mistakes
- Forgetting to center (shown above), or centering but not scaling when features have different units.
- Confusing singular values with variances: the variance is the singular value squared, divided by n−1.
- Assuming eigenvectors and singular vectors come with a fixed sign.
- Choosing k by a fixed variance target alone: look at the spectrum for a gap, and judge the downstream task.
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∣.
Unlock Full Question Bank
Get access to all 8 Linear Algebra and Numerical Computing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.