Day 24. Matrix Calculus & Gradients
Differentiating with respect to a whole vector at once, and deriving the OLS, ridge, WLS and logit first-order conditions.
- ●Apply the core rules ∂(a′x)/∂x = a and ∂(x′Ax)/∂x = (A + A′)x.
- ●Derive the gradient and Hessian of the sum of squared residuals and obtain the normal equations.
- ●Derive the ridge and weighted-least-squares estimators.
- ●Compute the gradient and Hessian of the logit log-likelihood and the sensitivity of OLS to one observation.
Theory
Layout
For a scalar function of a vector , the gradient is the column vector , and the Hessian is the matrix . For a vector function , the Jacobian is .
Four rules cover almost everything
| Function | Gradient |
|---|---|
| , which is if is symmetric | |
| (vector) | Jacobian |
| chain rule: |
The least-squares objective
Setting the gradient to zero gives the normal equations . The Hessian is PSD (Day 17), so is convex and the solution is a minimum (Day 25).
The same template, other estimators
- Ridge: .
- Weighted least squares: .
- Logit: and with .
Causal link. Weighted least squares with weights and is how IPW regressions are run; ridge and lasso are the nuisance learners in double machine learning.
Part 1 · Warm-up
Exercise 1 · A linear function
Find the gradient of with .
Show solution
, the same at every .
Exercise 2 · A quadratic form
For and , find at .
Show solution
Step 1. is symmetric, so .
Step 2. at .
Answer: .
Exercise 3 · Its Hessian
Find the Hessian of in Exercise 2.
Show solution
, constant because is quadratic.
Exercise 4 · Component check
Find the gradient of at directly and via the matrix rule.
Show solution
Directly: . Matrix: , . ✓
Exercise 5 · A Jacobian
Find the Jacobian of .
Show solution
.
Part 2 · Proofs
Exercise 6 · The linear rule
Prove .
Show solution
, so . Stacking gives .
Exercise 7 · The quadratic rule
Prove .
Show solution
. Differentiating with respect to picks up terms with and with : .
Exercise 8 · The normal equations
Derive and the normal equations.
Show solution
Step 1. Expand (the two cross terms are equal scalars).
Step 2. By the rules, .
Step 3. Setting it to zero: , so under full rank.
Exercise 9 · A unique minimum
Show that the Hessian of is PD when has full column rank, so the solution is the unique minimiser.
Show solution
Step 1. and for under full rank (Day 18).
Step 2. A function with a PD Hessian everywhere is strictly convex, so its stationary point is the unique global minimum (Day 25).
Exercise 10 · Ridge regression
Derive the minimiser of and show it exists even when is rank-deficient (for ).
Show solution
Step 1. Gradient: .
Step 2. For , , so the matrix is PD and invertible whatever the rank of .
Part 3 · Applied
Exercise 11 · A gradient from the farm data
For the four farms of Day 17 (visits , yields ), and . Compute at (no intercept, 1 t/ha per visit) and at .
Show solution
Step 1. .
Step 2. At : , so .
Step 3. Both entries are negative, so increasing either coefficient lowers the SSR.
Step 4. At : , so .
Answer: at the guess, and zero at the OLS estimate, as the normal equations require.
Exercise 12 · Weighted least squares
Derive the WLS estimator, and explain how weights for treated and for control units turn a regression of on into an IPW estimator.
Show solution
Step 1. Objective: with diagonal (one weight per unit).
Step 2. Gradient: . Setting it to zero gives , so .
Step 3. With , the fitted values are the weighted group means, so the slope is (weighted mean of treated outcomes) − (weighted mean of control outcomes).
Step 4. With weights for treated and for controls, that is the Hájek IPW estimator.
Answer: an IPW estimate of the ATE is a weighted regression of on a treatment dummy (Days 14 and 44).
Exercise 13 · The Hessian of a propensity-score logit
For a logit model of programme participation, ( if household participates). Derive the gradient and Hessian and show that is concave.
Show solution
Step 1. Derivative of the second term: .
Step 2. Gradient: .
Step 3. Differentiate again using : with .
Step 4. For any , , so the Hessian is negative semi-definite.
Answer: is concave, so any stationary point is a global maximum and Newton's method is reliable (Day 25).
Exercise 14 · The MLE of the error variance in a wage regression
For a log-wage regression with normal errors, , where is the sum of squared residuals. Find the MLE of and compare it with .
Show solution
Step 1. Differentiate with respect to (treat it as one variable): .
Step 2. Set to zero and multiply by : .
Step 3. At : .
Answer: , which is biased downward; is unbiased (Day 27).
Exercise 15 · How much does one farm move the estimates?
is linear in , so . For the four farms, by how much do the intercept and the yield-per-visit slope change if farm 4's yield is recorded 1 t/ha higher?
Show solution
Step 1. (determinant ).
Step 2. Farm 4's column of is .
Step 3. .
Answer: the slope rises by 0.3 t/ha per visit and the intercept falls by 0.5: an end-point farm tilts the line. A data-entry error there matters a lot.
Verify in Python
import numpy as np
def num_grad(f, x, h=1e-6):
return np.array([(f(x + h * e) - f(x - h * e)) / (2 * h) for e in np.eye(len(x))])
A = np.array([[2, 1], [1, 3.]])
print("grad x'Ax at (1,1):", num_grad(lambda x: x @ A @ x, np.array([1, 1.])).round(4))
x = np.array([1, 2, 3, 4.]); y = np.array([2, 3, 5, 6.]); X = np.column_stack([np.ones(4), x])
S = lambda b: (y - X @ b) @ (y - X @ b)
for b in (np.array([0, 1.]), np.array([0.5, 1.4])):
print("grad S at", b, ":", num_grad(S, b).round(4), " formula:", (-2 * X.T @ (y - X @ b)).round(4))
print("dbeta/dy4:", (np.linalg.inv(X.T @ X) @ X.T)[:, 3])
lam = 0.5
print("ridge:", np.linalg.solve(X.T @ X + lam * np.eye(2), X.T @ y).round(4))
Key takeaways
- and (symmetric ) do most of the work.
- Setting the gradient of the SSR to zero gives the normal equations; its Hessian guarantees a minimum.
- Ridge, WLS and logit follow the same recipe: write the objective, differentiate, solve.
Simulation Lab: The Gradient of the Sum of Squares
Open full screen →Click anywhere on the SSR surface to see −∇S = 2X′(y − Xβ) point downhill toward the OLS estimate.
Contours of the sum of squared residuals S(β₀, β₁) for six data points. Click or drag anywhere: the orange arrow is −∇S = 2X′(y − Xβ), the direction of steepest descent (drawn at a fixed length). It points across the contours toward lower S and vanishes only at the OLS estimate.