Math for Causal Inference

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.

Video coming soon
Learning outcomes
  • ●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.
2-HOUR SESSION PLAN
Theory 25′Warm-up (1–5) 20′Proofs (6–10) 35′Applied (11–15) 25′Python & Lab 15′
Colab notebook (.ipynb) Jump to the simulator

Theory

Layout

For a scalar function f(x)f(x) of a vector x∈Rkx \in \mathbb{R}^k, the gradient is the column vector ∂f/∂x=(∂f/∂x1,…,∂f/∂xk)⊤\partial f/\partial x = (\partial f/\partial x_1, \dots, \partial f/\partial x_k)^{\top}, and the Hessian is the k×kk \times k matrix ∂2f/∂x ∂x⊤\partial^2 f/\partial x\,\partial x^{\top}. For a vector function g(x)∈Rmg(x) \in \mathbb{R}^m, the Jacobian ∂g/∂x⊤\partial g/\partial x^{\top} is m×km \times k.

Four rules cover almost everything

FunctionGradient
a⊤xa^{\top}xaa
x⊤Axx^{\top}Ax(A+A⊤)x(A + A^{\top})x, which is 2Ax2Ax if AA is symmetric
AxAx (vector)Jacobian AA
f(g(x))f(g(x))chain rule: ∂g∂x⊤ ⁣⊤∇f(g(x))\frac{\partial g}{\partial x^{\top}}^{\!\top}\nabla f(g(x))

The least-squares objective

S(β)=(y−Xβ)⊤(y−Xβ)=y⊤y−2β⊤X⊤y+β⊤X⊤Xβ,S(\beta) = (y - X\beta)^{\top}(y - X\beta) = y^{\top}y - 2\beta^{\top}X^{\top}y + \beta^{\top}X^{\top}X\beta, ∇S(β)=−2X⊤y+2X⊤Xβ=−2X⊤(y−Xβ),∇2S=2X⊤X.\nabla S(\beta) = -2X^{\top}y + 2X^{\top}X\beta = -2X^{\top}(y - X\beta), \qquad \nabla^2 S = 2X^{\top}X.

Setting the gradient to zero gives the normal equations X⊤Xβ^=X⊤yX^{\top}X\hat\beta = X^{\top}y. The Hessian is PSD (Day 17), so SS is convex and the solution is a minimum (Day 25).

The same template, other estimators

  • Ridge: S(β)+λβ⊤β⇒β^=(X⊤X+λI)−1X⊤yS(\beta) + \lambda\beta^{\top}\beta \Rightarrow \hat\beta = (X^{\top}X + \lambda I)^{-1}X^{\top}y.
  • Weighted least squares: (y−Xβ)⊤W(y−Xβ)⇒β^=(X⊤WX)−1X⊤Wy(y - X\beta)^{\top}W(y - X\beta) \Rightarrow \hat\beta = (X^{\top}WX)^{-1}X^{\top}Wy.
  • Logit: ∇ℓ=X⊤(y−p)\nabla\ell = X^{\top}(y - p) and ∇2ℓ=−X⊤VX\nabla^2\ell = -X^{\top}VX with V=diag⁡(pi(1−pi))V = \operatorname{diag}(p_i(1 - p_i)).

Causal link. Weighted least squares with weights 1/e^(x)1/\hat e(x) and 1/(1−e^(x))1/(1 - \hat e(x)) 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 f(x)=a⊤xf(x) = a^{\top}x with a=(2,−1,3)a = (2, -1, 3).

Show solution

∇f=a=(2,−1,3)⊤\nabla f = a = (2, -1, 3)^{\top}, the same at every xx.

Exercise 2 · A quadratic form

For A=(2113)A = \begin{pmatrix}2 & 1\\1 & 3\end{pmatrix} and f(x)=x⊤Axf(x) = x^{\top}Ax, find ∇f\nabla f at x=(1,1)x = (1, 1).

Show solution

Step 1. AA is symmetric, so ∇(x⊤Ax)=2Ax\nabla(x^{\top}Ax) = 2Ax.

