Skip to content

47. Calculus and optimization for ML — Exercises

These 25 exercises practice every idea in 47. Calculus and optimization for ML. They reuse the course datasets data/houses.csv, data/customers.csv, data/ab_test.csv, and data/reviews.csv (see the data dictionary).

How to work:

  1. Copy the setup block and the starter code into a script, for example exercise.py.
  2. Replace each to-do comment with your implementation, then run python exercise.py from the folder that contains data/.
  3. Check your output against the expected output (or acceptance criteria). Open one hint at a time when stuck, and open the solution only after a genuine attempt.

Every exercise starts with these imports and formatting settings. The verifier runs this block before each exercise section.

import numpy as np
import pandas as pd
from scipy import integrate, optimize, stats
np.set_printoptions(precision=4, suppress=True)

M47-W01 · Product and quotient rule check

Section titled “M47-W01 · Product and quotient rule check”
Warm-up

Compute the analytic derivatives of f(x)=x2e−xf(x) = x^2 e^{-x} (product rule) and g(x)=x1+x2g(x) = \frac{x}{1 + x^2} (quotient rule) at x=1.5x = 1.5. Compare each against a central-difference estimate with h=10−6h = 10^{-6}, printing both values and the absolute error.

Expected output
f'(1.5): ana=+0.167348, num=+0.167348, err=1.7e-11
g'(1.5): ana=-0.118343, num=-0.118343, err=4.9e-12
Starter
def central_diff(fn, x: float, h: float = 1e-6) -> float:
return float((fn(x + h) - fn(x - h)) / (2 * h))
x0 = 1.5
# TODO: define f(x) = x**2 * exp(-x), g(x) = x / (1 + x**2) and their analytic derivatives
# TODO: print analytic, numerical, and absolute error for both
Hint 1

For f(x)=x2e−xf(x) = x^2 e^{-x}, apply (uv)′=u′v+uv′(uv)' = u'v + uv' with u=x2u = x^2 and v=e−xv = e^{-x} to get (2x−x2)e−x(2x - x^2) e^{-x}.

Hint 2

For g(x)=x1+x2g(x) = \frac{x}{1 + x^2}, apply (uv)′=u′v−uv′v2\left(\frac{u}{v}\right)' = \frac{u'v - uv'}{v^2} to get (1+x2)−x(2x)(1+x2)2=1−x2(1+x2)2\frac{(1 + x^2) - x(2x)}{(1 + x^2)^2} = \frac{1 - x^2}{(1 + x^2)^2}.

Solution
def central_diff(fn, x: float, h: float = 1e-6) -> float:
return float((fn(x + h) - fn(x - h)) / (2 * h))
x0 = 1.5
def f(x: float) -> float:
return float(x**2 * np.exp(-x))
def df(x: float) -> float:
return float((2 * x - x**2) * np.exp(-x))
def g(x: float) -> float:
return float(x / (1 + x**2))
def dg(x: float) -> float:
return float((1 - x**2) / (1 + x**2) ** 2)
for name, fn, dfn in [("f", f, df), ("g", g, dg)]:
ana = float(dfn(x0))
num = central_diff(fn, x0)
err = abs(ana - num)
print(f"{name}'({x0}): ana={ana:+.6f}, num={num:+.6f}, err={err:.1e}")
assert err < 1e-9
Output
f'(1.5): ana=+0.167348, num=+0.167348, err=1.7e-11
g'(1.5): ana=-0.118343, num=-0.118343, err=4.9e-12

How it works:

  1. The product rule splits (x2e−x)′(x^2 e^{-x})' into 2xe−x+x2(−e−x)=(2x−x2)e−x2x e^{-x} + x^2(-e^{-x}) = (2x - x^2)e^{-x}.
  2. The quotient rule differentiates x/(1+x2)x / (1 + x^2) into (1−x2)/(1+x2)2(1 - x^2)/(1 + x^2)^2, which is negative at x=1.5x = 1.5 because gg peaks at x=1x = 1.
  3. Central differences match both formulas to 10−1110^{-11}.

Alternative: Rewrite g(x)=x(1+x2)−1g(x) = x (1 + x^2)^{-1} and differentiate it using the product and chain rules instead of memorizing the quotient rule.

M47-W02 · Predict the output: ReLU and Huber derivatives

Section titled “M47-W02 · Predict the output: ReLU and Huber derivatives”
Warm-up

Predict the output: read the code below and write down the exact printed arrays for the ReLU subgradient and the Huber derivative (with δ=1.0\delta = 1.0) at r = [-2.0, -0.5, 0.0, 0.5, 2.0], then run the script to verify.

Starter
r = np.array([-2.0, -0.5, 0.0, 0.5, 2.0])
relu_subgrad = np.where(r > 0.0, 1.0, 0.0)
huber_grad = np.where(np.abs(r) <= 1.0, r, np.sign(r))
print("relu :", relu_subgrad)
print("huber:", huber_grad)

Acceptance criteria:

  • Write down both arrays before running the code.
  • Explain why both values at r = 0.0 are 0.0, and why huber caps at ±1.0 for ±2.0.
Hint 1

For r <= 0, r > 0.0 is False, so relu_subgrad selects 0.0 (a valid subgradient at the kink 00).

Hint 2

Inside ∣r∣≤1\lvert r \rvert \le 1, Huber is 12r2\frac{1}{2} r^2 (derivative rr); outside, its slope is fixed at ±1\pm 1.

Solution
r = np.array([-2.0, -0.5, 0.0, 0.5, 2.0])
relu_subgrad = np.where(r > 0.0, 1.0, 0.0)
huber_grad = np.where(np.abs(r) <= 1.0, r, np.sign(r))
print("relu :", relu_subgrad)
print("huber:", huber_grad)
assert np.allclose(relu_subgrad, [0.0, 0.0, 0.0, 1.0, 1.0])
assert np.allclose(huber_grad, [-1.0, -0.5, 0.0, 0.5, 1.0])
Output
relu : [0. 0. 0. 1. 1.]
huber: [-1. -0.5 0. 0.5 1. ]

How it works:

  1. ReLU is flat for negative inputs and has slope 11 for positive inputs; picking 00 at r=0r = 0 is the standard subgradient convention used by PyTorch.
  2. Huber behaves like MSE inside [−1,1][-1, 1] (slope equals rr) and clips to ±1\pm 1 outside so large residuals cannot dominate the gradient.

Alternative: Write huber_grad in one call as np.clip(r, -delta, delta), which equals r inside [−δ,δ][-\delta, \delta] and ±δ\pm \delta outside.

M47-W03 · Taylor polynomials of log(1 + x)

Section titled “M47-W03 · Taylor polynomials of log(1 + x)”
Warm-up

Evaluate the 1st-, 2nd-, and 3rd-order Taylor polynomials of log⁡(1+x)\log(1 + x) around a=0a = 0 at x=0.25x = 0.25. Print each approximation and its absolute error relative to np.log1p(0.25).

Expected output
exact = 0.223144
T1 = 0.250000 |err| = 0.026856
T2 = 0.218750 |err| = 0.004394
T3 = 0.223958 |err| = 0.000815
Starter
x = 0.25
exact = float(np.log1p(x))
# TODO: compute t1, t2, t3 around a = 0 and print value and absolute error for each
Hint 1

