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.
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.
Minimize x^2 + y^2 subject to x + y = 1 using Lagrange multipliers. Show the steps and explain the geometric meaning of the solution.
Sample Answer
The idea in plain words
We want the point closest to the origin (smallest x2+y2) among points on the line x+y=1. A Lagrange multiplier turns a constrained problem into an unconstrained one by adding the constraint, scaled by a new variable λ, to the objective. At the best constrained point the objective cannot be improved by sliding along the constraint, which means the objective's gradient points straight across the constraint, parallel to the constraint's own gradient.
Steps
Objective f(x,y)=x2+y2, constraint g(x,y)=x+y−1=0. Form the Lagrangian:
L(x,y,λ)=x2+y2−λ(x+y−1)
Set each partial derivative to zero (a point where they all vanish is called stationary: the function is flat there to first order, so it is a candidate for a minimum, maximum or saddle):
∂x∂L∂y∂L∂λ∂L=2x−λ=0=2y−λ=0=−(x+y−1)=0The first two give x=y=λ/2. The third gives x+y=1, so λ=1 and
x=y=21,f=41+41=21
A picture in numbers shows why tangency is the condition. At the feasible point (1,0) the objective's gradient is (2,0), which is not parallel to the constraint's gradient (1,1), so part of ∇f points along the line and sliding along the line changes f. Sliding to (0.9,0.1) stays on the line and lowers f:
import numpy as np
f = lambda p: p[0] ** 2 + p[1] ** 2
p = np.array([1.0, 0.0]) # on the line x + y = 1, but not the optimum
print("at (1, 0): grad f =", 2 * p, " grad g = [1. 1.] cross product =", 2 * p[0] * 1.0 - 2 * p[1] * 1.0)
q = p + 0.1 * np.array([-1.0, 1.0]) # slide along the line (direction (-1, 1) keeps x + y = 1)
print("f(1, 0) =", f(p), " f after sliding to", np.round(q, 1), "=", round(f(q), 2), " still on the line:", q.sum())
Output:
at (1, 0): grad f = [2. 0.] grad g = [1. 1.] cross product = 2.0
f(1, 0) = 1.0 f after sliding to [0.9 0.1] = 0.82 still on the line: 1.0
At the optimum no such slide helps.
This is three equations in three unknowns, and for this problem they are linear, so the program solves them as one linear system, then checks the result several ways.
import numpy as np
from scipy.optimize import minimize
# L(x, y, lam) = x^2 + y^2 - lam * (x + y - c). Stationarity in x, y and the constraint form a LINEAR system:
# 2x - lam = 0, 2y - lam = 0, x + y = c unknowns (x, y, lam)
def solve_lagrange(c):
K = np.array([[2.0, 0.0, -1.0],
[0.0, 2.0, -1.0],
[1.0, 1.0, 0.0]])
rhs = np.array([0.0, 0.0, c])
x, y, lam = np.linalg.solve(K, rhs)
return x, y, lam
x, y, lam = solve_lagrange(1.0)
print(f"x = {x:.4f}, y = {y:.4f}, lambda = {lam:.4f}, f = {x**2 + y**2:.4f}")
# Geometry 1: at the solution, grad f = (2x, 2y) is parallel to grad g = (1, 1)
gf, gg = np.array([2 * x, 2 * y]), np.array([1.0, 1.0])
print("grad f:", gf, " grad g:", gg, " cross product (0 means parallel):", gf[0] * gg[1] - gf[1] * gg[0])
print("grad f = lambda * grad g:", np.allclose(gf, lam * gg))
# Geometry 2: the constrained minimum is the squared distance from the origin to the line x + y = 1
print("squared distance from origin to the line:", round((1 / np.sqrt(2)) ** 2, 4))
# Check against a general-purpose constrained optimizer
res = minimize(lambda p: p[0] ** 2 + p[1] ** 2, x0=[2.0, -1.0], method="SLSQP",
constraints=[{"type": "eq", "fun": lambda p: p[0] + p[1] - 1.0}])
print("SLSQP solution:", np.round(res.x, 4), " matches:", np.allclose(res.x, [x, y], atol=1e-5))
# Meaning of lambda: the rate at which the optimal value changes when the constraint level c moves
h = 1e-5
fstar = lambda c: sum(np.square(solve_lagrange(c)[:2]))
print("finite-difference d f*/dc at c = 1:", round((fstar(1 + h) - fstar(1 - h)) / (2 * h), 4))
# Is the stationary point a minimum? Compare with other points on the constraint line
ts = np.linspace(-2, 3, 1001)
vals = [t**2 + (1 - t) ** 2 for t in ts]
print("min of f along the line over a grid:", round(min(vals), 4), "at x =", round(float(ts[int(np.argmin(vals))]), 3))
Output:
x = 0.5000, y = 0.5000, lambda = 1.0000, f = 0.5000
grad f: [1. 1.] grad g: [1. 1.] cross product (0 means parallel): 0.0
grad f = lambda * grad g: True
squared distance from origin to the line: 0.5
SLSQP solution: [0.5 0.5] matches: True
finite-difference d f*/dc at c = 1: 1.0
min of f along the line over a grid: 0.5 at x = 0.5
Geometric meaning
- Tangency. The level sets of f (the contour curves along which f is constant) are circles centred at the origin; the constraint is a line. The optimum is where the smallest circle that touches the line just touches it, and the circle and the line are tangent there. The tangent condition is that the two gradients are parallel: ∇f=λ∇g. In two dimensions the cross product a1b2−a2b1 of two vectors is zero exactly when they are parallel, which is why the program prints it. The output shows ∇f=(1,1), ∇g=(1,1), a cross product of 0 and λ=1.
- Distance. The answer is the foot of the perpendicular from the origin to the line, at squared distance (1/2)2=1/2, matching f=0.5.
- Meaning of λ. It is the sensitivity of the optimal value to the constraint level. If the constraint is x+y=c, the optimum is x=y=c/2 with value c2/2, whose derivative at c=1 is 1. The finite-difference line in the output reports 1.0, equal to λ. In economics this is the "shadow price": the amount the best achievable value changes per unit of loosening of the constraint, such as per extra unit of budget.
Pitfalls
- Stationary is not the same as minimum. The Lagrange conditions find candidates. Here substituting y=1−x gives 2x2−2x+1, whose second derivative is 4 > 0, so the point is a minimum, and a fine grid along the line (last line of output) agrees.
- Sign convention. Writing +λ(x+y−1) instead flips the sign of λ to −1 but gives the same x and y.
- Constraint qualification. A constraint qualification is a regularity condition that guarantees the multiplier conditions apply; the simplest one is that the constraint gradient is nonzero at the optimum (here it is (1,1)). It matters because the same line can be written as (x+y−1)2=0, whose gradient is zero everywhere on the line, and then the equations ∇f=λ∇g force x=y=0, which is not on the line, so they miss the answer.
- Inequalities (a typical next question). A constraint like x+y≥1 needs the KKT (Karush-Kuhn-Tucker) conditions, which add the rule that the multiplier is nonnegative and zero when the constraint is not binding.
Derive the gradient with respect to a matrix X of trace(A X B) and of log det X, and check the shapes. Where do these identities show up in machine learning, for example in the maximum-likelihood estimate of a Gaussian's covariance?
Sample Answer
The short answer
Use the convention that the gradient of a scalar f(X) with respect to a matrix X is the matrix of partial derivatives ∂f/∂Xij, so it has the same shape as X. Then, for A of size p×m, X of size m×q, B of size q×p:
∇Xtr(AXB)=A⊤B⊤=(BA)⊤,∇XlogdetX=X−⊤(the trace tr of a square matrix is the sum of its diagonal entries; the second identity holds for invertible X with detX>0, or with log∣detX∣ in general). Notation: q is a matrix dimension here; from the Gaussian section on, n counts samples and d is the data dimension, while a d written in front of a symbol (df, dX) always means a small change in it. Setting a gradient of the Gaussian log-likelihood to zero with these two identities gives the maximum-likelihood covariance Σ^=n1∑i(xi−μ^)(xi−μ^)⊤, which divides by n, not n−1.
The tool: the differential and the Frobenius inner product
Matrix-calculus derivations are easiest by writing the first-order change df in terms of a small change dX and matching it to ⟨G,dX⟩=tr(G⊤dX)=∑ijGijdXij (the Frobenius inner product: multiply entries pairwise and sum). Whatever G makes that match is the gradient, and it automatically has the shape of X. For example, the trace of (1324) is 1+4=5. The trace is cyclic, tr(PQR)=tr(RPQ) whenever the products are defined, and a trace is unchanged by transposing: tr(M)=tr(M⊤).
Gradient of tr(AXB). The map is linear in X, so df=tr(AdXB). Cycle the trace: tr(AdXB)=tr(BAdX)=tr(((BA)⊤)⊤dX)=⟨(BA)⊤,dX⟩. So the gradient is (BA)⊤=A⊤B⊤.
Entry-wise check: tr(AXB)=∑k,i,jAkiXijBjk, so ∂/∂Xij is ∑kBjkAki=(BA)ji. Entry (i,j) of the gradient is the entry (j,i) of BA, which is the transpose.
Shape check. AXB is p×p so its trace is a scalar. BA is q×m (here (q×p)(p×m)), so (BA)⊤ is m×q, the shape of X. Writing BA without the transpose gives the wrong shape, and that mismatch is the quickest way to catch a dropped transpose.
A 2 by 2 instance. Take A=(1021), B=(1101) and X=(x11x21x12x22). Then BA=(1123), and writing out tr(AXB) gives x11+x12+2x21+3x22. Each coefficient is a partial derivative, so the gradient is (1213)=(BA)⊤, and the transpose is visible: the coefficient of x12 is the entry in row 2, column 1 of BA.
import numpy as np
A = np.array([[1.0, 2.0], [0.0, 1.0]])
B = np.array([[1.0, 0.0], [1.0, 1.0]])
X = np.array([[1.0, 2.0], [3.0, 4.0]])
print("trace of [[1, 2], [3, 4]] =", np.trace(X), "(1 + 4, the diagonal entries)")
f = lambda M: np.trace(A @ M @ B)
print("f(X) = tr(A X B) =", f(X))
claimed = (B @ A).T
print("claimed gradient (BA)^T =", claimed.tolist())
for i in range(2):
for j in range(2):
E = np.zeros((2, 2)); E[i, j] = 1.0
print(f" raising X[{i+1},{j+1}] by 1 changes f by {f(X + E) - f(X):.1f} (gradient entry {claimed[i, j]:.1f})")
Output:
trace of [[1, 2], [3, 4]] = 5.0 (1 + 4, the diagonal entries)
f(X) = tr(A X B) = 21.0
claimed gradient (BA)^T = [[1.0, 1.0], [2.0, 3.0]]
raising X[1,1] by 1 changes f by 1.0 (gradient entry 1.0)
raising X[1,2] by 1 changes f by 1.0 (gradient entry 1.0)
raising X[2,1] by 1 changes f by 2.0 (gradient entry 2.0)
raising X[2,2] by 1 changes f by 3.0 (gradient entry 3.0)
At X=(1324) the value is 1+2+6+12=21, and raising each entry by 1 changes it by exactly its coefficient, because the function is linear in X.
Gradient of logdetX. For small E, det(I+E)=1+trE+O(∥E∥2) (the determinant is the product of the eigenvalues 1+εi, and the first-order terms add up to the trace). Then
det(X+dX)=detXdet(I+X−1dX)≈detX(1+tr(X−1dX)),so dlogdetX=tr(X−1dX)=⟨X−⊤,dX⟩ and the gradient is X−⊤. Entry-wise: expanding the determinant along row i gives detX=∑jXijCij with Cij the cofactors (signed minors, which do not involve row i), so ∂detX/∂Xij=Cij=detX(X−1)ji, and dividing by detX gives (X−1)ji, again a transpose. When X is symmetric (a covariance or precision matrix) the result X−1 is symmetric and the transpose is invisible, which is why the mistake of dropping it survives in practice until a non-symmetric matrix shows up.
The program checks both identities against central finite differences (the numerical derivative (f(X+hE)−f(X−hE))/2h for each entry) on a 2×3, 3×4, 4×2 triple and a non-symmetric 3×3 matrix.
Where they show up: the Gaussian covariance MLE
Take n independent samples xi∈Rd from a Gaussian with mean μ and covariance Σ. Let Θ=Σ−1 (the precision matrix) and S=∑i(xi−μ)(xi−μ)⊤ (the scatter matrix, a d×d sum of outer products). The log-likelihood is
ℓ(μ,Θ)=2nlogdetΘ−21i∑(xi−μ)⊤Θ(xi−μ)−2ndlog2πand each quadratic form is a trace: (xi−μ)⊤Θ(xi−μ)=tr(Θ(xi−μ)(xi−μ)⊤), so the sum is tr(ΘS). Then:
- Mean. Setting the gradient in μ to zero gives Θ∑i(xi−μ)=0, so μ^ is the sample mean. Use it inside S from now on.
- Covariance. Using ∇ΘlogdetΘ=Θ−⊤=Θ−1 (the matrix is symmetric) and ∇Θtr(ΘS)=S⊤=S (the trace identity with A=I, B=S):
- It is a maximum. logdet is concave (it curves downward, so a stationary point is a global maximum) on positive definite matrices (symmetric matrices whose eigenvalues are all positive), and −tr(ΘS) is linear in Θ, so ℓ is concave in Θ and the stationary point is the global maximum. The likelihood does not care what its parameter is called: Σ↦Σ−1 pairs each covariance with exactly one precision matrix, so the best precision matrix is the inverse of the best covariance (the maximum-likelihood estimate is invariant under one-to-one reparametrisation).
One subtlety: Θ is symmetric, yet step 2 differentiated as if its entries were independent. That is safe here because the stationary point S/n it produced is already symmetric, so it satisfies the constraint and is also the maximiser of the constrained problem.
Differentiating directly in Σ gives the same answer but needs one more identity, d(Σ−1)=−Σ−1dΣΣ−1, which makes ∇Σtr(Σ−1S)=−Σ−1SΣ−1 and ∇Σℓ=−2nΣ−1+21Σ−1SΣ−1; setting it to zero gives Σ=S/n again.
Run with NumPy 2.1.3 (seed 0, n=200 points in d=3 dimensions drawn from a known covariance), the program verifies this:
import numpy as np
def num_grad(f, X, h=1e-6):
"""Central finite differences, one entry of X at a time; the result has the same shape as X."""
G = np.zeros_like(X)
for idx in np.ndindex(*X.shape):
E = np.zeros_like(X); E[idx] = h
G[idx] = (f(X + E) - f(X - E)) / (2 * h)
return G
rng = np.random.default_rng(0)
print("1) f(X) = trace(A X B), A is 2x3, X is 3x4, B is 4x2")
A = rng.normal(size=(2, 3)); X = rng.normal(size=(3, 4)); B = rng.normal(size=(4, 2))
f = lambda X: np.trace(A @ X @ B)
G_formula = A.T @ B.T # claimed gradient = (B A)^T
print(" shapes: A X B", (A @ X @ B).shape, " B A", (B @ A).shape, " gradient", G_formula.shape, " X", X.shape)
print(" finite-difference gradient matches A^T B^T:", np.allclose(num_grad(f, X), G_formula, atol=1e-7))
print(" wrong version B A (no transpose) has shape", (B @ A).shape, "and does not match X's shape")
print("\n2) g(X) = log det X, X is 3x3 and not symmetric")
X = rng.normal(size=(3, 3)) + 2 * np.eye(3)
sign, _ = np.linalg.slogdet(X)
g = lambda X: np.linalg.slogdet(X)[1]
FD = num_grad(g, X)
print(" det X > 0:", bool(sign > 0))
print(" finite difference vs X^{-T}:", np.allclose(FD, np.linalg.inv(X).T, atol=1e-7), "| vs X^{-1} (forgetting the transpose):", np.allclose(FD, np.linalg.inv(X), atol=1e-7))
print("\n3) Gaussian covariance MLE")
n, d = 200, 3
Sigma_true = np.array([[2.0, 0.6, 0.0], [0.6, 1.0, -0.3], [0.0, -0.3, 0.5]])
data = rng.multivariate_normal(np.zeros(d), Sigma_true, size=n)
mu = data.mean(axis=0)
S = (data - mu).T @ (data - mu) # scatter matrix: sum of outer products
Sigma_hat = S / n
def loglik(Sigma): # log-likelihood of the n centred points, as a function of Sigma
return -0.5 * n * np.linalg.slogdet(Sigma)[1] - 0.5 * np.trace(np.linalg.solve(Sigma, S)) - 0.5 * n * d * np.log(2 * np.pi)
def loglik_theta(Theta): # the same log-likelihood as a function of the precision matrix
return 0.5 * n * np.linalg.slogdet(Theta)[1] - 0.5 * np.trace(Theta @ S) - 0.5 * n * d * np.log(2 * np.pi)
Theta_hat = np.linalg.inv(Sigma_hat)
Theta_off = 1.05 * Theta_hat
fd_hat, fd_off = num_grad(loglik_theta, Theta_hat), num_grad(loglik_theta, Theta_off)
print(" finite-difference gradient w.r.t. the precision matrix is zero at Theta_hat:", np.allclose(fd_hat, 0, atol=1e-5), "| zero at 1.05 * Theta_hat:", np.allclose(fd_off, 0, atol=1e-5))
print(" formula n/2 Theta^-1 - S/2 equals the finite difference at 1.05 * Theta_hat:", np.allclose(fd_off, 0.5 * n * np.linalg.inv(Theta_off) - 0.5 * S, atol=1e-4))
print(" Sigma_hat equals np.cov(data.T, bias=True):", np.allclose(Sigma_hat, np.cov(data.T, bias=True)), "; equals the default np.cov (divides by n-1):", np.allclose(Sigma_hat, np.cov(data.T)))
print(f" loglik at the MLE {loglik(Sigma_hat):.3f}; at S/(n-1) {loglik(S / (n - 1)):.3f}; at the true covariance {loglik(Sigma_true):.3f}")
def better_neighbours(C, tries=1000):
"""How many random symmetric perturbations of C (2% of its norm) raise the likelihood."""
count = 0
for _ in range(tries):
M = rng.normal(size=(d, d)); E = M + M.T
Pert = C + E * (0.02 * np.linalg.norm(C) / np.linalg.norm(E))
if np.all(np.linalg.eigvalsh(Pert) > 0) and loglik(Pert) > loglik(C) + 1e-9:
count += 1
return count
print(" random nearby matrices (1000 tries) with higher likelihood: around the MLE", better_neighbours(Sigma_hat), "| around 1.05 * MLE (5% too large)", better_neighbours(1.05 * Sigma_hat))
few = rng.normal(size=(3, 5)); Sf = (few - few.mean(axis=0)).T @ (few - few.mean(axis=0))
print(" n = 3 points in d = 5 dimensions: rank of the scatter matrix =", np.linalg.matrix_rank(Sf), "of 5, so S/n is singular (log det = -inf) and the likelihood has no finite maximum")
Output:
1) f(X) = trace(A X B), A is 2x3, X is 3x4, B is 4x2
shapes: A X B (2, 2) B A (4, 3) gradient (3, 4) X (3, 4)
finite-difference gradient matches A^T B^T: True
wrong version B A (no transpose) has shape (4, 3) and does not match X's shape
2) g(X) = log det X, X is 3x3 and not symmetric
det X > 0: True
finite difference vs X^{-T}: True | vs X^{-1} (forgetting the transpose): False
3) Gaussian covariance MLE
finite-difference gradient w.r.t. the precision matrix is zero at Theta_hat: True | zero at 1.05 * Theta_hat: False
formula n/2 Theta^-1 - S/2 equals the finite difference at 1.05 * Theta_hat: True
Sigma_hat equals np.cov(data.T, bias=True): True ; equals the default np.cov (divides by n-1): False
loglik at the MLE -809.827; at S/(n-1) -809.831; at the true covariance -812.905
random nearby matrices (1000 tries) with higher likelihood: around the MLE 0 | around 1.05 * MLE (5% too large) 152
n = 3 points in d = 5 dimensions: rank of the scatter matrix = 2 of 5, so S/n is singular (log det = -inf) and the likelihood has no finite maximum
Reading the output:
- Section 1: the finite-difference gradient matches A⊤B⊤, of shape 3×4; BA alone has shape 4×3.
- Section 2: the finite difference matches X−⊤ and does not match X−1 for a non-symmetric X.
- Section 3: a finite-difference derivative of the log-likelihood with respect to the precision matrix Θ is zero at Θ^=Σ^−1 and clearly nonzero at 1.05Θ^, where it agrees with the formula 2nΘ−1−21S; Σ^ equals
np.cov(data.T, bias=True)(which divides by n) and differs from the defaultnp.cov, which divides by n−1 for the unbiased estimate. The log-likelihood is −809.827 at the MLE, −809.831 at S/(n−1) and −812.905 at the true covariance, so the MLE has the highest likelihood on this sample. None of 1000 random nearby symmetric matrices (perturbations of 2% of the matrix norm) beat it, while the same test around a covariance estimate 5% too large (1.05 times the MLE) finds many that do, so the test can tell a wrong estimate from the right one; both results are consistent with concavity. - The last line: with n=3 points in d=5 dimensions the scatter matrix has rank 2, so S/n is singular and its logdet is −∞. The Gaussian likelihood then has no finite maximum (it grows without bound as the covariance squeezes towards the flat subspace that holds the data), so no usable MLE exists. The sample covariance needs at least d+1 points to be positive definite, one of the reasons covariance estimates are shrunk in high dimensions.
Where else these identities appear in machine learning
- Backpropagation through a linear layer. For Y=WX and a scalar loss, the same differential argument gives ∇WL=(∇YL)X⊤.
- Gaussian processes and Bayesian linear regression. The log marginal likelihood contains logdetK and y⊤K−1y, and hyperparameter gradients use tr(K−1∂K), which is the logdet identity.
- Gaussian graphical models. The graphical lasso maximises logdetΘ−tr(SΘ/n)−λ∥Θ∥1 over precision matrices, which is the average Gaussian log-likelihood above (up to a constant factor) plus an L1 penalty; zeros in Θ mean conditional independence (two variables are independent once all the others are known).
- Normalizing flows and change of variables. The density picks up log∣detJ∣ for the Jacobian J of the transform (the matrix of first partial derivatives of its outputs with respect to its inputs).
- Discriminant analysis. QDA fits one covariance per class with this estimator, and LDA fits one pooled covariance shared by all classes with the same estimator applied to the class-centred data.
Common mistakes
- Dropping the transpose in ∇logdetX=X−⊤ or ∇tr(AXB)=A⊤B⊤. The shape check catches the second; the first needs a non-symmetric test matrix.
- Returning a gradient whose shape is not the shape of the variable. Before trusting a formula, check its shape.
- Dividing by n−1 and calling it the MLE: S/(n−1) is the unbiased estimator, S/n is the maximum-likelihood one. They differ by the factor n/(n−1).
- Forgetting that logdet needs detX=0 (and log∣det∣ if negative), and that the MLE needs an invertible S.
Derive the gradient of f(x) = ||Ax - b||^2 with respect to x. What does setting it to zero give you, and when is the solution well defined?
Sample Answer
The idea in plain words
f(x)=∥Ax−b∥2 is the sum of squared residuals of a linear model: A is an m×n matrix (m equations or samples, n unknowns or features), x has n entries, and b has m entries. It is a quadratic bowl in x. Setting its gradient to zero gives the normal equations, and the bowl has a single lowest point exactly when the columns of A are linearly independent (no column can be built as a combination of the others).
Derivation
Write the squared norm as a product, ∥v∥2=v⊤v, and expand:
f(x)=(Ax−b)⊤(Ax−b)=x⊤A⊤Ax−2b⊤Ax+b⊤b
Use two standard rules for the gradient with respect to x (the vector of partial derivatives): the gradient of x⊤Mx is (M+M⊤)x, which is 2Mx when M is symmetric (and A⊤A is), and the gradient of c⊤x is c. With M=A⊤A and c=A⊤b (so b⊤Ax=c⊤x):
∇f(x)=2A⊤Ax−2A⊤b=2A⊤(Ax−b)
Where the two rules come from, on the smallest cases. In one dimension (n=m=1, A=a a single number) the loss is f(x)=(ax−b)2, and the ordinary chain rule gives f′(x)=2a(ax−b)=2a2x−2ab, which is the formula above with A⊤A=a2 and A⊤b=ab. For general n, write the quadratic form as a double sum, x⊤Mx=∑i,jMijxixj. The partial derivative with respect to xk picks up the terms where xk appears as xi (giving ∑jMkjxj=(Mx)k) and as xj (giving ∑iMikxi=(M⊤x)k), so the gradient is (M+M⊤)x. For the linear term, c⊤x=∑icixi has partial derivative ck with respect to xk, so its gradient is c.
Shapes: A⊤ is n×m and the residual Ax−b has m entries, so the gradient has n entries, like x. Read it as "each column of A, dotted with the residual".
Setting it to zero gives the normal equations:
A⊤Ax=A⊤b
They say the residual is orthogonal to every column of A: the best fit leaves nothing that a column could still explain. The Hessian (matrix of second derivatives) is 2A⊤A.
A hand-sized example
Three points (t,b)=(0,1),(1,2),(2,4), fitted by a line b≈x0+x1t. Each row of A is (1,t) and the unknowns are the intercept x0 and slope x1. The normal equations A⊤Ax=A⊤b become a 2 by 2 system that can be solved with pencil and paper, and the program checks the arithmetic and the orthogonality statement.
import numpy as np
# Three points (t, b): (0, 1), (1, 2), (2, 4); fit b = x0 + x1 * t
A = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]])
b = np.array([1.0, 2.0, 4.0])
AtA, Atb = A.T @ A, A.T @ b
print("A^T A =", AtA.tolist())
print("A^T b =", Atb.tolist())
x = np.linalg.solve(AtA, Atb)
print("solution of A^T A x = A^T b:", x, " 5/6 =", round(5 / 6, 4))
r = A @ x - b
print("residual:", np.round(r, 4), " A^T r:", np.round(A.T @ r, 12))
Output:
A^T A = [[3.0, 3.0], [3.0, 5.0]]
A^T b = [7.0, 10.0]
solution of A^T A x = A^T b: [0.83333333 1.5 ] 5/6 = 0.8333
residual: [-0.1667 0.3333 -0.1667] A^T r: [0. 0.]
By hand: A⊤A=(3335) (its determinant is 15−9=6), A⊤b=(7,10), and solving gives x0=5/6 and x1=3/2. The residuals sum to zero and are orthogonal to the slope column, which is exactly "A⊤ times the residual is zero".
When the solution is well defined
- Full column rank (the n columns of A are linearly independent, which needs m≥n): A⊤A is positive definite (all eigenvalues positive), so it is invertible, the bowl is strictly convex (it curves upward in every direction, so there is exactly one lowest point), and the unique minimizer is x⋆=(A⊤A)−1A⊤b.
- Rank deficient (the rank of A is its number of independent columns, and here it is less than n: some column is a combination of the others, or m<n): A⊤A is singular (not invertible, with a zero eigenvalue). A minimizer still exists (the normal equations are always solvable), but there are infinitely many, differing by vectors in the null space of A (the vectors z with Az=0, which change x without changing any prediction). The pseudoinverse A+ (computed from the SVD, the factorization A=UΣV⊤) returns the solution with the smallest norm, and adding a ridge penalty λ∥x∥2 (which turns A⊤A into A⊤A+λI) makes the answer unique again.
Worked example
The program fits a line to six points, checks the analytic gradient against central finite differences, solves the normal equations and compares with np.linalg.lstsq. It then duplicates a column to make A rank deficient and shows two different solutions with identical loss, adds ridge, and shows the condition number effect.
import numpy as np
np.set_printoptions(precision=4, suppress=True)
rng = np.random.default_rng(0)
# Full-column-rank case: 6 equations, 2 unknowns
A = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0], [1.0, 3.0], [1.0, 4.0], [1.0, 5.0]])
b = np.array([1.1, 2.9, 5.2, 7.1, 8.8, 11.2])
f = lambda x: np.sum((A @ x - b) ** 2)
grad = lambda x: 2 * A.T @ (A @ x - b)
# 1. Check the derived gradient against central finite differences at a random point
x = rng.normal(size=2)
eps = 1e-6
num = np.array([(f(x + eps * e) - f(x - eps * e)) / (2 * eps) for e in np.eye(2)])
print("analytic gradient: ", grad(x))
print("finite differences: ", num)
print("match:", np.allclose(grad(x), num, atol=1e-5))
print("match if the factor 2 is dropped:", np.allclose(grad(x) / 2, num, atol=1e-5))
# 2. Set the gradient to zero: normal equations A^T A x = A^T b
x_star = np.linalg.solve(A.T @ A, A.T @ b)
print("normal equations solution:", x_star)
print("largest |gradient| there below 1e-9:", np.abs(grad(x_star)).max() < 1e-9)
print("lstsq agrees:", np.allclose(x_star, np.linalg.lstsq(A, b, rcond=None)[0]))
print("Hessian 2 A^T A eigenvalues (all > 0):", np.linalg.eigvalsh(2 * A.T @ A))
# 3. Not well defined: duplicate a column, so A^T A is singular
B = np.hstack([A, A[:, [1]]]) # 6 x 3, columns 2 and 3 identical
print("rank of B:", np.linalg.matrix_rank(B), " columns:", B.shape[1])
print("smallest eigenvalue of B^T B is ~0:", abs(np.linalg.eigvalsh(B.T @ B)[0]) < 1e-9)
x_min = np.linalg.pinv(B) @ b # minimum-norm minimiser
x_alt = x_min + np.array([0.0, 1.0, -1.0]) # shift along the null space of B
print("min-norm solution:", x_min, " objective:", round(np.sum((B @ x_min - b) ** 2), 6))
print("shifted solution: ", x_alt, " objective:", round(np.sum((B @ x_alt - b) ** 2), 6))
# 4. Ridge makes it well defined again; and the normal equations square the condition number
lam = 0.1
x_ridge = np.linalg.solve(B.T @ B + lam * np.eye(3), B.T @ b)
print("ridge solution:", x_ridge)
C = np.vander(np.linspace(0, 1, 8), 6, increasing=True) # polynomial design matrix, nearly dependent columns
print("cond(C):", f"{np.linalg.cond(C):.3e}", " cond(C^T C):", f"{np.linalg.cond(C.T @ C):.3e}",
" cond(C)^2:", f"{np.linalg.cond(C) ** 2:.3e}")
Output:
analytic gradient: [ -75.0544 -262.3596]
finite differences: [ -75.0544 -262.3596]
match: True
match if the factor 2 is dropped: False
normal equations solution: [1.0429 2.0029]
largest |gradient| there below 1e-9: True
lstsq agrees: True
Hessian 2 A^T A eigenvalues (all > 0): [ 3.5457 118.4543]
rank of B: 2 columns: 3
smallest eigenvalue of B^T B is ~0: True
min-norm solution: [1.0429 1.0014 1.0014] objective: 0.134857
shifted solution: [1.0429 2.0014 0.0014] objective: 0.134857
ridge solution: [1.0046 1.0057 1.0057]
cond(C): 3.405e+03 cond(C^T C): 1.159e+07 cond(C)^2: 1.159e+07
Reading the output:
- The analytic and numeric gradients agree, and the version with the factor 2 dropped does not match, so the check can fail and the derivation passes it.
- The solution is intercept 1.0429 and slope 2.0029; the gradient there is zero to within 1e-9; the Hessian eigenvalues 3.5457 and 118.4543 are positive, so the minimum is unique.
- With a duplicated column, the rank is 2 for 3 columns and the smallest eigenvalue of B⊤B is about 0. The two printed solutions differ by the vector (0, 1, -1) in the null space, and both give objective 0.134857. Ridge with λ=0.1 picks one answer, splitting the weight evenly between the identical columns (1.0057 each).
Trade-offs and pitfalls
- Squared condition number. The condition number (largest singular value divided by smallest, a measure of how much input errors get amplified) is what matters here. For the polynomial design matrix, cond(C)=3.405e3 while cond(C⊤C)=1.159e7, which equals the square. Forming A⊤A loses roughly twice as many digits as working with A, so numerical libraries solve least squares through a QR factorization (A=QR with Q having orthonormal columns and R triangular) or an SVD of A rather than inverting A⊤A.
- Never write the inverse explicitly. Solve the linear system; the inverse is slower and less accurate.
- Large n. Forming A⊤A costs about mn2 and solving costs about n3; for huge problems use gradient-based or iterative methods (conjugate gradient, which improves the solution step by step using only products with A and A⊤, or SGD) that never form A⊤A.
- Near-dependent columns do not make the problem undefined, but make the solution unstable to noise: small changes in b move x⋆ a lot. Diagnose with the condition number or the singular values of A.
State the KKT conditions for a problem with inequality constraints and explain each one using a small worked example.
Sample Answer
The short answer
For a problem "minimise f(x) subject to g_i(x) <= 0", a point x* that is optimal (and where the problem is regular enough for the conditions to apply, made precise after the worked example) comes with one multiplier lam_i >= 0 per inequality constraint such that four things hold. These are the KKT conditions (Karush-Kuhn-Tucker). They generalise Lagrange multipliers from equality constraints to inequality constraints, and the new ingredient is a sign rule plus "a constraint either binds or its multiplier is zero".
Setup and the four conditions
Here f is the objective (a function of the vector x), each g_i is a constraint function, and a constraint is active at x if g_i(x) = 0 (the point sits on its boundary) and inactive if g_i(x) < 0. The Lagrangian adds each constraint to the objective, weighted by its multiplier lam_i (a non-negative number, the "price" of the constraint):
L(x,λ)=f(x)+i∑λigi(x)- Stationarity: the gradient of the Lagrangian with respect to x is zero, that is, the gradient of f plus the sum of lam_i times the gradient of g_i is the zero vector. Meaning: at the optimum the objective cannot be improved by a first-order move that keeps the active constraints satisfied; the pull of f is exactly balanced by the "walls" of the active constraints.
- Primal feasibility: g_i(x*) <= 0 for every i. The point must obey the constraints. ("Primal" names the original problem in the variable x; the "dual" problem is the companion problem written in terms of the multipliers, so "dual feasibility" below is the sign rule on the multipliers.)
- Dual feasibility: lam_i >= 0 for every i. A wall can only push back from the inside, never pull. If a multiplier came out negative, the objective would want to move further into the forbidden region, so the point is not a constrained minimum.
- Complementary slackness: lam_i * g_i(x*) = 0 for every i. Each constraint is either active (g_i = 0) or unused (lam_i = 0). An inactive constraint exerts no force, so removing it would not change the solution.
With equality constraints h_j(x) = 0 added, each gets a multiplier nu_j that may have either sign, and the condition h_j(x*) = 0 joins primal feasibility.
Worked example
Minimise f(x1, x2) = (x1 - 2)^2 + (x2 - 2)^2 (squared distance to the point (2, 2)) subject to g1 = x1 + x2 - 2 <= 0 and g2 = x1 - 3 <= 0.
In this example, picture the gradients at the candidate answer (1, 1): the gradient of f is (-2, -2), pointing away from the target (2, 2); the gradient of g1 is (1, 1), pointing out of the feasible region. Stationarity asks for (-2, -2) + lam1 * (1, 1) = 0, which holds with lam1 = 2 > 0: the wall pushes back toward the feasible side. The wrong-sign case is the point (3, 2) with only g2 active: the gradient of f there is (2, 0) and the gradient of g2 is (1, 0), so stationarity needs 2 + lam2 * 1 = 0, giving lam2 = -2. The wall would have to pull, so that point is not a constrained minimum.
import numpy as np
target = np.array([2.0, 2.0])
grad_f = lambda x: 2 * (x - target)
x = np.array([1.0, 1.0])
print("at (1, 1): grad f =", grad_f(x), " grad g1 = [1. 1.] grad f + 2 * grad g1 =", grad_f(x) + 2 * np.array([1.0, 1.0]))
x = np.array([3.0, 2.0])
print("at (3, 2): grad f =", grad_f(x), " grad g2 = [1. 0.] grad f + lam * grad g2 = 0 needs lam =", -grad_f(x)[0])
Output:
at (1, 1): grad f = [-2. -2.] grad g1 = [1. 1.] grad f + 2 * grad g1 = [0. 0.]
at (3, 2): grad f = [2. 0.] grad g2 = [1. 0.] grad f + lam * grad g2 = 0 needs lam = -2.0
Complementary slackness splits the search by which constraints are active, so there are four cases (neither, g1 only, g2 only, both). For each case the program treats the active constraints as equalities, solves stationarity for x and the multipliers, and then tests primal feasibility, dual feasibility and complementary slackness. It finishes by solving the original problem with a library solver (SLSQP, sequential least squares programming) as a cross-check.
For the g1-only case by hand: stationarity says 2(x1 - 2) + lam1 = 0 and 2(x2 - 2) + lam1 = 0, and g1 = 0 gives x1 + x2 = 2. So x1 = x2 = 1 and lam1 = 2. The constraint g2 = 1 - 3 = -2 is inactive, so lam2 = 0.
import itertools
import numpy as np
from scipy.optimize import minimize
# minimise f(x) = (x1-2)^2 + (x2-2)^2 subject to g1(x) = x1 + x2 - 2 <= 0 and g2(x) = x1 - 3 <= 0
target = np.array([2.0, 2.0])
grad_f = lambda x: 2 * (x - target)
G = np.array([[1.0, 1.0], [1.0, 0.0]]) # rows are the gradients of g1, g2 (both constraints are linear)
b = np.array([2.0, 3.0]) # g_i(x) = G[i] @ x - b[i]
def solve_with_active(active):
"""Treat the constraints in `active` as equalities, solve stationarity, return x and the multipliers."""
# stationarity: 2(x - target) + sum_i lam_i G[i] = 0 and G[i] x = b[i] for i in active
k = len(active)
A = np.zeros((2 + k, 2 + k)); rhs = np.zeros(2 + k)
A[:2, :2] = 2 * np.eye(2); rhs[:2] = 2 * target
for j, i in enumerate(active):
A[:2, 2 + j] = G[i] # 2x + sum_i lam_i G[i] = 2 * target
A[2 + j, :2] = G[i]; rhs[2 + j] = b[i]
sol = np.linalg.solve(A, rhs)
lam = np.zeros(2)
for j, i in enumerate(active):
lam[i] = sol[2 + j]
return sol[:2], lam
for active in [(), (0,), (1,), (0, 1)]:
x, lam = solve_with_active(active)
g = G @ x - b
stat = np.linalg.norm(grad_f(x) + G.T @ lam)
ok_primal = bool(np.all(g <= 1e-9))
ok_dual = bool(np.all(lam >= -1e-9))
ok_cs = bool(np.allclose(lam * g, 0, atol=1e-9))
print(f"active={active!s:7} x={np.round(x,3)} lam={np.round(lam,3)} g={np.round(g,3)} "
f"stationarity={stat:.1e} primal={ok_primal} dual={ok_dual} compl={ok_cs} KKT={ok_primal and ok_dual and ok_cs}")
res = minimize(lambda x: np.sum((x - target) ** 2), x0=[0.0, 0.0], method="SLSQP",
constraints=[{"type": "ineq", "fun": lambda x, i=i: -(G[i] @ x - b[i])} for i in range(2)])
print("SLSQP solution:", np.round(res.x, 4))
# the multiplier as a price: loosen g1 to x1 + x2 <= 2 + eps and watch the optimal value fall by about lam1 * eps
def best_value(eps):
r = minimize(lambda x: np.sum((x - target) ** 2), x0=[0.0, 0.0], method="SLSQP", options={"ftol": 1e-12},
constraints=[{"type": "ineq", "fun": lambda x: -(x[0] + x[1] - (2 + eps))},
{"type": "ineq", "fun": lambda x: -(x[0] - 3)}])
return r.fun
eps = 0.01
print(f"f*(0)={best_value(0):.4f} f*({eps})={best_value(eps):.4f} slope={(best_value(eps) - best_value(0)) / eps:.2f} (minus lam1 = -2)")
Output:
active=() x=[2. 2.] lam=[0. 0.] g=[ 2. -1.] stationarity=0.0e+00 primal=False dual=True compl=True KKT=False
active=(0,) x=[1. 1.] lam=[2. 0.] g=[ 0. -2.] stationarity=0.0e+00 primal=True dual=True compl=True KKT=True
active=(1,) x=[3. 2.] lam=[ 0. -2.] g=[3. 0.] stationarity=0.0e+00 primal=False dual=False compl=True KKT=False
active=(0, 1) x=[ 3. -1.] lam=[ 6. -8.] g=[0. 0.] stationarity=0.0e+00 primal=True dual=False compl=True KKT=False
SLSQP solution: [1. 1.]
f*(0)=2.0000 f*(0.01)=1.9801 slope=-1.99 (minus lam1 = -2)
Reading the output, row by row:
- Neither active: the unconstrained minimum (2, 2) breaks g1 (g1 = 2), so primal feasibility fails.
- g1 only: every condition holds. x = (1, 1), lam1 = 2 > 0, lam2 = 0 and g2 = -2. This is the KKT point, and SLSQP finds the same point.
- g2 only: the multiplier is -2, so dual feasibility fails, and g1 = 3 is violated too.
- Both active: lam2 = -8 fails the sign rule.
The last line shows what a multiplier means: loosening g1 to x1 + x2 <= 2 + eps lowers the best achievable objective at a rate of about lam1 = 2 per unit of eps (the run measured a slope of -1.99 for eps = 0.01; the small gap from 2 is the curvature of the second-order term). A multiplier is the sensitivity ("shadow price") of its constraint, and an inactive constraint has price zero.
When the conditions are necessary and when they are sufficient
In an interview, the sufficiency statement for convex problems is the main point to state; the constraint qualification is a technical assumption that is usually raised only as a follow-up, and the non-convex case (a KKT point is a candidate, not a guarantee) comes up when the interviewer asks whether every KKT point is optimal.
- Sufficient: if f and every g_i are convex (bowl-shaped: the straight line between any two points of the graph never dips below the graph) and the equality constraints are affine (of the form a . x + c, flat), any point satisfying KKT is a global minimum. Here f is convex and both constraints are linear, so (1, 1) is the global optimum.
- Necessary: a minimiser must satisfy KKT only if a constraint qualification holds, a regularity condition that rules out pathological constraint geometry. Two common ones are LICQ (linear independence constraint qualification: the gradients of the active constraints are linearly independent) and Slater's condition (for convex problems, some point satisfies every inequality strictly). Without one, KKT can fail at the true optimum. Example: minimise x subject to x^2 <= 0. The only feasible point is x = 0, but the gradient of the constraint there is 0, so stationarity would need 1 + lam * 0 = 0, which no lam satisfies.
- For non-convex problems, a KKT point is only a candidate: it can be a local minimum, a local maximum or a saddle, and second-order conditions (checks on the curvature of the Lagrangian along the directions that keep the active constraints satisfied) are needed to tell them apart. A saddle is a point that is a minimum in some directions and a maximum in others.
Common mistakes
- Getting the sign convention wrong. The statement "lam_i >= 0" belongs to the form g_i(x) <= 0 with a minimisation and f + sum lam_i g_i. Writing the constraint as g_i >= 0 flips either the sign of the term or the sign rule.
- Reading complementary slackness as "both are zero". It says at least one of lam_i and g_i is zero; both may be zero (a degenerate, weakly active constraint: it touches the optimum but exerts no force, for example when the unconstrained minimum happens to lie exactly on its boundary).
- Checking only stationarity and forgetting feasibility, or solving the stationarity equations and not testing the inactive cases.
- Claiming KKT is always necessary.
Unlock Full Question Bank
Get access to all 15 Linear Algebra and Numerical Computing interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.