Step 2. Ax=(2+1,  1+3)=(3,4)Ax = (2 + 1,\; 1 + 3) = (3, 4) at x=(1,1)x = (1, 1).

Answer: ∇f=(6,8)\nabla f = (6, 8).

Exercise 3 · Its Hessian

Find the Hessian of ff in Exercise 2.

Show solution

2A=(4226)2A = \begin{pmatrix}4 & 2\\2 & 6\end{pmatrix}, constant because ff is quadratic.

Exercise 4 · Component check

Find the gradient of f(x1,x2)=x12+x1x2+2x22f(x_1, x_2) = x_1^2 + x_1x_2 + 2x_2^2 at (1,2)(1, 2) directly and via the matrix rule.

Show solution

Directly: (2x1+x2,  x1+4x2)=(4,9)(2x_1 + x_2,\; x_1 + 4x_2) = (4, 9). Matrix: A=(10.50.52)A = \begin{pmatrix}1 & 0.5\\0.5 & 2\end{pmatrix}, 2Ax=2(1+1,0.5+4)=(4,9)2Ax = 2(1 + 1, 0.5 + 4) = (4, 9). ✓

Exercise 5 · A Jacobian

Find the Jacobian of g(x)=(x1x2,  x1+x22)⊤g(x) = (x_1x_2,\; x_1 + x_2^2)^{\top}.

Show solution

∂g∂x⊤=(x2x112x2)\frac{\partial g}{\partial x^{\top}} = \begin{pmatrix}x_2 & x_1\\1 & 2x_2\end{pmatrix}.

Part 2 · Proofs

Exercise 6 · The linear rule

Prove ∂(a⊤x)/∂x=a\partial(a^{\top}x)/\partial x = a.

Show solution

a⊤x=∑jajxja^{\top}x = \sum_j a_jx_j, so ∂/∂xℓ=aℓ\partial/\partial x_\ell = a_\ell. Stacking gives aa.

Exercise 7 · The quadratic rule

Prove ∂(x⊤Ax)/∂x=(A+A⊤)x\partial(x^{\top}Ax)/\partial x = (A + A^{\top})x.

Show solution

x⊤Ax=∑i∑jaijxixjx^{\top}Ax = \sum_i\sum_j a_{ij}x_ix_j. Differentiating with respect to xℓx_\ell picks up terms with i=ℓi = \ell and with j=ℓj = \ell: ∑jaℓjxj+∑iaiℓxi=(Ax)ℓ+(A⊤x)ℓ\sum_j a_{\ell j}x_j + \sum_i a_{i\ell}x_i = (Ax)_\ell + (A^{\top}x)_\ell.

Exercise 8 · The normal equations

Derive ∇S(β)\nabla S(\beta) and the normal equations.

Show solution

Step 1. Expand S(β)=y⊤y−2β⊤X⊤y+β⊤X⊤XβS(\beta) = y^{\top}y - 2\beta^{\top}X^{\top}y + \beta^{\top}X^{\top}X\beta (the two cross terms are equal scalars).

Step 2. By the rules, ∇S=−2X⊤y+2X⊤Xβ\nabla S = -2X^{\top}y + 2X^{\top}X\beta.

Step 3. Setting it to zero: X⊤Xβ^=X⊤yX^{\top}X\hat\beta = X^{\top}y, so β^=(X⊤X)−1X⊤y\hat\beta = (X^{\top}X)^{-1}X^{\top}y under full rank.

Exercise 9 · A unique minimum

Show that the Hessian of SS is PD when XX has full column rank, so the solution is the unique minimiser.

Show solution

Step 1. ∇2S=2X⊤X\nabla^2S = 2X^{\top}X and v⊤X⊤Xv=∥Xv∥2>0v^{\top}X^{\top}Xv = \|Xv\|^2 > 0 for v≠0v \ne 0 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 S(β)+λ∥β∥2S(\beta) + \lambda\|\beta\|^2 and show it exists even when XX is rank-deficient (for λ>0\lambda > 0).

Show solution