Around 00, log⁡(1+x)=x−x22+x33−x44+…\log(1 + x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \dots

Hint 2

Notice the denominator is kk, not k!k!, because the kk-th derivative of log⁡(1+x)\log(1 + x) at 00 is (−1)k−1(k−1)!(-1)^{k-1}(k - 1)!, which cancels (k−1)!(k - 1)! from k!k!.

Solution
x = 0.25
exact = float(np.log1p(x))
t1 = x
t2 = x - x**2 / 2
t3 = x - x**2 / 2 + x**3 / 3
print(f"exact = {exact:.6f}")
for order, val in [(1, t1), (2, t2), (3, t3)]:
print(f"T{order} = {val:.6f} |err| = {abs(exact - val):.6f}")
assert abs(exact - t3) < abs(exact - t2) < abs(exact - t1)
assert abs(exact - t3) < 1e-3
Output
exact = 0.223144
T1 = 0.250000 |err| = 0.026856
T2 = 0.218750 |err| = 0.004394
T3 = 0.223958 |err| = 0.000815

How it works:

  1. Each added term matches one higher derivative of log⁡(1+x)\log(1 + x) at 00.
  2. Because x=0.25x = 0.25 is well inside the convergence radius ∣x∣<1\lvert x \rvert < 1, each order cuts the error roughly by a factor of 44.

Alternative: Compute the kk-th partial sum with a list comprehension sum(((-1) ** (i - 1)) * (x**i) / i for i in range(1, k + 1)).

M47-W04 · Directional derivative and steepest ascent

Section titled “M47-W04 · Directional derivative and steepest ascent”
Warm-up

For f(w1,w2)=2w12+w1w2+3w22f(w_1, w_2) = 2 w_1^2 + w_1 w_2 + 3 w_2^2 at w=(1.0,−1.0)\mathbf{w} = (1.0, -1.0), compute the gradient ∇f(w)\nabla f(\mathbf{w}), the directional derivative along the unit vector u=(0.6,0.8)\mathbf{u} = (0.6, 0.8), and the maximum directional derivative (along the normalized gradient). Verify the directional derivative along u\mathbf{u} numerically.

Expected output
grad : [ 3. -5.]
D_u f : ana=-2.2000, num=-2.2000
max rate: 5.8310
Starter
def f(w: np.ndarray) -> float:
return float(2 * w[0] ** 2 + w[0] * w[1] + 3 * w[1] ** 2)
w0 = np.array([1.0, -1.0])
u = np.array([0.6, 0.8])
# TODO: compute analytic gradient, directional derivative along u, numerical check, and max rate
Hint 1

The partial derivatives are ∂f∂w1=4w1+w2\frac{\partial f}{\partial w_1} = 4 w_1 + w_2 and ∂f∂w2=w1+6w2\frac{\partial f}{\partial w_2} = w_1 + 6 w_2.

Hint 2

Check Duf(w)=∇f(w)⋅uD_{\mathbf{u}} f(\mathbf{w}) = \nabla f(\mathbf{w}) \cdot \mathbf{u} against (f(w0 + h * u) - f(w0 - h * u)) / (2 * h). The maximum directional derivative over all unit vectors is ∥∇f(w)∥2\lVert \nabla f(\mathbf{w}) \rVert_2.

Solution
def f(w: np.ndarray) -> float:
return float(2 * w[0] ** 2 + w[0] * w[1] + 3 * w[1] ** 2)
w0 = np.array([1.0, -1.0])
u = np.array([0.6, 0.8])
grad = np.array([4 * w0[0] + w0[1], w0[0] + 6 * w0[1]])
du_ana = float(grad @ u)
h = 1e-6
du_num = (f(w0 + h * u) - f(w0 - h * u)) / (2 * h)
max_rate = float(np.linalg.norm(grad))
print("grad :", grad)
print(f"D_u f : ana={du_ana:.4f}, num={du_num:.4f}")
print(f"max rate: {max_rate:.4f}")
assert np.isclose(du_ana, du_num, atol=1e-8)
assert abs(du_ana) <= max_rate
Output
grad : [ 3. -5.]
D_u f : ana=-2.2000, num=-2.2000
max rate: 5.8310

How it works:

  1. At (1,−1)(1, -1), the gradient is [3,−5][3, -5], so moving along [0.6,0.8][0.6, 0.8] changes ff at rate 3(0.6)+(−5)(0.8)=−2.23(0.6) + (-5)(0.8) = -2.2 (downhill!).
  2. The steepest ascent rate is ∥[3,−5]∥2=34≈5.8310\lVert [3, -5] \rVert_2 = \sqrt{34} \approx 5.8310, achieved along ∇f/∥∇f∥2\nabla f / \lVert \nabla f \rVert_2.

Alternative: Write f(w)=w⊤Awf(\mathbf{w}) = \mathbf{w}^\top A \mathbf{w} with A=(20.50.53)A = \begin{pmatrix} 2 & 0.5 \\ 0.5 & 3 \end{pmatrix} so ∇f(w)=2Aw\nabla f(\mathbf{w}) = 2 A \mathbf{w}.

M47-W05 · Classify stationary points by Hessian eigenvalues

Section titled “M47-W05 · Classify stationary points by Hessian eigenvalues”
Warm-up

Write a function classify_hessian(H) that returns "local_min", "local_max", "saddle", or "degenerate" based on the eigenvalues of a symmetric matrix H (treating eigenvalues with ∣λ∣≤10−10\lvert \lambda \rvert \le 10^{-10} as zero). Test it on the four matrices in the starter block.

Expected output
H1: eigs=[2.382 4.618] -> local_min
H2: eigs=[-3.2071 -1.7929] -> local_max
H3: eigs=[-1. 3.] -> saddle
H4: eigs=[0. 4.] -> degenerate
Starter
matrices = {
"H1": np.array([[4.0, 1.0], [1.0, 3.0]]),
"H2": np.array([[-3.0, 0.5], [0.5, -2.0]]),
"H3": np.array([[1.0, 2.0], [2.0, 1.0]]),
"H4": np.array([[2.0, 2.0], [2.0, 2.0]]),
}
# TODO: implement classify_hessian(H) and print name, eigenvalues, and classification
Hint 1

Use np.linalg.eigvalsh(H) for symmetric matrices — it is faster and returns real eigenvalues sorted in ascending order.

Hint 2

Check np.all(eigs > tol) for "local_min", np.all(eigs < -tol) for "local_max", np.any(eigs > tol) and np.any(eigs < -tol) for "saddle", otherwise "degenerate".

Solution
matrices = {
"H1": np.array([[4.0, 1.0], [1.0, 3.0]]),
"H2": np.array([[-3.0, 0.5], [0.5, -2.0]]),
"H3": np.array([[1.0, 2.0], [2.0, 1.0]]),
"H4": np.array([[2.0, 2.0], [2.0, 2.0]]),
}
def classify_hessian(H: np.ndarray, tol: float = 1e-10) -> str:
eigs = np.linalg.eigvalsh(H)
if np.all(eigs > tol):
return "local_min"
if np.all(eigs < -tol):
return "local_max"
if np.any(eigs > tol) and np.any(eigs < -tol):
return "saddle"
return "degenerate"
labels = {}
for name, H in matrices.items():
eigs = np.linalg.eigvalsh(H)
kind = classify_hessian(H)
labels[name] = kind
print(f"{name}: eigs={eigs} -> {kind}")
assert labels == {
"H1": "local_min",
"H2": "local_max",
"H3": "saddle",
"H4": "degenerate",
}
Output
H1: eigs=[2.382 4.618] -> local_min
H2: eigs=[-3.2071 -1.7929] -> local_max
H3: eigs=[-1. 3.] -> saddle
H4: eigs=[0. 4.] -> degenerate

How it works:

  1. H3 has positive diagonal entries (1.0, 1.0), yet its eigenvalues are -1.0 and 3.0 because the off-diagonal cross-term 2.0 bends one direction downward — diagonal entries alone cannot tell a minimum from a saddle!
  2. H4 has rank 1, so one eigenvalue is 0.0 (flat direction) and the second-derivative test is inconclusive.

Alternative: For 2×22 \times 2 matrices only, you can inspect the determinant and trace, but eigvalsh generalizes cleanly to any dimension pp.

M47-W06 · Integrate a normal density with scipy.integrate.quad

Section titled “M47-W06 · Integrate a normal density with scipy.integrate.quad”
Warm-up

Use scipy.integrate.quad on stats.norm.pdf to compute P(−1≤Z≤1)P(-1 \le Z \le 1) and P(−1.96≤Z≤1.96)P(-1.96 \le Z \le 1.96) for a standard normal variable ZZ. Verify each integral against stats.norm.cdf(b) - stats.norm.cdf(a).

Expected output
[-1.00, +1.00]: quad=0.682689, cdf=0.682689
[-1.96, +1.96]: quad=0.950004, cdf=0.950004
Starter
intervals = [(-1.0, 1.0), (-1.96, 1.96)]
# TODO: integrate stats.norm.pdf over each interval and compare with CDF difference
Hint 1

area, err = integrate.quad(stats.norm.pdf, a, b) returns both the integral and an error bound.

Hint 2

Compare area to stats.norm.cdf(b) - stats.norm.cdf(a) using np.isclose(..., atol=1e-12).

Solution
intervals = [(-1.0, 1.0), (-1.96, 1.96)]
for a, b in intervals:
area, _ = integrate.quad(stats.norm.pdf, a, b)
cdf_diff = float(stats.norm.cdf(b) - stats.norm.cdf(a))
print(f"[{a:+.2f}, {b:+.2f}]: quad={area:.6f}, cdf={cdf_diff:.6f}")
assert np.isclose(area, cdf_diff, atol=1e-12)
Output
[-1.00, +1.00]: quad=0.682689, cdf=0.682689
[-1.96, +1.96]: quad=0.950004, cdf=0.950004

How it works:

  1. By the Fundamental Theorem of Calculus, integrating the PDF over [a,b][a, b] recovers the exact CDF increment F(b)−F(a)F(b) - F(a).
  2. This reproduces the familiar 68% (±1σ\pm 1\sigma) and 95% (±1.96σ\pm 1.96\sigma) normal rules directly from area under the density curve.

Alternative: Compute the area on a fine grid with np.trapezoid (much less accurate than adaptive quadrature, though useful when you only have tabulated samples).

M47-W07 · Fix the bug: unstable softmax overflow

Section titled “M47-W07 · Fix the bug: unstable softmax overflow”
Warm-up

Fix the bug: the naive_softmax function below overflows to nan on large logits [1000.0, 1001.0, 999.0]. Rewrite it as stable_softmax so that it works for both 1D and 2D arrays (row-wise) without any overflow warnings, and print the probabilities for [1000.0, 1001.0, 999.0].

Expected output
probs: [0.2447 0.6652 0.09 ]
sum : 1.0
Starter
def naive_softmax(z: np.ndarray) -> np.ndarray:
exps = np.exp(z)
return exps / np.sum(exps, axis=-1, keepdims=True)
logits = np.array([1000.0, 1001.0, 999.0])
# TODO: fix the function as stable_softmax(z) and print stable_softmax(logits)
Hint 1

Adding or subtracting any constant cc from all logits leaves softmax unchanged: ezi−c∑kezk−c=e−cezie−c∑kezk=ezi∑kezk\frac{e^{z_i - c}}{\sum_k e^{z_k - c}} = \frac{e^{-c} e^{z_i}}{e^{-c} \sum_k e^{z_k}} = \frac{e^{z_i}}{\sum_k e^{z_k}}.

Hint 2

Set shifted = z - np.max(z, axis=-1, keepdims=True) before calling np.exp(shifted).

Solution
def stable_softmax(z: np.ndarray) -> np.ndarray:
shifted = z - np.max(z, axis=-1, keepdims=True)
exps = np.exp(shifted)
return exps / np.sum(exps, axis=-1, keepdims=True)
logits = np.array([1000.0, 1001.0, 999.0])
probs = stable_softmax(logits)
print("probs:", probs)
print("sum :", round(float(probs.sum()), 6))
assert np.all(np.isfinite(probs))
assert np.allclose(probs, stable_softmax(logits - 1000.0))
assert np.isclose(probs.sum(), 1.0)
Output
probs: [0.2447 0.6652 0.09 ]
sum : 1.0

How it works:

  1. Subtracting the maximum logit shifts the largest exponent to 0.0, so every exp term lies in (0,1](0, 1] and can never overflow float64.
  2. Using axis=-1, keepdims=True makes the same function work seamlessly on both 1D vectors (K,) and 2D batches (n, K).

Alternative: Use scipy.special.softmax(z, axis=-1), which applies the same max-shift internally.

M47-W08 · Test convexity with Jensen’s inequality

Section titled “M47-W08 · Test convexity with Jensen’s inequality”
Warm-up

Write a helper check_convex_grid(fn, low, high) that draws 200 random pairs (u,v)(u, v) and weights t∈[0,1]t \in [0, 1] using np.random.default_rng(42) and checks whether f(tu+(1−t)v)≤tf(u)+(1−t)f(v)+10−12f(tu + (1-t)v) \le t f(u) + (1-t) f(v) + 10^{-12} holds for every pair. Test it on x2x^2, −log⁡(x)-\log(x), and sin⁡(x)\sin(x) on [0.5,4.0][0.5, 4.0].

Expected output
x**2 : passes Jensen check -> True
-log(x) : passes Jensen check -> True
sin(x) : passes Jensen check -> False
Starter
funcs = [
("x**2", lambda x: x**2),
("-log(x)", lambda x: -np.log(x)),
("sin(x)", np.sin),
]
# TODO: test Jensen's inequality on [0.5, 4.0] with 200 random pairs per function
Hint 1

Generate u = rng.uniform(low, high, 200), v = rng.uniform(low, high, 200), and t = rng.uniform(0.0, 1.0, 200) inside the function (or pass rng).

Hint 2

Count violations with np.sum(fn(t * u + (1 - t) * v) > t * fn(u) + (1 - t) * fn(v) + 1e-12).

Solution
def check_convex_grid(fn, low: float, high: float, n: int = 200) -> bool:
rng = np.random.default_rng(42)
u = rng.uniform(low, high, n)
v = rng.uniform(low, high, n)
t = rng.uniform(0.0, 1.0, n)
lhs = fn(t * u + (1.0 - t) * v)
rhs = t * fn(u) + (1.0 - t) * fn(v)
return bool(np.all(lhs <= rhs + 1e-12))
funcs = [
("x**2", lambda x: x**2),
("-log(x)", lambda x: -np.log(x)),
("sin(x)", np.sin),
]
results = {}
for name, fn in funcs:
ok = check_convex_grid(fn, 0.5, 4.0)
results[name] = ok
print(f"{name:8}: passes Jensen check -> {ok}")
assert results == {"x**2": True, "-log(x)": True, "sin(x)": False}
Output
x**2 : passes Jensen check -> True
-log(x) : passes Jensen check -> True
sin(x) : passes Jensen check -> False

How it works:

  1. (x2)′′=2>0(x^2)'' = 2 > 0 and (−log⁡x)′′=1/x2>0(-\log x)'' = 1/x^2 > 0 on [0.5,4.0][0.5, 4.0], so both are strictly convex and pass every chord check.
  2. (sin⁡x)′′=−sin⁡x(\sin x)'' = -\sin x flips sign across [0.5,4.0][0.5, 4.0], so chords dip below the curve and fail Jensen’s inequality.

Alternative: For twice-differentiable 1D functions, evaluating f′′(x)≥0f''(x) \ge 0 on a grid is an equivalent local test.

Core

Implement softmax_jacobian(z) returning the K×KK \times K matrix J=diag⁡(p)−pp⊤J = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top for logits z = np.array([2.0, 0.5, -1.0, 0.0]). Verify that it matches central finite differences to 1e-9 and that every row and column sums to 0.

Expected output
[[ 0.2059 -0.1125 -0.0251 -0.0682]
[-0.1125 0.1333 -0.0056 -0.0152]
[-0.0251 -0.0056 0.0341 -0.0034]
[-0.0682 -0.0152 -0.0034 0.0869]]
max abs err = 6.3e-11, max |row sum| = 9.7e-17
Starter
z = np.array([2.0, 0.5, -1.0, 0.0])
# TODO: implement softmax, softmax_jacobian, and numerical Jacobian check
# TODO: print J rounded to 4 decimals, max abs error, and max abs row sum
Hint 1

np.diag(p) - np.outer(p, p) constructs the exact K×KK \times K Jacobian in one line.

Hint 2

Column jj of the numerical Jacobian is (softmax(z + h * e_j) - softmax(z - h * e_j)) / (2 * h).

Solution
def softmax(z: np.ndarray) -> np.ndarray:
s = z - np.max(z)
e = np.exp(s)
return e / e.sum()
def softmax_jacobian(z: np.ndarray) -> np.ndarray:
p = softmax(z)
return np.diag(p) - np.outer(p, p)
z = np.array([2.0, 0.5, -1.0, 0.0])
J = softmax_jacobian(z)
h = 1e-6
J_num = np.column_stack([
(softmax(z + h * e) - softmax(z - h * e)) / (2 * h) for e in np.eye(len(z))
])
max_err = float(np.max(np.abs(J - J_num)))
max_row_sum = float(np.max(np.abs(J.sum(axis=1))))
print(J)
print(f"max abs err = {max_err:.1e}, max |row sum| = {max_row_sum:.1e}")
assert max_err < 1e-9
assert max_row_sum < 1e-15
assert np.allclose(J, J.T)
Output
[[ 0.2059 -0.1125 -0.0251 -0.0682]
[-0.1125 0.1333 -0.0056 -0.0152]
[-0.0251 -0.0056 0.0341 -0.0034]
[-0.0682 -0.0152 -0.0034 0.0869]]
max abs err = 6.3e-11, max |row sum| = 9.7e-17

How it works:

  1. Because ∑ipi=1\sum_i p_i = 1 identically, any perturbation to zjz_j shifts probability mass among classes with zero net change, so ∑i∂pi/∂zj=0\sum_i \partial p_i / \partial z_j = 0 (columns sum to 0).
  2. Because JJ is symmetric (diag⁡(p)−pp⊤\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top), rows also sum to 0 — adding a constant to all logits leaves p\mathbf{p} unchanged.

Alternative: Compute p[:, None] * (np.eye(len(p)) - p[None, :]) using broadcasting instead of np.diag and np.outer.

M47-C02 · Condition number of the OLS Hessian on houses.csv

Section titled “M47-C02 · Condition number of the OLS Hessian on houses.csv”
Core

Load data/houses.csv and select ["sqft", "bedrooms", "bathrooms", "distance_to_center_km"]. Compute the OLS MSE Hessian H=2nA⊤AH = \frac{2}{n} A^\top A (where AA has a leading intercept column of ones) both on the raw features and on standardized features. Print the smallest eigenvalue, largest eigenvalue, and condition number κ(H)\kappa(H) for both, and compute the ratio of raw to standardized condition number.

Expected output
raw: min_eig=0.1370, max_eig=7,907,777.24, cond=57,701,821.4
std: min_eig=0.2071, max_eig=5.49, cond=26.5
condition number reduction: 2,178,232x
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "distance_to_center_km"]
# TODO: compute H_raw and H_std, their min/max eigenvalues, and condition numbers
Hint 1