Step 1. Gradient: −2X⊤y+2X⊤Xβ+2λβ=0⇒(X⊤X+λI)β=X⊤y-2X^{\top}y + 2X^{\top}X\beta + 2\lambda\beta = 0 \Rightarrow (X^{\top}X + \lambda I)\beta = X^{\top}y.

Step 2. For v≠0v \ne 0, v⊤(X⊤X+λI)v=∥Xv∥2+λ∥v∥2>0v^{\top}(X^{\top}X + \lambda I)v = \|Xv\|^2 + \lambda\|v\|^2 > 0, so the matrix is PD and invertible whatever the rank of XX.

Part 3 · Applied

Exercise 11 · A gradient from the farm data

For the four farms of Day 17 (visits xx, yields yy), X⊤X=(4101030)X^{\top}X = \begin{pmatrix}4 & 10\\10 & 30\end{pmatrix} and X⊤y=(16,47)X^{\top}y = (16, 47). Compute ∇S\nabla S at β=(0,1)\beta = (0, 1) (no intercept, 1 t/ha per visit) and at β^=(0.5,1.4)\hat\beta = (0.5, 1.4).

Show solution

Step 1. ∇S(β)=−2(X⊤y−X⊤Xβ)\nabla S(\beta) = -2(X^{\top}y - X^{\top}X\beta).

Step 2. At (0,1)(0, 1): X⊤Xβ=(10,30)X^{\top}X\beta = (10, 30), so ∇S=−2((16,47)−(10,30))=−2(6,17)=(−12,−34)\nabla S = -2\big((16, 47) - (10, 30)\big) = -2(6, 17) = (-12, -34).

Step 3. Both entries are negative, so increasing either coefficient lowers the SSR.

Step 4. At β^\hat\beta: X⊤Xβ^=(4(0.5)+10(1.4),  10(0.5)+30(1.4))=(16,47)X^{\top}X\hat\beta = (4(0.5) + 10(1.4),\; 10(0.5) + 30(1.4)) = (16, 47), so ∇S=0\nabla S = 0.

Answer: (−12,−34)(-12, -34) 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 wi=1/e^(xi)w_i = 1/\hat e(x_i) for treated and 1/(1−e^(xi))1/(1 - \hat e(x_i)) for control units turn a regression of yy on (1,T)(1, T) into an IPW estimator.

Show solution

Step 1. Objective: (y−Xβ)⊤W(y−Xβ)(y - X\beta)^{\top}W(y - X\beta) with WW diagonal (one weight per unit).

Step 2. Gradient: −2X⊤W(y−Xβ)-2X^{\top}W(y - X\beta). Setting it to zero gives X⊤WXβ=X⊤WyX^{\top}WX\beta = X^{\top}Wy, so β^=(X⊤WX)−1X⊤Wy\hat\beta = (X^{\top}WX)^{-1}X^{\top}Wy.

Step 3. With X=(1,T)X = (\mathbf 1, T), 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 1/e^(xi)1/\hat e(x_i) for treated and 1/(1−e^(xi))1/(1 - \hat e(x_i)) for controls, that is the Hájek IPW estimator.

Answer: an IPW estimate of the ATE is a weighted regression of yy on a treatment dummy (Days 14 and 44).

Exercise 13 · The Hessian of a propensity-score logit

For a logit model of programme participation, ℓ(β)=∑i[yixi⊤β−ln⁡(1+exi⊤β)]\ell(\beta) = \sum_i[y_ix_i^{\top}\beta - \ln(1 + e^{x_i^{\top}\beta})] (yi=1y_i = 1 if household ii participates). Derive the gradient and Hessian and show that ℓ\ell is concave.

Show solution

Step 1. Derivative of the second term: ∂∂βln⁡(1+ex⊤β)=ex⊤β1+ex⊤βx=p x\dfrac{\partial}{\partial\beta}\ln(1 + e^{x^{\top}\beta}) = \dfrac{e^{x^{\top}\beta}}{1 + e^{x^{\top}\beta}}x = p\,x.