A = np.column_stack([np.ones(len(X)), X]) and H = 2.0 * (A.T @ A) / len(X).

Hint 2

Use eigs = np.linalg.eigvalsh(H) and cond = eigs[-1] / eigs[0].

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
conds = {}
for name, M in [("raw", X), ("std", Z)]:
A = np.column_stack([np.ones(len(M)), M])
H = 2.0 * (A.T @ A) / len(M)
eigs = np.linalg.eigvalsh(H)
cond = float(eigs[-1] / eigs[0])
conds[name] = cond
print(f"{name:3}: min_eig={eigs[0]:.4f}, max_eig={eigs[-1]:,.2f}, cond={cond:,.1f}")
print(f"condition number reduction: {conds['raw'] / conds['std']:,.0f}x")
assert conds["raw"] > 1e6
assert conds["std"] < 100
Output
raw: min_eig=0.1370, max_eig=7,907,777.24, cond=57,701,821.4
std: min_eig=0.2071, max_eig=5.49, cond=26.5
condition number reduction: 2,178,232x

How it works:

  1. Because sqft is measured in thousands while bedrooms is around 3, the raw Hessian stretches curvature by more than 10 million times along one axis compared to another.
  2. Standardizing drops κ(H)\kappa(H) to 26.5 (remaining stretch comes only from the genuine correlation among sqft, bedrooms, and bathrooms), cutting the condition number by more than two million times.

Alternative: np.linalg.cond(H) computes the same ratio via singular values (equal to λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min} for symmetric positive definite matrices).

M47-C03 · Saddle point stagnation vs. escape

Section titled “M47-C03 · Saddle point stagnation vs. escape”
Core

Consider the saddle surface f(x,y)=x2−y2f(x, y) = x^2 - y^2, which has a saddle point at (0,0)(0, 0). Run 30 steps of gradient descent (η=0.1\eta = 0.1) from two starting points: p1 = [1.0, 0.0] (exact symmetry) and p2 = [1.0, 1e-3] (tiny perturbation). Print the final (x,y)(x, y) and f(x,y)f(x, y) for both runs.

Expected output
from (1, 0): end=[0.0012 0. ], f=+0.000002
from (1, 1e-3): end=[0.0012 0.2374], f=-0.056346
Starter
def f(p: np.ndarray) -> float:
return float(p[0] ** 2 - p[1] ** 2)
def grad_f(p: np.ndarray) -> np.ndarray:
return np.array([2.0 * p[0], -2.0 * p[1]])
# TODO: run 30 steps of GD (lr=0.1) from [1.0, 0.0] and [1.0, 1e-3] and print results
Hint 1

At y = 0, the second gradient entry -2 * y is identically zero, so GD slides straight into the saddle (0, 0) and stays trapped there forever.

Hint 2

With y = 1e-3, each step multiplies y by 1 + 2 * 0.1 = 1.2, escaping the saddle exponentially (1.2**30 ≈ 237).

Solution
def f(p: np.ndarray) -> float:
return float(p[0] ** 2 - p[1] ** 2)
def grad_f(p: np.ndarray) -> np.ndarray:
return np.array([2.0 * p[0], -2.0 * p[1]])
def run_gd(start: list[float], lr: float = 0.1, steps: int = 30) -> np.ndarray:
p = np.array(start, dtype=float)
for _ in range(steps):
p = p - lr * grad_f(p)
return p
p1 = run_gd([1.0, 0.0])
p2 = run_gd([1.0, 1e-3])
print(f"from (1, 0): end={p1}, f={f(p1):+.6f}")
print(f"from (1, 1e-3): end={p2}, f={f(p2):+.6f}")
assert abs(p1[1]) == 0.0 and f(p1) > 0
assert f(p2) < -0.05
Output
from (1, 0): end=[0.0012 0. ], f=+0.000002
from (1, 1e-3): end=[0.0012 0.2374], f=-0.056346

How it works:

  1. Starting exactly on the stable manifold (y=0y = 0) makes GD converge to the saddle point (0,0)(0, 0) even though downward directions exist.
  2. Any tiny nonzero perturbation (such as random initialization or mini-batch SGD noise in neural networks) grows exponentially along the negative-curvature eigenvector and escapes the saddle.

Alternative: Verify analytically that after kk steps, xk=(1−2η)kx0x_k = (1 - 2\eta)^k x_0 and yk=(1+2η)ky0y_k = (1 + 2\eta)^k y_0.

M47-C04 · Quadratic convergence of 1D Newton’s method

Section titled “M47-C04 · Quadratic convergence of 1D Newton’s method”
Core

Minimize the strictly convex function f(w)=ew+w2−4wf(w) = e^w + w^2 - 4w starting from w0=2.0w_0 = 2.0 using Newton’s update wt+1=wt−f′(wt)/f′′(wt)w_{t+1} = w_t - f'(w_t) / f''(w_t) for 6 iterations. Print wtw_t and ∣f′(wt)∣\lvert f'(w_t) \rvert at each step and confirm that abs(f'(w_6)) < 1e-14.

Expected output
step 1: w = 1.213013957838, |f'(w)| = 1.79e+00
step 2: w = 0.879351364229, |f'(w)| = 1.68e-01
step 3: w = 0.841241514985, |f'(w)| = 1.73e-03
step 4: w = 0.840841538333, |f'(w)| = 1.85e-07
step 5: w = 0.840841495378, |f'(w)| = 1.78e-15
step 6: w = 0.840841495378, |f'(w)| = 0.00e+00
Starter
# f(w) = exp(w) + w**2 - 4*w
# TODO: write f1(w) and f2(w), run 6 Newton steps from w = 2.0, and print each step
Hint 1

f′(w)=ew+2w−4f'(w) = e^w + 2w - 4 and f′′(w)=ew+2>2f''(w) = e^w + 2 > 2 everywhere (strictly convex!).

Hint 2

Update w = w - f1(w) / f2(w) inside a for step in range(1, 7): loop.

Solution
def f1(w: float) -> float:
return float(np.exp(w) + 2.0 * w - 4.0)
def f2(w: float) -> float:
return float(np.exp(w) + 2.0)
w = 2.0
for step in range(1, 7):
w = w - f1(w) / f2(w)
print(f"step {step}: w = {w:.12f}, |f'(w)| = {abs(f1(w)):.2e}")
assert abs(f1(w)) < 1e-14
Output
step 1: w = 1.213013957838, |f'(w)| = 1.79e+00
step 2: w = 0.879351364229, |f'(w)| = 1.68e-01
step 3: w = 0.841241514985, |f'(w)| = 1.73e-03
step 4: w = 0.840841538333, |f'(w)| = 1.85e-07
step 5: w = 0.840841495378, |f'(w)| = 1.78e-15
step 6: w = 0.840841495378, |f'(w)| = 0.00e+00

How it works:

  1. Because f′′(w)=ew+2>0f''(w) = e^w + 2 > 0 everywhere, Newton steps always move downhill toward the unique global minimum.
  2. Watch the exponent of |f'(w)|: near the optimum, the number of accurate decimal digits roughly doubles on every step — the signature of quadratic convergence.

Alternative: Use scipy.optimize.root_scalar(f1, fprime=f2, x0=2.0, method="newton") to solve f′(w)=0f'(w) = 0.

M47-C05 · Expected capped revenue via quad vs. Monte Carlo

Section titled “M47-C05 · Expected capped revenue via quad vs. Monte Carlo”
Core

Using the converted buyers in data/ab_test.csv, fit a log-normal distribution to revenue as in Example 3 (log_mu, log_sigma with ddof=1). Suppose a cashback promotion caps eligible revenue per order at USD 80: g(R)=min⁡(R,80)g(R) = \min(R, 80). Compute E[min⁡(R,80)]\mathbb{E}[\min(R, 80)] both by scipy.integrate.quad and by Monte Carlo with N=100,000N = 100{,}000 draws (default_rng(42)), and verify they agree within USD 0.25.

Expected output
E[min(R, 80)] quad = USD 39.3253
E[min(R, 80)] Monte Carlo = USD 39.2339
abs diff = USD 0.0914
Starter
ab = pd.read_csv("data/ab_test.csv")
rev = ab.loc[ab["converted"] == 1, "revenue"].to_numpy(dtype=float)
# TODO: fit lognorm, compute E[min(R, 80)] via quad and Monte Carlo (N=100_000)
Hint 1

Split the integral at the kink 80.0 for maximum accuracy: integrate.quad(lambda x: x * dist.pdf(x), 0.0, 80.0)[0] + 80.0 * (1.0 - dist.cdf(80.0)) (or pass points=[80.0] to quad).

Hint 2

For Monte Carlo, draw draws = dist.rvs(size=100_000, random_state=np.random.default_rng(42)) and take np.mean(np.minimum(draws, 80.0)).

Solution
ab = pd.read_csv("data/ab_test.csv")
rev = ab.loc[ab["converted"] == 1, "revenue"].to_numpy(dtype=float)
log_mu = float(np.mean(np.log(rev)))
log_sigma = float(np.std(np.log(rev), ddof=1))
dist = stats.lognorm(s=log_sigma, scale=np.exp(log_mu))
part1, _ = integrate.quad(lambda x: x * dist.pdf(x), 0.0, 80.0)
exp_quad = part1 + 80.0 * float(1.0 - dist.cdf(80.0))
draws = dist.rvs(size=100_000, random_state=np.random.default_rng(42))
exp_mc = float(np.mean(np.minimum(draws, 80.0)))
print(f"E[min(R, 80)] quad = USD {exp_quad:.4f}")
print(f"E[min(R, 80)] Monte Carlo = USD {exp_mc:.4f}")
print(f"abs diff = USD {abs(exp_quad - exp_mc):.4f}")
assert abs(exp_quad - exp_mc) < 0.25
Output
E[min(R, 80)] quad = USD 39.3253
E[min(R, 80)] Monte Carlo = USD 39.2339
abs diff = USD 0.0914

How it works:

  1. Splitting the integral at x=80x = 80 removes the piecewise kink of min⁡(x,80)\min(x, 80): below 80 we integrate xf(x)x f(x), and above 80 the payoff is constant at 80⋅P(R>80)80 \cdot P(R > 80).
  2. Monte Carlo evaluates np.minimum(draws, 80.0) without caring about kinks at all, matching quadrature within a few cents.

Alternative: Call integrate.quad(lambda x: min(x, 80.0) * dist.pdf(x), 0.0, np.inf, points=[80.0]) directly.

M47-C06 · Lagrange multipliers for a linear equality constraint

Section titled “M47-C06 · Lagrange multipliers for a linear equality constraint”
Core

Minimize f(w1,w2)=12(w12+w22)f(w_1, w_2) = \frac{1}{2}(w_1^2 + w_2^2) subject to 2w1+w2=52 w_1 + w_2 = 5. Set up the 3×33 \times 3 linear KKT system for (w1,w2,λ)(w_1, w_2, \lambda) from ∇L=0\nabla \mathcal{L} = \mathbf{0}, solve it with np.linalg.solve, and verify the solution against scipy.optimize.minimize(..., method="SLSQP").

Expected output
KKT : w = [2. 1.], lambda = -1.0000
SLSQP : w = [2. 1.]
Starter
# Lagrangian: L(w1, w2, lam) = 0.5*(w1**2 + w2**2) + lam*(2*w1 + w2 - 5)
# TODO: build the 3x3 linear system K @ sol = rhs, solve it, and verify with SLSQP
Hint 1

Setting partial derivatives to zero gives three equations: w1+2λ=0w_1 + 2\lambda = 0, w2+λ=0w_2 + \lambda = 0, and 2w1+w2=52 w_1 + w_2 = 5.

Hint 2

In matrix form: K = np.array([[1, 0, 2], [0, 1, 1], [2, 1, 0]], dtype=float) and rhs = np.array([0.0, 0.0, 5.0]).

Solution
K = np.array([[1.0, 0.0, 2.0], [0.0, 1.0, 1.0], [2.0, 1.0, 0.0]])
rhs = np.array([0.0, 0.0, 5.0])
w1, w2, lam = np.linalg.solve(K, rhs)
w_kkt = np.array([w1, w2])
res = optimize.minimize(
lambda w: 0.5 * float(w @ w),
x0=np.zeros(2),
constraints={"type": "eq", "fun": lambda w: 2 * w[0] + w[1] - 5.0},
method="SLSQP",
)
print(f"KKT : w = {w_kkt}, lambda = {lam:.4f}")
print(f"SLSQP : w = {res.x}")
assert np.allclose(w_kkt, res.x, atol=1e-6)
assert np.isclose(2 * w1 + w2, 5.0)
Output
KKT : w = [2. 1.], lambda = -1.0000
SLSQP : w = [2. 1.]

How it works:

  1. The KKT matrix encodes both stationarity (∇f+λ∇g=0\nabla f + \lambda \nabla g = \mathbf{0}) and primal feasibility (g(w)=5g(\mathbf{w}) = 5) in one linear system.
  2. Geometrically, (2,1)(2, 1) is the closest point on the line 2w1+w2=52w_1 + w_2 = 5 to the origin, which lies directly along the line’s normal vector (2,1)(2, 1)!

Alternative: Notice that the closed-form minimum-norm solution to a⊤w=c\mathbf{a}^\top \mathbf{w} = c is w∗=c∥a∥22a=55(2,1)=(2,1)\mathbf{w}^* = \frac{c}{\lVert \mathbf{a} \rVert_2^2} \mathbf{a} = \frac{5}{5}(2, 1) = (2, 1).

M47-C07 · Fix the bug: missing bias correction in Adam

Section titled “M47-C07 · Fix the bug: missing bias correction in Adam”
Core

Fix the bug: the Adam implementation below omits the bias corrections 1−β1t1 - \beta_1^t and 1−β2t1 - \beta_2^t on an ill-conditioned quadratic f(w1,w2)=0.5(w12+25w22)f(w_1, w_2) = 0.5(w_1^2 + 25 w_2^2) starting at (0.4, 0.4). Run 20 steps of both the buggy version and the corrected version (lr=0.3), print the loss after step 1 and step 20 for each, and verify that bias-corrected Adam reaches a much lower loss at both step 1 and step 20.

Expected output
buggy: step 1=3.9137, step 20=0.2845
fixed: step 1=0.1300, step 20=0.0052
Starter
def quad_loss(w: np.ndarray) -> float:
return float(0.5 * (w[0] ** 2 + 25.0 * w[1] ** 2))
def quad_grad(w: np.ndarray) -> np.ndarray:
return np.array([w[0], 25.0 * w[1]])
def adam_buggy(lr: float = 0.3, steps: int = 20) -> list[float]:
w = np.array([0.4, 0.4])
m, v = np.zeros(2), np.zeros(2)
b1, b2, eps = 0.9, 0.999, 1e-8
losses = []
for _ in range(1, steps + 1):
g = quad_grad(w)
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g**2
w = w - lr * m / (np.sqrt(v) + eps)
losses.append(quad_loss(w))
return losses
# TODO: write adam_fixed with bias correction and compare step 1 and step 20 losses
Hint 1

At step t=1t = 1, m=0.1gm = 0.1 g and v=0.001g2v = 0.001 g^2, so without bias correction m/v≈(0.1/0.001)sign⁡(g)≈3.16sign⁡(g)m / \sqrt{v} \approx (0.1 / \sqrt{0.001}) \operatorname{sign}(g) \approx 3.16 \operatorname{sign}(g) — jumping over the minimum from 0.4 to -0.55!

Hint 2

Compute m_hat = m / (1 - b1**t) and v_hat = v / (1 - b2**t) before updating w.

Solution
def quad_loss(w: np.ndarray) -> float:
return float(0.5 * (w[0] ** 2 + 25.0 * w[1] ** 2))
def quad_grad(w: np.ndarray) -> np.ndarray:
return np.array([w[0], 25.0 * w[1]])
def run_adam(bias_correct: bool, lr: float = 0.3, steps: int = 20) -> list[float]:
w = np.array([0.4, 0.4])
m, v = np.zeros(2), np.zeros(2)
b1, b2, eps = 0.9, 0.999, 1e-8
losses = []
for t in range(1, steps + 1):
g = quad_grad(w)
m = b1 * m + (1 - b1) * g
v = b2 * v + (1 - b2) * g**2
m_use = m / (1 - b1**t) if bias_correct else m
v_use = v / (1 - b2**t) if bias_correct else v
w = w - lr * m_use / (np.sqrt(v_use) + eps)
losses.append(quad_loss(w))
return losses
buggy = run_adam(bias_correct=False)
fixed = run_adam(bias_correct=True)
print(f"buggy: step 1={buggy[0]:.4f}, step 20={buggy[-1]:.4f}")
print(f"fixed: step 1={fixed[0]:.4f}, step 20={fixed[-1]:.4f}")
assert fixed[0] < buggy[0]
assert fixed[-1] < buggy[-1]
Output
buggy: step 1=3.9137, step 20=0.2845
fixed: step 1=0.1300, step 20=0.0052

How it works:

  1. Because m and v are initialized at zero and beta2 = 0.999 is close to 1, v stays tiny during early steps; dividing by sqrt(v) without bias correction overshoots dramatically on step 1.
  2. Dividing by 1 - beta1**t and 1 - beta2**t keeps the effective step bounded near lr right from t = 1.

Alternative: You can absorb the two bias factors into an effective learning rate ηt=η1−β2t1−β1t\eta_t = \eta \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t} for one fewer array division per step.