Step 2. Gradient: ∇ℓ=∑i(yi−pi)xi=X⊤(y−p)\nabla\ell = \sum_i(y_i - p_i)x_i = X^{\top}(y - p).

Step 3. Differentiate −pixi-p_ix_i again using ∂pi/∂β⊤=pi(1−pi)xi⊤\partial p_i/\partial\beta^{\top} = p_i(1 - p_i)x_i^{\top}: ∇2ℓ=−∑ipi(1−pi)xixi⊤=−X⊤VX\nabla^2\ell = -\sum_ip_i(1 - p_i)x_ix_i^{\top} = -X^{\top}VX with V=diag⁡(pi(1−pi))V = \operatorname{diag}(p_i(1 - p_i)).

Step 4. For any vv, v⊤X⊤VXv=∑ipi(1−pi)(xi⊤v)2≥0v^{\top}X^{\top}VXv = \sum_ip_i(1 - p_i)(x_i^{\top}v)^2 \ge 0, so the Hessian is negative semi-definite.

Answer: ℓ\ell 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, ℓ=−n2ln⁡(2πσ2)−S(β)2σ2\ell = -\frac n2\ln(2\pi\sigma^2) - \frac{S(\beta)}{2\sigma^2}, where SS is the sum of squared residuals. Find the MLE of σ2\sigma^2 and compare it with s2s^2.

Show solution

Step 1. Differentiate with respect to σ2\sigma^2 (treat it as one variable): ∂ℓ∂σ2=−n2σ2+S2σ4\dfrac{\partial\ell}{\partial\sigma^2} = -\dfrac{n}{2\sigma^2} + \dfrac{S}{2\sigma^4}.

Step 2. Set to zero and multiply by 2σ42\sigma^4: −nσ2+S=0-n\sigma^2 + S = 0.

Step 3. At β^\hat\beta: σ^2=S(β^)/n=e⊤e/n\hat\sigma^2 = S(\hat\beta)/n = e^{\top}e/n.

Answer: e⊤e/ne^{\top}e/n, which is biased downward; s2=e⊤e/(n−k)s^2 = e^{\top}e/(n - k) is unbiased (Day 27).

Exercise 15 · How much does one farm move the estimates?

β^=(X⊤X)−1X⊤y\hat\beta = (X^{\top}X)^{-1}X^{\top}y is linear in yy, so ∂β^/∂y⊤=(X⊤X)−1X⊤\partial\hat\beta/\partial y^{\top} = (X^{\top}X)^{-1}X^{\top}. 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. (X⊤X)−1=120(30−10−104)(X^{\top}X)^{-1} = \frac{1}{20}\begin{pmatrix}30 & -10\\-10 & 4\end{pmatrix} (determinant 4⋅30−102=204 \cdot 30 - 10^2 = 20).

Step 2. Farm 4's column of X⊤X^{\top} is (1,4)⊤(1, 4)^{\top}.

Step 3. 120(30−40−10+16)=120(−106)=(−0.50.3)\frac{1}{20}\begin{pmatrix}30 - 40\\-10 + 16\end{pmatrix} = \frac{1}{20}\begin{pmatrix}-10\\6\end{pmatrix} = \begin{pmatrix}-0.5\\0.3\end{pmatrix}.

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

  • ∂(a⊤x)/∂x=a\partial(a^{\top}x)/\partial x = a and ∂(x⊤Ax)/∂x=2Ax\partial(x^{\top}Ax)/\partial x = 2Ax (symmetric AA) do most of the work.
  • Setting the gradient of the SSR to zero gives the normal equations; its Hessian 2X⊤X2X^{\top}X 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.

-101230.511.5β₀ (intercept)β₁ (slope)
β (your point)
(2.50, 0.400)
S(β)
8.100
minimum 0.111
∇S = −2X′(y − Xβ)
(-7.20, -45.40)
OLS β̂
(1.080, 0.977)
∇S = 0 here
Hessian 2X′X
[12 42; 42 182]
eigenvalues 191.8, 2.19

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.

Day 23Day 25