M47-C08 · Momentum vs. vanilla GD on a narrow valley

Section titled “M47-C08 · Momentum vs. vanilla GD on a narrow valley”
Core

Minimize the narrow quadratic valley f(w1,w2)=0.5(w12+25w22)f(w_1, w_2) = 0.5(w_1^2 + 25 w_2^2) starting at (10.0, 1.0) until f(w)<10−6f(\mathbf{w}) < 10^{-6}. Compare vanilla GD (lr = 0.075, near its stability ceiling 2/25=0.082 / 25 = 0.08) against heavy-ball Momentum (lr = 0.075, beta = 0.7). Print the iteration count and final loss of each.

Expected output
GD : 114 steps, loss=9.53e-07
Momentum : 47 steps, loss=5.16e-07
Starter
def valley_loss(w: np.ndarray) -> float:
return float(0.5 * (w[0] ** 2 + 25.0 * w[1] ** 2))
def valley_grad(w: np.ndarray) -> np.ndarray:
return np.array([w[0], 25.0 * w[1]])
# TODO: count iterations to reach valley_loss(w) < 1e-6 for GD and Momentum (beta=0.7)
Hint 1

With heavy-ball momentum, update v = beta * v + valley_grad(w) and then w = w - lr * v.

Hint 2

Keep a max_iter = 1000 guard and break as soon as valley_loss(w) < 1e-6.

Solution
def valley_loss(w: np.ndarray) -> float:
return float(0.5 * (w[0] ** 2 + 25.0 * w[1] ** 2))
def valley_grad(w: np.ndarray) -> np.ndarray:
return np.array([w[0], 25.0 * w[1]])
def solve_valley(
beta: float, lr: float = 0.075, tol: float = 1e-6
) -> tuple[int, float]:
w = np.array([10.0, 1.0])
v = np.zeros(2)
for step in range(1, 1001):
v = beta * v + valley_grad(w)
w = w - lr * v
loss = valley_loss(w)
if loss < tol:
return step, loss
return 1000, valley_loss(w)
gd_steps, gd_loss = solve_valley(beta=0.0)
mom_steps, mom_loss = solve_valley(beta=0.7)
print(f"GD : {gd_steps:3d} steps, loss={gd_loss:.2e}")
print(f"Momentum : {mom_steps:3d} steps, loss={mom_loss:.2e}")
assert mom_steps < gd_steps / 2
Output
GD : 114 steps, loss=9.53e-07
Momentum : 47 steps, loss=5.16e-07

How it works:

  1. Across the steep w2w_2 walls, the gradient flips sign every step so momentum cancels oscillations; along the flat w1w_1 floor, gradients point the same way every step so velocity builds up speed.
  2. Momentum cuts the step count by more than 2x (from 114 down to 47) with the exact same learning rate.

Alternative: Theoretical optimal heavy-ball momentum for a quadratic with eigenvalues λmin⁡,λmax⁡\lambda_{\min}, \lambda_{\max} has β=(κ−1κ+1)2\beta = \left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^2, reducing iterations from O(κ)O(\kappa) to O(κ)O(\sqrt{\kappa}).

M47-C09 · Robust Huber regression with scipy.optimize.minimize

Section titled “M47-C09 · Robust Huber regression with scipy.optimize.minimize”
Core

Load data/houses.csv (which contains 8 extreme price outliers) and standardize sqft, bedrooms, bathrooms, condition, and distance_to_center_km. Fit log(price) with both ordinary least squares (np.linalg.lstsq) and Huber regression (δ=0.25\delta = 0.25) using scipy.optimize.minimize(..., method="L-BFGS-B", jac=...). Print the sqft weight and the median absolute error (in log-price) of both models.

Expected output
OLS : sqft_w=0.3664, median_abs_err=0.1884
Huber: sqft_w=0.3804, median_abs_err=0.1866, ok=True
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
# TODO: build standardized design matrix A and target y = log(price)
# TODO: write huber_loss and huber_grad (delta=0.25), fit with L-BFGS-B, compare with OLS
Hint 1

For residuals r=Aw−yr = A\mathbf{w} - \mathbf{y}, the mean Huber loss has gradient 1nA⊤clip⁡(r,−δ,δ)\frac{1}{n} A^\top \operatorname{clip}(\mathbf{r}, -\delta, \delta).

Hint 2

Pass jac=huber_grad to optimize.minimize(huber_loss, x0=np.zeros(A.shape[1]), jac=huber_grad, method="L-BFGS-B") and verify res.success is True.

Solution
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
A = np.column_stack([np.ones(len(Z)), Z])
y = np.log(houses["price"].to_numpy(dtype=float))
delta = 0.25
def huber_loss(w: np.ndarray) -> float:
r = A @ w - y
abs_r = np.abs(r)
terms = np.where(abs_r <= delta, 0.5 * r**2, delta * (abs_r - 0.5 * delta))
return float(np.mean(terms))
def huber_grad(w: np.ndarray) -> np.ndarray:
r = A @ w - y
return (A.T @ np.clip(r, -delta, delta)) / len(y)
w_ols, *_ = np.linalg.lstsq(A, y, rcond=None)
res = optimize.minimize(
huber_loss, x0=np.zeros(A.shape[1]), jac=huber_grad, method="L-BFGS-B"
)
w_hub = res.x
med_ols = float(np.median(np.abs(A @ w_ols - y)))
med_hub = float(np.median(np.abs(A @ w_hub - y)))
print(f"OLS : sqft_w={w_ols[1]:.4f}, median_abs_err={med_ols:.4f}")
print(f"Huber: sqft_w={w_hub[1]:.4f}, median_abs_err={med_hub:.4f}, ok={res.success}")
assert res.success
assert med_hub < med_ols
Output
OLS : sqft_w=0.3664, median_abs_err=0.1884
Huber: sqft_w=0.3804, median_abs_err=0.1866, ok=True

How it works:

  1. Because Huber loss is continuously differentiable everywhere, L-BFGS-B converges cleanly with the analytic gradient A.T @ np.clip(r, -delta, delta) / n.
  2. Clipping large residuals prevents the 8 extreme outlier houses from pulling the fitted plane away from the bulk of the data, improving median absolute error.

Alternative: Compare with sklearn.linear_model.HuberRegressor, which jointly estimates the residual scale parameter alongside the weights.

M47-C10 · Forward-mode automatic differentiation with dual numbers

Section titled “M47-C10 · Forward-mode automatic differentiation with dual numbers”
Core

Implement a Dual(val, der) class for forward-mode automatic differentiation supporting +, *, sin(), and exp() using dual-number algebra: (a+bϵ)(c+dϵ)=ac+(ad+bc)ϵ(a + b\epsilon)(c + d\epsilon) = ac + (ad + bc)\epsilon where ϵ2=0\epsilon^2 = 0. Evaluate f(x)=ex2sin⁡(x)f(x) = e^{x^2} \sin(x) at x=0.7x = 0.7 by passing Dual(0.7, 1.0) and verify both the value and exact derivative against the analytic formula ex2(2xsin⁡x+cos⁡x)e^{x^2}(2x \sin x + \cos x).

Expected output
value: dual=1.051567, exact=1.051567
deriv: dual=2.720658, exact=2.720658
Starter
class Dual:
def __init__(self, val: float, der: float = 0.0) -> None:
self.val = float(val)
self.der = float(der)
# TODO: implement __add__, __mul__, sin, and exp
x = Dual(0.7, 1.0)
# TODO: evaluate (x * x).exp() * x.sin() and compare against analytic formula
Hint 1

By the chain rule for dual numbers, sin(Dual(a, b)) returns Dual(np.sin(a), np.cos(a) * b) and exp(Dual(a, b)) returns Dual(np.exp(a), np.exp(a) * b).

Hint 2

In __mul__, (a + bε)(c + dε) = a*c + (a*d + b*c)ε, which is literally the product rule encoded as arithmetic!

Solution
class Dual:
def __init__(self, val: float, der: float = 0.0) -> None:
self.val = float(val)
self.der = float(der)
def __add__(self, other: "Dual") -> "Dual":
return Dual(self.val + other.val, self.der + other.der)
def __mul__(self, other: "Dual") -> "Dual":
return Dual(
self.val * other.val, self.val * other.der + self.der * other.val
)
def sin(self) -> "Dual":
return Dual(float(np.sin(self.val)), float(np.cos(self.val)) * self.der)
def exp(self) -> "Dual":
e = float(np.exp(self.val))
return Dual(e, e * self.der)
x0 = 0.7
x = Dual(x0, 1.0)
out = (x * x).exp() * x.sin()
exact_val = float(np.exp(x0**2) * np.sin(x0))
exact_der = float(np.exp(x0**2) * (2 * x0 * np.sin(x0) + np.cos(x0)))
print(f"value: dual={out.val:.6f}, exact={exact_val:.6f}")
print(f"deriv: dual={out.der:.6f}, exact={exact_der:.6f}")
assert np.isclose(out.val, exact_val, atol=1e-14)
assert np.isclose(out.der, exact_der, atol=1e-14)
Output
value: dual=1.051567, exact=1.051567
deriv: dual=2.720658, exact=2.720658

How it works:

  1. Setting x = Dual(0.7, 1.0) seeds dxdx=1\frac{dx}{dx} = 1; every operation carries the exact derivative forward alongside the value with zero truncation error and no graph storage.
  2. Forward-mode computes one column of the Jacobian per pass, which makes it ideal when you have few inputs and many outputs (the opposite of deep learning).

Alternative: In complex-step differentiation, np.imag(f(x + 1j * 1e-20)) / 1e-20 achieves a similar machine-precision derivative for real analytic functions using Python’s built-in complex type.

M47-C11 · Fix the bug: gradient accumulation on shared nodes

Section titled “M47-C11 · Fix the bug: gradient accumulation on shared nodes”
Core

Fix the bug: the tiny Value class below overwrites self.grad = ... instead of accumulating with +=. Because x is used in three places inside y=x⋅x+3xy = x \cdot x + 3x, the buggy code returns the wrong derivative at x=2.0x = 2.0 (exact derivative is 2x+3=7.02x + 3 = 7.0). Fix the bug and print both the buggy result and the fixed result.

Expected output
buggy: y=10.0, dy/dx=3.0
fixed: y=10.0, dy/dx=7.0
Starter
class BuggyValue:
def __init__(self, data: float, prev: tuple["BuggyValue", ...] = ()) -> None:
self.data = float(data)
self.grad = 0.0
self._prev = set(prev)
self._backward = lambda: None
def __add__(self, other: "BuggyValue") -> "BuggyValue":
out = BuggyValue(self.data + other.data, (self, other))
def _backward() -> None:
self.grad = out.grad # BUG: overwrites instead of +=
other.grad = out.grad
out._backward = _backward
return out
def __mul__(self, other: "BuggyValue") -> "BuggyValue":
out = BuggyValue(self.data * other.data, (self, other))
def _backward() -> None:
self.grad = other.data * out.grad # BUG: overwrites instead of +=
other.grad = self.data * out.grad
out._backward = _backward
return out
# TODO: fix the accumulation bug and compare buggy vs fixed gradient of y = x*x + 3*x at x=2
Hint 1

When computing x * x, self and other are the exact same object! Writing self.grad = ... followed by other.grad = ... discards the first contribution immediately.

Hint 2

Replace = with += in both _backward closures, and run topological sort in backward() so x * x and 3 * x both finish before accumulating into x.

Solution
def make_value_class(accumulate: bool):
class Node:
def __init__(self, data: float, prev: tuple["Node", ...] = ()) -> None:
self.data = float(data)
self.grad = 0.0
self._prev = set(prev)
self._backward = lambda: None
def _add_grad(self, delta: float) -> None:
if accumulate:
self.grad += delta
else:
self.grad = delta
def __add__(self, other: "Node") -> "Node":
out = Node(self.data + other.data, (self, other))
def _backward() -> None:
self._add_grad(out.grad)
other._add_grad(out.grad)
out._backward = _backward
return out
def __mul__(self, other: "Node") -> "Node":
out = Node(self.data * other.data, (self, other))
def _backward() -> None:
self._add_grad(other.data * out.grad)
other._add_grad(self.data * out.grad)
out._backward = _backward
return out
def backward(self) -> None:
topo, visited = [], set()
def build(v: Node) -> None:
if v not in visited:
visited.add(v)
for c in v._prev:
build(c)
topo.append(v)
build(self)
self.grad = 1.0
for v in reversed(topo):
v._backward()
return Node
for label, acc in [("buggy", False), ("fixed", True)]:
Cls = make_value_class(acc)
x = Cls(2.0)
y = x * x + Cls(3.0) * x
y.backward()
print(f"{label}: y={y.data:.1f}, dy/dx={x.grad:.1f}")
if acc:
assert np.isclose(x.grad, 7.0)
else:
assert not np.isclose(x.grad, 7.0)
Output
buggy: y=10.0, dy/dx=3.0
fixed: y=10.0, dy/dx=7.0

How it works:

  1. By the multivariable chain rule, whenever a variable feeds multiple paths (x⋅xx \cdot x has two paths and 3⋅x3 \cdot x has a third), its total derivative is the sum of all incoming gradients: 2+2+3=72 + 2 + 3 = 7.
  2. Overwriting with = retains only the last incoming edge, silently producing a wrong gradient without raising any error.

Alternative: Write a dedicated __pow__ operator for x2x^2, though you still need += whenever any variable appears in more than one term.

M47-C12 · Choose an optimizer and verify on customers.csv

Section titled “M47-C12 · Choose an optimizer and verify on customers.csv”
Core

Choose a method and justify it: match each of the three ML optimization problems below to the best solver ("L-BFGS-B", "Adam", or "Proximal / Coordinate Descent"):

  1. Full-batch L2-regularized logistic regression with p=30p = 30 features on 5,000 rows (customers.csv).
  2. A 20-million-parameter Transformer trained on mini-batches of 64 sequences.
  3. High-dimensional L1-regularized Lasso regression where exact zero weights are required.

Then verify scenario 1 on data/customers.csv by measuring how many gradient evaluations L-BFGS-B needs to reach ||grad|| < 1e-7 compared to vanilla GD (lr = 0.5).

Expected output
small_convex_logit -> L-BFGS-B
transformer_minibatch -> Adam
sparse_lasso_l1 -> Proximal / Coordinate Descent
L-BFGS-B grad evals: 11 (||g||=2.6e-07)
GD grad evals: 674 (||g||=9.9e-08)
Starter
choices = {
"small_convex_logit": "", # TODO: fill solver name
"transformer_minibatch": "",
"sparse_lasso_l1": "",
}
# TODO: benchmark gradient evaluation counts of L-BFGS-B vs GD on customers.csv
Hint 1

Smooth full-batch convex models with small pp suit quasi-Newton (L-BFGS-B); huge noisy mini-batch neural nets suit adaptive first-order (Adam); non-smooth L1 kinks need Proximal / Coordinate Descent.

Hint 2

optimize.minimize(..., method="L-BFGS-B", options={"gtol": 1e-7}) reports gradient evaluation count in res.njev (or res.nfev).

Solution
choices = {
"small_convex_logit": "L-BFGS-B",
"transformer_minibatch": "Adam",
"sparse_lasso_l1": "Proximal / Coordinate Descent",
}
df = pd.read_csv("data/customers.csv")
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X = df[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
A = np.column_stack([np.ones(len(Z)), Z])
y = df["churned"].to_numpy(dtype=float)
D = np.diag([0.0, 1.0, 1.0, 1.0, 1.0])
def loss(w: np.ndarray) -> float:
z = A @ w
return float(np.mean(np.logaddexp(0.0, z) - y * z) + 0.5e-3 * (w @ D @ w))
def grad(w: np.ndarray) -> np.ndarray:
p = 1.0 / (1.0 + np.exp(-(A @ w)))
return (A.T @ (p - y)) / len(y) + 1e-3 * (D @ w)
res = optimize.minimize(
loss, x0=np.zeros(A.shape[1]), jac=grad, method="L-BFGS-B", options={"gtol": 1e-7}
)
w_gd = np.zeros(A.shape[1])
gd_evals = 0
for step in range(1, 2001):
gd_evals = step
g = grad(w_gd)
if np.linalg.norm(g) < 1e-7:
break
w_gd = w_gd - 0.5 * g
for k, v in choices.items():
print(f"{k:22} -> {v}")
print(f"L-BFGS-B grad evals: {res.njev:3d} (||g||={np.linalg.norm(grad(res.x)):.1e})")
print(f"GD grad evals: {gd_evals:3d} (||g||={np.linalg.norm(grad(w_gd)):.1e})")
assert res.njev < 25
assert gd_evals > 10 * res.njev
Output
small_convex_logit -> L-BFGS-B
transformer_minibatch -> Adam
sparse_lasso_l1 -> Proximal / Coordinate Descent
L-BFGS-B grad evals: 11 (||g||=2.6e-07)
GD grad evals: 674 (||g||=9.9e-08)

How it works:

  1. Each solver exploits the structure of its problem: L-BFGS-B uses secant curvature on smooth full batches, Adam adapts per-parameter step sizes under mini-batch noise, and proximal/coordinate methods handle the L1 kink at zero without smoothing it away.
  2. On customers.csv, L-BFGS-B converges to 1e-7 gradient norm in 11 gradient evaluations — over 60x fewer than vanilla GD (674).

Alternative: On scenario 1 with p=5p = 5, exact Newton’s method uses even fewer iterations (~6), though L-BFGS-B avoids forming the p×pp \times p Hessian when pp grows to hundreds or thousands.

Section titled “M47-X01 · Damped Newton’s method with Armijo backtracking line search”
Challenge

Pure Newton’s method (α=1\alpha = 1) can overshoot if started far from the minimum. Implement damped Newton’s method with an Armijo backtracking line search on the churn logistic regression loss from data/customers.csv, starting from a bad initial guess w0 = np.full(5, 3.0) (where un-damped Newton can take huge initial jumps). At each step, solve Hd=−∇LH \mathbf{d} = -\nabla L, start with α=1.0\alpha = 1.0, and halve α\alpha until L(w+αd)≤L(w)+10−4α(∇L⋅d)L(\mathbf{w} + \alpha \mathbf{d}) \le L(\mathbf{w}) + 10^{-4} \alpha (\nabla L \cdot \mathbf{d}). Print each iteration’s α\alpha, loss, and gradient norm until ||grad|| < 1e-10.

Expected output
step 1: alpha=0.1250, loss=1.25569589, ||g||=3.07e-01
step 2: alpha=0.2500, loss=0.76921363, ||g||=3.61e-01
step 3: alpha=1.0000, loss=0.45623679, ||g||=1.11e-01
step 4: alpha=1.0000, loss=0.41012969, ||g||=2.62e-02
step 5: alpha=1.0000, loss=0.40710797, ||g||=1.96e-03
step 6: alpha=1.0000, loss=0.40706452, ||g||=4.38e-05
step 7: alpha=1.0000, loss=0.40706449, ||g||=2.61e-08
step 8: alpha=1.0000, loss=0.40706449, ||g||=9.31e-15
Starter
df = pd.read_csv("data/customers.csv")
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
# TODO: build standardized A, loss, grad, hess (lam=1e-3)
# TODO: implement Armijo backtracking Newton from w0 = np.full(5, 3.0)
Hint 1

At large w0 = 3.0, probabilities saturate near 0 or 1, making p(1−p)p(1 - p) very small and the pure Newton step huge; backtracking shrinks α\alpha on the first step or two, then automatically uses α=1.0\alpha = 1.0 once close to the solution.

Hint 2

Compute slope = float(g @ d) (guaranteed negative when H≻0H \succ 0) and loop while loss(w + alpha * d) > cur_loss + 1e-4 * alpha * slope: alpha *= 0.5.

Solution
df = pd.read_csv("data/customers.csv")
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X = df[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
A = np.column_stack([np.ones(len(Z)), Z])
y = df["churned"].to_numpy(dtype=float)
D = np.diag([0.0, 1.0, 1.0, 1.0, 1.0])
lam = 1e-3
def loss(w: np.ndarray) -> float:
z = A @ w
return float(np.mean(np.logaddexp(0.0, z) - y * z) + 0.5 * lam * (w @ D @ w))
def grad(w: np.ndarray) -> np.ndarray:
p = 1.0 / (1.0 + np.exp(-np.clip(A @ w, -500, 500)))
return (A.T @ (p - y)) / len(y) + lam * (D @ w)
def hess(w: np.ndarray) -> np.ndarray:
p = 1.0 / (1.0 + np.exp(-np.clip(A @ w, -500, 500)))
return (A.T * (p * (1.0 - p))) @ A / len(y) + lam * D
w = np.full(A.shape[1], 3.0)
steps_taken = 0
for step in range(1, 25):
g = grad(w)
if np.linalg.norm(g) < 1e-10:
break
d = np.linalg.solve(hess(w), -g)
alpha = 1.0
cur_loss = loss(w)
slope = float(g @ d)
while loss(w + alpha * d) > cur_loss + 1e-4 * alpha * slope:
alpha *= 0.5
w = w + alpha * d
steps_taken = step
print(f"step {step:2d}: alpha={alpha:.4f}, loss={loss(w):.8f}, "
f"||g||={np.linalg.norm(grad(w)):.2e}")
assert np.linalg.norm(grad(w)) < 1e-10
assert steps_taken <= 15
Output
step 1: alpha=0.1250, loss=1.25569589, ||g||=3.07e-01
step 2: alpha=0.2500, loss=0.76921363, ||g||=3.61e-01
step 3: alpha=1.0000, loss=0.45623679, ||g||=1.11e-01
step 4: alpha=1.0000, loss=0.41012969, ||g||=2.62e-02
step 5: alpha=1.0000, loss=0.40710797, ||g||=1.96e-03
step 6: alpha=1.0000, loss=0.40706452, ||g||=4.38e-05
step 7: alpha=1.0000, loss=0.40706449, ||g||=2.61e-08
step 8: alpha=1.0000, loss=0.40706449, ||g||=9.31e-15

How it works:

  1. Starting at [3, 3, 3, 3, 3], pure Newton overshoots because saturated sigmoids make the local Hessian tiny; the Armijo condition halves α\alpha automatically to guarantee strict decrease.
  2. Once inside the quadratic basin, α=1.0\alpha = 1.0 is accepted immediately and quadratic convergence finishes the job in a few steps.

Alternative: scipy.optimize.minimize(..., method="trust-ncg") uses a trust region instead of line search to guard Newton steps on even harder non-convex problems.

M47-X02 · Softmax + Cross-Entropy Hessian-vector product check

Section titled “M47-X02 · Softmax + Cross-Entropy Hessian-vector product check”
Challenge

For 3-class sentiment classification on data/reviews.csv (using features ["great", "broken", "refund", "recommend"] plus bias), the full Hessian has size (pK)×(pK)(pK) \times (pK), which grows quadratically with pKpK. Instead of forming the Hessian, derive and implement the Hessian-vector product HvH \mathbf{v} for any direction matrix V∈Rp×KV \in \mathbb{R}^{p \times K}:

(HV)=1nA⊤(P⊙(S−∑kPkSk))where S=AV(HV) = \frac{1}{n} A^\top \Big( P \odot \big(S - \sum_k P_k S_k\big) \Big) \qquad \text{where } S = A V

Verify hvp(W, V) against the finite-difference directional derivative of the gradient (grad(W + h*V) - grad(W - h*V)) / (2*h) to relative error < 1e-7.

Expected output
HVP shape: (5, 3), rel_err: 3.13e-09
first row analytic : [-0.0162 0.0626 -0.0464]
first row numerical: [-0.0162 0.0626 -0.0464]
Starter
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
words = ["great", "broken", "refund", "recommend"]
# TODO: build A (3000, 5) and Y (3000, 3)
# TODO: implement ce_grad(W) and ce_hvp(W, V) and compare with finite difference of ce_grad
Hint 1

Differentiate P=softmax⁡(Z)P = \operatorname{softmax}(Z) along S=AVS = AV: the directional derivative of row ii‘s probabilities is Jsoftmax(zi)si=pi⊙(si−(pi⋅si))J_{\text{softmax}}(\mathbf{z}_i) \mathbf{s}_i = \mathbf{p}_i \odot (\mathbf{s}_i - (\mathbf{p}_i \cdot \mathbf{s}_i)).

Hint 2

In vectorized NumPy, ps = np.sum(P * S, axis=1, keepdims=True) and dP = P * (S - ps), then hvp = (A.T @ dP) / len(A).

Solution
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
words = ["great", "broken", "refund", "recommend"]
texts = reviews["text"].str.lower()
X = np.column_stack([texts.str.count(w).to_numpy(dtype=float) for w in words])
A = np.column_stack([np.ones(len(X)), X])
classes = ["negative", "neutral", "positive"]
y_idx = reviews["sentiment"].map({c: i for i, c in enumerate(classes)}).to_numpy()
Y = np.eye(3)[y_idx]
def softmax_rows(Z: np.ndarray) -> np.ndarray:
s = Z - np.max(Z, axis=1, keepdims=True)
e = np.exp(s)
return e / e.sum(axis=1, keepdims=True)
def ce_grad(W: np.ndarray) -> np.ndarray:
return (A.T @ (softmax_rows(A @ W) - Y)) / len(A)
def ce_hvp(W: np.ndarray, V: np.ndarray) -> np.ndarray:
P = softmax_rows(A @ W)
S = A @ V
dP = P * (S - np.sum(P * S, axis=1, keepdims=True))
return (A.T @ dP) / len(A)
rng = np.random.default_rng(42)
W0 = rng.normal(scale=0.3, size=(A.shape[1], 3))
V0 = rng.normal(scale=0.3, size=(A.shape[1], 3))
hv_ana = ce_hvp(W0, V0)
h = 1e-6
hv_num = (ce_grad(W0 + h * V0) - ce_grad(W0 - h * V0)) / (2 * h)
rel_err = float(np.linalg.norm(hv_ana - hv_num) / np.linalg.norm(hv_ana + hv_num))
print(f"HVP shape: {hv_ana.shape}, rel_err: {rel_err:.2e}")
print("first row analytic :", hv_ana[0])
print("first row numerical:", hv_num[0])
assert rel_err < 1e-7
Output
HVP shape: (5, 3), rel_err: 3.13e-09
first row analytic : [-0.0162 0.0626 -0.0464]
first row numerical: [-0.0162 0.0626 -0.0464]

How it works:

  1. Hessian-vector products cost the same O(npK)O(npK) as one gradient evaluation — never forming the (pK)×(pK)(pK) \times (pK) matrix at all!
  2. This Pearlmutter trick powers Newton-CG (method="Newton-CG" in SciPy) and second-order curvature estimators in deep learning.

Alternative: Compute hvp automatically in PyTorch with torch.func.jvp / double backprop (torch.autograd.grad applied twice).

M47-X03 · Proximal gradient descent (ISTA) for Lasso regression

Section titled “M47-X03 · Proximal gradient descent (ISTA) for Lasso regression”
Challenge

Because λ∥w∥1\lambda \lVert \mathbf{w} \rVert_1 is non-differentiable at 00, smooth gradient descent cannot produce exact zeros. Implement ISTA (Iterative Shrinkage-Thresholding Algorithm) to minimize 12n∥Zw−y∥22+λ∥w∥1\frac{1}{2n}\lVert Z\mathbf{w} - \mathbf{y} \rVert_2^2 + \lambda \lVert \mathbf{w} \rVert_1 on 6 standardized features of data/houses.csv (sqft, bedrooms, bathrooms, condition, distance_to_center_km, has_pool) predicting centered log(price) with λ=0.05\lambda = 0.05. Each step takes a gradient step on the smooth MSE part, then applies soft-thresholding:

Sτ(u)=sign⁡(u)max⁡(∣u∣−τ,0)with τ=ηλS_\tau(u) = \operatorname{sign}(u) \max(\lvert u \rvert - \tau, 0) \qquad \text{with } \tau = \eta \lambda

Run 400 steps with η=1/LLip\eta = 1 / L_{\text{Lip}} (where LLipL_{\text{Lip}} is the largest eigenvalue of 1nZ⊤Z\frac{1}{n} Z^\top Z), print the learned weights and number of exact zeros, and verify the KKT subgradient optimality conditions: ∣gj+λsign⁡(wj)∣<10−5\lvert g_j + \lambda \operatorname{sign}(w_j) \rvert < 10^{-5} for wj≠0w_j \ne 0, and ∣gj∣≤λ+10−5\lvert g_j \rvert \le \lambda + 10^{-5} for wj=0w_j = 0.

Expected output
sqft w=+0.3172 g=-0.0500 KKT=True
bedrooms w=+0.0000 g=-0.0442 KKT=True
bathrooms w=+0.0140 g=-0.0500 KKT=True
condition w=+0.0843 g=-0.0500 KKT=True
distance_to_center_km w=-0.1264 g=+0.0500 KKT=True
has_pool w=+0.0391 g=-0.0500 KKT=True
exact zeros: 1 / 6, all KKT satisfied: True
Starter
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km", "has_pool"]
# TODO: standardize X -> Z, center log(price) -> y
# TODO: implement soft_threshold and ISTA for 400 iterations with lam = 0.05
# TODO: verify KKT optimality conditions for nonzero and zero weights
Hint 1

The Lipschitz constant of ∇(12n∥Zw−y∥22)=1nZ⊤(Zw−y)\nabla \left(\frac{1}{2n}\lVert Z\mathbf{w} - \mathbf{y} \rVert_2^2\right) = \frac{1}{n} Z^\top(Z\mathbf{w} - \mathbf{y}) is L_lip = np.linalg.eigvalsh(Z.T @ Z / len(y))[-1], so lr = 1.0 / L_lip is guaranteed to converge monotonically.

Hint 2

soft_threshold(u, tau) is simply np.sign(u) * np.maximum(np.abs(u) - tau, 0.0).

Solution
houses = pd.read_csv("data/houses.csv")
cols = [
"sqft",
"bedrooms",
"bathrooms",
"condition",
"distance_to_center_km",
"has_pool",
]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
y = np.log(houses["price"].to_numpy(dtype=float))
y = y - y.mean()
lam = 0.05
L_lip = float(np.linalg.eigvalsh((Z.T @ Z) / len(y))[-1])
lr = 1.0 / L_lip
def soft_threshold(u: np.ndarray, tau: float) -> np.ndarray:
return np.sign(u) * np.maximum(np.abs(u) - tau, 0.0)
w = np.zeros(Z.shape[1])
for _ in range(400):
g = (Z.T @ (Z @ w - y)) / len(y)
w = soft_threshold(w - lr * g, lr * lam)
g_final = (Z.T @ (Z @ w - y)) / len(y)
kkt_ok = True
for name, wj, gj in zip(cols, w, g_final, strict=True):
if abs(wj) > 0:
ok = abs(gj + lam * np.sign(wj)) < 1e-5
else:
ok = abs(gj) <= lam + 1e-5
kkt_ok = kkt_ok and ok
print(f"{name:22} w={wj:+.4f} g={gj:+.4f} KKT={ok}")
n_zeros = int(np.sum(w == 0.0))
print(f"exact zeros: {n_zeros} / {len(w)}, all KKT satisfied: {kkt_ok}")
assert n_zeros >= 1
assert kkt_ok
Output
sqft w=+0.3172 g=-0.0500 KKT=True
bedrooms w=+0.0000 g=-0.0442 KKT=True
bathrooms w=+0.0140 g=-0.0500 KKT=True
condition w=+0.0843 g=-0.0500 KKT=True
distance_to_center_km w=-0.1264 g=+0.0500 KKT=True
has_pool w=+0.0391 g=-0.0500 KKT=True
exact zeros: 1 / 6, all KKT satisfied: True

How it works:

  1. The proximal operator of τ∥⋅∥1\tau \lVert \cdot \rVert_1 is soft-thresholding, which clips any weight inside [−τ,+τ][-\tau, +\tau] directly to exact 0.0.
  2. Checking the KKT subgradient conditions proves mathematically that w is the exact global minimum of the non-smooth Lasso objective.

Alternative: FISTA (Fast ISTA) adds Nesterov momentum to the proximal step, improving convergence from O(1/k)O(1/k) to O(1/k2)O(1/k^2).

M47-X04 · Extend scalar autograd with log, relu, and sigmoid and verify vs. PyTorch

Section titled “M47-X04 · Extend scalar autograd with log, relu, and sigmoid and verify vs. PyTorch”
Challenge

Extend the lesson’s Value class with .exp(), .log(), .relu(), and .sigmoid() methods, then compute the binary log loss of a single 2-feature logistic neuron on 3 training examples ([(1.0, -0.5, 1), (-1.2, 0.8, 0), (0.4, 0.6, 1)]) with initial weights w1 = 0.5, w2 = -0.3, b = 0.1. Verify every parameter gradient (w1, w2, b) against torch.autograd to 1e-12.

Expected output
loss: Value=0.470636, torch=0.470636
w1: Value=-0.298814, torch=-0.298814, diff=5.6e-17
w2: Value=+0.045597, torch=+0.045597, diff=1.4e-17
b: Value=-0.155951, torch=-0.155951, diff=0.0e+00
Starter
import torch
torch.set_num_threads(1)
# TODO: implement Value with +, *, exp, log, relu, sigmoid, and backward()
# TODO: compute mean binary log loss on the 3 examples and verify gradients vs torch.autograd
Hint 1

For sigmoid(x): s = 1 / (1 + np.exp(-self.data)), local gradient s * (1 - s). For log(x): local gradient 1 / self.data. For relu(x): max(0.0, self.data), local gradient 1.0 if self.data > 0 else 0.0.

Hint 2

Use dtype=torch.float64 in PyTorch so both engines use 64-bit precision and agree to ~1e-16.

Solution
import torch
torch.set_num_threads(1)
class Value:
def __init__(self, data: float, children: tuple["Value", ...] = ()) -> None:
self.data = float(data)
self.grad = 0.0
self._prev = set(children)
self._backward = lambda: None
def __add__(self, other: "Value | float") -> "Value":
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other))
def _backward() -> None:
self.grad += out.grad
other.grad += out.grad
out._backward = _backward
return out
def __mul__(self, other: "Value | float") -> "Value":
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other))
def _backward() -> None:
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out._backward = _backward
return out
def exp(self) -> "Value":
e = float(np.exp(self.data))
out = Value(e, (self,))
def _backward() -> None:
self.grad += e * out.grad
out._backward = _backward
return out
def log(self) -> "Value":
out = Value(float(np.log(self.data)), (self,))
def _backward() -> None:
self.grad += (1.0 / self.data) * out.grad
out._backward = _backward
return out
def relu(self) -> "Value":
out = Value(max(0.0, self.data), (self,))
def _backward() -> None:
self.grad += (1.0 if self.data > 0.0 else 0.0) * out.grad
out._backward = _backward
return out
def sigmoid(self) -> "Value":
s = float(1.0 / (1.0 + np.exp(-self.data)))
out = Value(s, (self,))
def _backward() -> None:
self.grad += s * (1.0 - s) * out.grad
out._backward = _backward
return out
def backward(self) -> None:
topo, visited = [], set()
def build(node: Value) -> None:
if node not in visited:
visited.add(node)
for child in node._prev:
build(child)
topo.append(node)
build(self)
self.grad = 1.0
for node in reversed(topo):
node._backward()
data = [(1.0, -0.5, 1.0), (-1.2, 0.8, 0.0), (0.4, 0.6, 1.0)]
w1, w2, b = Value(0.5), Value(-0.3), Value(0.1)
total_loss = Value(0.0)
for x1, x2, y in data:
p = (w1 * x1 + w2 * x2 + b).sigmoid()
term = p.log() * (-y) + (Value(1.0) + p * (-1.0)).log() * (-(1.0 - y))
total_loss = total_loss + term
loss_v = total_loss * (1.0 / len(data))
loss_v.backward()
tw1 = torch.tensor(0.5, dtype=torch.float64, requires_grad=True)
tw2 = torch.tensor(-0.3, dtype=torch.float64, requires_grad=True)
tb = torch.tensor(0.1, dtype=torch.float64, requires_grad=True)
t_losses = []
for x1, x2, y in data:
tp = torch.sigmoid(tw1 * x1 + tw2 * x2 + tb)
t_losses.append(-(y * torch.log(tp) + (1.0 - y) * torch.log(1.0 - tp)))
t_loss = torch.stack(t_losses).mean()
t_loss.backward()
print(f"loss: Value={loss_v.data:.6f}, torch={t_loss.item():.6f}")
for name, v_p, t_p in [("w1", w1, tw1), ("w2", w2, tw2), ("b", b, tb)]:
t_grad = t_p.grad.item()
diff = abs(v_p.grad - t_grad)
print(f"{name}: Value={v_p.grad:+.6f}, torch={t_grad:+.6f}, diff={diff:.1e}")
assert diff < 1e-12
Output
loss: Value=0.470636, torch=0.470636
w1: Value=-0.298814, torch=-0.298814, diff=5.6e-17
w2: Value=+0.045597, torch=+0.045597, diff=1.4e-17
b: Value=-0.155951, torch=-0.155951, diff=0.0e+00

How it works:

  1. Adding sigmoid and log lets the autograd graph build binary cross-entropy directly from elementary operations, and topological backprop automatically accumulates gradients across all three training rows.
  2. Comparing against torch.float64 confirms machine-precision agreement.

Alternative: You can implement .sigmoid() purely in terms of .exp() and ** (-1) without a dedicated closure, though a dedicated closure is numerically cleaner and faster.

M47-X05 · Rare-event Monte Carlo with importance sampling

Section titled “M47-X05 · Rare-event Monte Carlo with importance sampling”
Challenge

Estimate the rare tail probability p=P(Z>4.0)≈3.167×10−5p = P(Z > 4.0) \approx 3.167 \times 10^{-5} for a standard normal Z∼N(0,1)Z \sim \mathcal{N}(0, 1) using N=20,000N = 20{,}000 samples (default_rng(42)) in two ways:

  1. Naive Monte Carlo: draw Zi∼N(0,1)Z_i \sim \mathcal{N}(0, 1) and average 1[Zi>4.0]\mathbf{1}[Z_i > 4.0].
  2. Importance sampling: draw Xi∼q=N(4.5,1)X_i \sim q = \mathcal{N}(4.5, 1) (centered in the rare tail!) and average 1[Xi>4.0]⋅ϕ(Xi)q(Xi)\mathbf{1}[X_i > 4.0] \cdot \frac{\phi(X_i)}{q(X_i)}.

Print the exact value (stats.norm.sf(4.0)), both estimates, and their standard errors, showing how dramatically importance sampling reduces variance.

Expected output
exact = 3.167e-05
naive MC (N=20k) = 1.000e-04 (+/- 7.07e-05)
imp. samp (N=20k) = 3.172e-05 (+/- 4.94e-07)
SE reduction = 143.1x
Starter
exact = float(stats.norm.sf(4.0))
N = 20_000
rng = np.random.default_rng(42)
# TODO: compute naive MC and importance sampling (proposal N(4.5, 1)) estimates and SEs
Hint 1

Importance sampling rewrites ∫1[x>4]ϕ(x) dx=∫1[x>4]ϕ(x)q(x)q(x) dx=EX∼q[1[X>4]ϕ(X)q(X)]\int \mathbf{1}[x > 4] \phi(x)\,dx = \int \mathbf{1}[x > 4] \frac{\phi(x)}{q(x)} q(x)\,dx = \mathbb{E}_{X \sim q}\left[\mathbf{1}[X > 4] \frac{\phi(X)}{q(X)}\right].

Hint 2

Compute the importance weights safely in log-space: w = np.exp(stats.norm.logpdf(x) - stats.norm.logpdf(x, loc=4.5)) and evaluate terms = (x > 4.0) * w.

Solution
exact = float(stats.norm.sf(4.0))
N = 20_000
rng = np.random.default_rng(42)
z_naive = rng.standard_normal(N)
naive_terms = (z_naive > 4.0).astype(float)
est_naive = float(naive_terms.mean())
se_naive = float(naive_terms.std(ddof=1) / np.sqrt(N))
x_is = rng.normal(loc=4.5, scale=1.0, size=N)
log_w = stats.norm.logpdf(x_is, loc=0.0) - stats.norm.logpdf(x_is, loc=4.5)
is_terms = (x_is > 4.0) * np.exp(log_w)
est_is = float(is_terms.mean())
se_is = float(is_terms.std(ddof=1) / np.sqrt(N))
print(f"exact = {exact:.3e}")
print(f"naive MC (N=20k) = {est_naive:.3e} (+/- {se_naive:.2e})")
print(f"imp. samp (N=20k) = {est_is:.3e} (+/- {se_is:.2e})")
print(f"SE reduction = {se_naive / se_is:.1f}x")
assert abs(est_is - exact) / exact < 0.05
assert se_is < se_naive / 10
Output
exact = 3.167e-05
naive MC (N=20k) = 1.000e-04 (+/- 7.07e-05)
imp. samp (N=20k) = 3.172e-05 (+/- 4.94e-07)
SE reduction = 143.1x

How it works:

  1. Naive Monte Carlo sees barely 0–2 hits out of 20,000 draws in the Z>4Z > 4 tail, so its relative error is huge.
  2. Shifting the proposal distribution to N(4.5,1)\mathcal{N}(4.5, 1) puts over half the samples inside the tail and reweights each sample by the exact likelihood ratio ϕ(x)/q(x)\phi(x)/q(x), keeping the estimator unbiased while cutting standard error by over 140x!

Alternative: Compute the likelihood ratio analytically as exp⁡(−4.5x+0.5⋅4.52)\exp(-4.5 x + 0.5 \cdot 4.5^2) without calling logpdf.