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:
- Copy the setup block and the starter code into a script, for example
exercise.py. - Replace each to-do comment with your implementation, then run
python exercise.pyfrom the folder that containsdata/. - 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 npimport pandas as pdfrom scipy import integrate, optimize, stats
np.set_printoptions(precision=4, suppress=True)Warm-up
Section titled “Warm-up”M47-W01 · Product and quotient rule check
Section titled “M47-W01 · Product and quotient rule check”Compute the analytic derivatives of (product rule) and (quotient rule) at . Compare each against a central-difference estimate with , printing both values and the absolute error.
f'(1.5): ana=+0.167348, num=+0.167348, err=1.7e-11g'(1.5): ana=-0.118343, num=-0.118343, err=4.9e-12def 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 bothHint 1
For , apply with and to get .
Hint 2
For , apply to get .
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-9f'(1.5): ana=+0.167348, num=+0.167348, err=1.7e-11g'(1.5): ana=-0.118343, num=-0.118343, err=4.9e-12How it works:
- The product rule splits into .
- The quotient rule differentiates into , which is negative at because peaks at .
- Central differences match both formulas to .
Alternative: Rewrite 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”Predict the output: read the code below and write down the exact printed arrays for the ReLU subgradient and the Huber derivative (with ) at r = [-2.0, -0.5, 0.0, 0.5, 2.0], then run the script to verify.
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.0are0.0, and whyhubercaps at±1.0for±2.0.
Hint 1
For r <= 0, r > 0.0 is False, so relu_subgrad selects 0.0 (a valid subgradient at the kink ).
Hint 2
Inside , Huber is (derivative ); outside, its slope is fixed at .
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])relu : [0. 0. 0. 1. 1.]huber: [-1. -0.5 0. 0.5 1. ]How it works:
- ReLU is flat for negative inputs and has slope for positive inputs; picking at is the standard subgradient convention used by PyTorch.
- Huber behaves like MSE inside (slope equals ) and clips to 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 and outside.
M47-W03 · Taylor polynomials of log(1 + x)
Section titled “M47-W03 · Taylor polynomials of log(1 + x)”Evaluate the 1st-, 2nd-, and 3rd-order Taylor polynomials of around at . Print each approximation and its absolute error relative to np.log1p(0.25).
exact = 0.223144T1 = 0.250000 |err| = 0.026856T2 = 0.218750 |err| = 0.004394T3 = 0.223958 |err| = 0.000815x = 0.25exact = float(np.log1p(x))# TODO: compute t1, t2, t3 around a = 0 and print value and absolute error for eachHint 1
Around ,
Hint 2
Notice the denominator is , not , because the -th derivative of at is , which cancels from .
Solution
x = 0.25exact = float(np.log1p(x))t1 = xt2 = x - x**2 / 2t3 = x - x**2 / 2 + x**3 / 3print(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-3exact = 0.223144T1 = 0.250000 |err| = 0.026856T2 = 0.218750 |err| = 0.004394T3 = 0.223958 |err| = 0.000815How it works:
- Each added term matches one higher derivative of at .
- Because is well inside the convergence radius , each order cuts the error roughly by a factor of .
Alternative: Compute the -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”For at , compute the gradient , the directional derivative along the unit vector , and the maximum directional derivative (along the normalized gradient). Verify the directional derivative along numerically.
grad : [ 3. -5.]D_u f : ana=-2.2000, num=-2.2000max rate: 5.8310def 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 rateHint 1
The partial derivatives are and .
Hint 2
Check against (f(w0 + h * u) - f(w0 - h * u)) / (2 * h). The maximum directional derivative over all unit vectors is .
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-6du_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_rategrad : [ 3. -5.]D_u f : ana=-2.2000, num=-2.2000max rate: 5.8310How it works:
- At , the gradient is , so moving along changes at rate (downhill!).
- The steepest ascent rate is , achieved along .
Alternative: Write with so .
M47-W05 · Classify stationary points by Hessian eigenvalues
Section titled “M47-W05 · Classify stationary points by Hessian eigenvalues”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 as zero). Test it on the four matrices in the starter block.
H1: eigs=[2.382 4.618] -> local_minH2: eigs=[-3.2071 -1.7929] -> local_maxH3: eigs=[-1. 3.] -> saddleH4: eigs=[0. 4.] -> degeneratematrices = { "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 classificationHint 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",}H1: eigs=[2.382 4.618] -> local_minH2: eigs=[-3.2071 -1.7929] -> local_maxH3: eigs=[-1. 3.] -> saddleH4: eigs=[0. 4.] -> degenerateHow it works:
H3has positive diagonal entries (1.0, 1.0), yet its eigenvalues are-1.0and3.0because the off-diagonal cross-term2.0bends one direction downward — diagonal entries alone cannot tell a minimum from a saddle!H4has rank 1, so one eigenvalue is0.0(flat direction) and the second-derivative test is inconclusive.
Alternative: For matrices only, you can inspect the determinant and trace, but eigvalsh generalizes cleanly to any dimension .
M47-W06 · Integrate a normal density with scipy.integrate.quad
Section titled “M47-W06 · Integrate a normal density with scipy.integrate.quad”Use scipy.integrate.quad on stats.norm.pdf to compute and for a standard normal variable . Verify each integral against stats.norm.cdf(b) - stats.norm.cdf(a).
[-1.00, +1.00]: quad=0.682689, cdf=0.682689[-1.96, +1.96]: quad=0.950004, cdf=0.950004intervals = [(-1.0, 1.0), (-1.96, 1.96)]# TODO: integrate stats.norm.pdf over each interval and compare with CDF differenceHint 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)[-1.00, +1.00]: quad=0.682689, cdf=0.682689[-1.96, +1.96]: quad=0.950004, cdf=0.950004How it works:
- By the Fundamental Theorem of Calculus, integrating the PDF over recovers the exact CDF increment .
- This reproduces the familiar 68% () and 95% () 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”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].
probs: [0.2447 0.6652 0.09 ]sum : 1.0def 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 from all logits leaves softmax unchanged: .
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)probs: [0.2447 0.6652 0.09 ]sum : 1.0How it works:
- Subtracting the maximum logit shifts the largest exponent to
0.0, so everyexpterm lies in and can never overflow float64. - Using
axis=-1, keepdims=Truemakes 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”Write a helper check_convex_grid(fn, low, high) that draws 200 random pairs and weights using np.random.default_rng(42) and checks whether holds for every pair. Test it on , , and on .
x**2 : passes Jensen check -> True-log(x) : passes Jensen check -> Truesin(x) : passes Jensen check -> Falsefuncs = [ ("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 functionHint 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}x**2 : passes Jensen check -> True-log(x) : passes Jensen check -> Truesin(x) : passes Jensen check -> FalseHow it works:
- and on , so both are strictly convex and pass every chord check.
- flips sign across , so chords dip below the curve and fail Jensen’s inequality.
Alternative: For twice-differentiable 1D functions, evaluating on a grid is an equivalent local test.
M47-C01 · Softmax Jacobian matrix
Section titled “M47-C01 · Softmax Jacobian matrix”Implement softmax_jacobian(z) returning the matrix 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.
[[ 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-17z = 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 sumHint 1
np.diag(p) - np.outer(p, p) constructs the exact Jacobian in one line.
Hint 2
Column 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-6J_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-9assert max_row_sum < 1e-15assert np.allclose(J, J.T)[[ 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-17How it works:
- Because identically, any perturbation to shifts probability mass among classes with zero net change, so (columns sum to 0).
- Because is symmetric (), rows also sum to 0 — adding a constant to all logits leaves 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”Load data/houses.csv and select ["sqft", "bedrooms", "bathrooms", "distance_to_center_km"]. Compute the OLS MSE Hessian (where 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 for both, and compute the ratio of raw to standardized condition number.
raw: min_eig=0.1370, max_eig=7,907,777.24, cond=57,701,821.4std: min_eig=0.2071, max_eig=5.49, cond=26.5condition number reduction: 2,178,232xhouses = 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 numbersHint 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"] > 1e6assert conds["std"] < 100raw: min_eig=0.1370, max_eig=7,907,777.24, cond=57,701,821.4std: min_eig=0.2071, max_eig=5.49, cond=26.5condition number reduction: 2,178,232xHow it works:
- Because
sqftis measured in thousands whilebedroomsis around3, the raw Hessian stretches curvature by more than 10 million times along one axis compared to another. - Standardizing drops to
26.5(remaining stretch comes only from the genuine correlation amongsqft,bedrooms, andbathrooms), cutting the condition number by more than two million times.
Alternative: np.linalg.cond(H) computes the same ratio via singular values (equal to for symmetric positive definite matrices).
M47-C03 · Saddle point stagnation vs. escape
Section titled “M47-C03 · Saddle point stagnation vs. escape”Consider the saddle surface , which has a saddle point at . Run 30 steps of gradient descent () from two starting points: p1 = [1.0, 0.0] (exact symmetry) and p2 = [1.0, 1e-3] (tiny perturbation). Print the final and for both runs.
from (1, 0): end=[0.0012 0. ], f=+0.000002from (1, 1e-3): end=[0.0012 0.2374], f=-0.056346def 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 resultsHint 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) > 0assert f(p2) < -0.05from (1, 0): end=[0.0012 0. ], f=+0.000002from (1, 1e-3): end=[0.0012 0.2374], f=-0.056346How it works:
- Starting exactly on the stable manifold () makes GD converge to the saddle point even though downward directions exist.
- 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 steps, and .
M47-C04 · Quadratic convergence of 1D Newton’s method
Section titled “M47-C04 · Quadratic convergence of 1D Newton’s method”Minimize the strictly convex function starting from using Newton’s update for 6 iterations. Print and at each step and confirm that abs(f'(w_6)) < 1e-14.
step 1: w = 1.213013957838, |f'(w)| = 1.79e+00step 2: w = 0.879351364229, |f'(w)| = 1.68e-01step 3: w = 0.841241514985, |f'(w)| = 1.73e-03step 4: w = 0.840841538333, |f'(w)| = 1.85e-07step 5: w = 0.840841495378, |f'(w)| = 1.78e-15step 6: w = 0.840841495378, |f'(w)| = 0.00e+00# 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 stepHint 1
and 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.0for 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-14step 1: w = 1.213013957838, |f'(w)| = 1.79e+00step 2: w = 0.879351364229, |f'(w)| = 1.68e-01step 3: w = 0.841241514985, |f'(w)| = 1.73e-03step 4: w = 0.840841538333, |f'(w)| = 1.85e-07step 5: w = 0.840841495378, |f'(w)| = 1.78e-15step 6: w = 0.840841495378, |f'(w)| = 0.00e+00How it works:
- Because everywhere, Newton steps always move downhill toward the unique global minimum.
- 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 .
M47-C05 · Expected capped revenue via quad vs. Monte Carlo
Section titled “M47-C05 · Expected capped revenue via quad vs. Monte Carlo”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: . Compute both by scipy.integrate.quad and by Monte Carlo with draws (default_rng(42)), and verify they agree within USD 0.25.
E[min(R, 80)] quad = USD 39.3253E[min(R, 80)] Monte Carlo = USD 39.2339abs diff = USD 0.0914ab = 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.25E[min(R, 80)] quad = USD 39.3253E[min(R, 80)] Monte Carlo = USD 39.2339abs diff = USD 0.0914How it works:
- Splitting the integral at removes the piecewise kink of : below 80 we integrate , and above 80 the payoff is constant at .
- 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”Minimize subject to . Set up the linear KKT system for from , solve it with np.linalg.solve, and verify the solution against scipy.optimize.minimize(..., method="SLSQP").
KKT : w = [2. 1.], lambda = -1.0000SLSQP : w = [2. 1.]# 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 SLSQPHint 1
Setting partial derivatives to zero gives three equations: , , and .
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)KKT : w = [2. 1.], lambda = -1.0000SLSQP : w = [2. 1.]How it works:
- The KKT matrix encodes both stationarity () and primal feasibility () in one linear system.
- Geometrically, is the closest point on the line to the origin, which lies directly along the line’s normal vector !
Alternative: Notice that the closed-form minimum-norm solution to is .
M47-C07 · Fix the bug: missing bias correction in Adam
Section titled “M47-C07 · Fix the bug: missing bias correction in Adam”Fix the bug: the Adam implementation below omits the bias corrections and on an ill-conditioned quadratic 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.
buggy: step 1=3.9137, step 20=0.2845fixed: step 1=0.1300, step 20=0.0052def 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 lossesHint 1
At step , and , so without bias correction — 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]buggy: step 1=3.9137, step 20=0.2845fixed: step 1=0.1300, step 20=0.0052How it works:
- Because
mandvare initialized at zero andbeta2 = 0.999is close to 1,vstays tiny during early steps; dividing bysqrt(v)without bias correction overshoots dramatically on step 1. - Dividing by
1 - beta1**tand1 - beta2**tkeeps the effective step bounded nearlrright fromt = 1.
Alternative: You can absorb the two bias factors into an effective learning rate 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”Minimize the narrow quadratic valley starting at (10.0, 1.0) until . Compare vanilla GD (lr = 0.075, near its stability ceiling ) against heavy-ball Momentum (lr = 0.075, beta = 0.7). Print the iteration count and final loss of each.
GD : 114 steps, loss=9.53e-07Momentum : 47 steps, loss=5.16e-07def 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 / 2GD : 114 steps, loss=9.53e-07Momentum : 47 steps, loss=5.16e-07How it works:
- Across the steep walls, the gradient flips sign every step so momentum cancels oscillations; along the flat floor, gradients point the same way every step so velocity builds up speed.
- 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 has , reducing iterations from to .
M47-C09 · Robust Huber regression with scipy.optimize.minimize
Section titled “M47-C09 · Robust Huber regression with scipy.optimize.minimize”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 () using scipy.optimize.minimize(..., method="L-BFGS-B", jac=...). Print the sqft weight and the median absolute error (in log-price) of both models.
OLS : sqft_w=0.3664, median_abs_err=0.1884Huber: sqft_w=0.3804, median_abs_err=0.1866, ok=Truehouses = 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 OLSHint 1
For residuals , the mean Huber loss has gradient .
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.successassert med_hub < med_olsOLS : sqft_w=0.3664, median_abs_err=0.1884Huber: sqft_w=0.3804, median_abs_err=0.1866, ok=TrueHow it works:
- Because Huber loss is continuously differentiable everywhere, L-BFGS-B converges cleanly with the analytic gradient
A.T @ np.clip(r, -delta, delta) / n. - 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”Implement a Dual(val, der) class for forward-mode automatic differentiation supporting +, *, sin(), and exp() using dual-number algebra: where . Evaluate at by passing Dual(0.7, 1.0) and verify both the value and exact derivative against the analytic formula .
value: dual=1.051567, exact=1.051567deriv: dual=2.720658, exact=2.720658class 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 formulaHint 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.7x = 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)value: dual=1.051567, exact=1.051567deriv: dual=2.720658, exact=2.720658How it works:
- Setting
x = Dual(0.7, 1.0)seeds ; every operation carries the exact derivative forward alongside the value with zero truncation error and no graph storage. - 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”Fix the bug: the tiny Value class below overwrites self.grad = ... instead of accumulating with +=. Because x is used in three places inside , the buggy code returns the wrong derivative at (exact derivative is ). Fix the bug and print both the buggy result and the fixed result.
buggy: y=10.0, dy/dx=3.0fixed: y=10.0, dy/dx=7.0class 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=2Hint 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)buggy: y=10.0, dy/dx=3.0fixed: y=10.0, dy/dx=7.0How it works:
- By the multivariable chain rule, whenever a variable feeds multiple paths ( has two paths and has a third), its total derivative is the sum of all incoming gradients: .
- Overwriting with
=retains only the last incoming edge, silently producing a wrong gradient without raising any error.
Alternative: Write a dedicated __pow__ operator for , 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”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"):
- Full-batch L2-regularized logistic regression with features on 5,000 rows (
customers.csv). - A 20-million-parameter Transformer trained on mini-batches of 64 sequences.
- 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).
small_convex_logit -> L-BFGS-Btransformer_minibatch -> Adamsparse_lasso_l1 -> Proximal / Coordinate DescentL-BFGS-B grad evals: 11 (||g||=2.6e-07)GD grad evals: 674 (||g||=9.9e-08)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.csvHint 1
Smooth full-batch convex models with small 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 = 0for 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 < 25assert gd_evals > 10 * res.njevsmall_convex_logit -> L-BFGS-Btransformer_minibatch -> Adamsparse_lasso_l1 -> Proximal / Coordinate DescentL-BFGS-B grad evals: 11 (||g||=2.6e-07)GD grad evals: 674 (||g||=9.9e-08)How it works:
- 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.
- On
customers.csv, L-BFGS-B converges to1e-7gradient norm in 11 gradient evaluations — over 60x fewer than vanilla GD (674).
Alternative: On scenario 1 with , exact Newton’s method uses even fewer iterations (~6), though L-BFGS-B avoids forming the Hessian when grows to hundreds or thousands.
Challenge
Section titled “Challenge”M47-X01 · Damped Newton’s method with Armijo backtracking line search
Section titled “M47-X01 · Damped Newton’s method with Armijo backtracking line search”Pure Newton’s method () 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 , start with , and halve until . Print each iteration’s , loss, and gradient norm until ||grad|| < 1e-10.
step 1: alpha=0.1250, loss=1.25569589, ||g||=3.07e-01step 2: alpha=0.2500, loss=0.76921363, ||g||=3.61e-01step 3: alpha=1.0000, loss=0.45623679, ||g||=1.11e-01step 4: alpha=1.0000, loss=0.41012969, ||g||=2.62e-02step 5: alpha=1.0000, loss=0.40710797, ||g||=1.96e-03step 6: alpha=1.0000, loss=0.40706452, ||g||=4.38e-05step 7: alpha=1.0000, loss=0.40706449, ||g||=2.61e-08step 8: alpha=1.0000, loss=0.40706449, ||g||=9.31e-15df = 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 very small and the pure Newton step huge; backtracking shrinks on the first step or two, then automatically uses once close to the solution.
Hint 2
Compute slope = float(g @ d) (guaranteed negative when ) 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 = 0for 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-10assert steps_taken <= 15step 1: alpha=0.1250, loss=1.25569589, ||g||=3.07e-01step 2: alpha=0.2500, loss=0.76921363, ||g||=3.61e-01step 3: alpha=1.0000, loss=0.45623679, ||g||=1.11e-01step 4: alpha=1.0000, loss=0.41012969, ||g||=2.62e-02step 5: alpha=1.0000, loss=0.40710797, ||g||=1.96e-03step 6: alpha=1.0000, loss=0.40706452, ||g||=4.38e-05step 7: alpha=1.0000, loss=0.40706449, ||g||=2.61e-08step 8: alpha=1.0000, loss=0.40706449, ||g||=9.31e-15How it works:
- Starting at
[3, 3, 3, 3, 3], pure Newton overshoots because saturated sigmoids make the local Hessian tiny; the Armijo condition halves automatically to guarantee strict decrease. - Once inside the quadratic basin, 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”For 3-class sentiment classification on data/reviews.csv (using features ["great", "broken", "refund", "recommend"] plus bias), the full Hessian has size , which grows quadratically with . Instead of forming the Hessian, derive and implement the Hessian-vector product for any direction matrix :
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.
HVP shape: (5, 3), rel_err: 3.13e-09first row analytic : [-0.0162 0.0626 -0.0464]first row numerical: [-0.0162 0.0626 -0.0464]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_gradHint 1
Differentiate along : the directional derivative of row ‘s probabilities is .
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-6hv_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-7HVP shape: (5, 3), rel_err: 3.13e-09first row analytic : [-0.0162 0.0626 -0.0464]first row numerical: [-0.0162 0.0626 -0.0464]How it works:
- Hessian-vector products cost the same as one gradient evaluation — never forming the matrix at all!
- 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”Because is non-differentiable at , smooth gradient descent cannot produce exact zeros. Implement ISTA (Iterative Shrinkage-Thresholding Algorithm) to minimize on 6 standardized features of data/houses.csv (sqft, bedrooms, bathrooms, condition, distance_to_center_km, has_pool) predicting centered log(price) with . Each step takes a gradient step on the smooth MSE part, then applies soft-thresholding:
Run 400 steps with (where is the largest eigenvalue of ), print the learned weights and number of exact zeros, and verify the KKT subgradient optimality conditions: for , and for .
sqft w=+0.3172 g=-0.0500 KKT=Truebedrooms w=+0.0000 g=-0.0442 KKT=Truebathrooms w=+0.0140 g=-0.0500 KKT=Truecondition w=+0.0843 g=-0.0500 KKT=Truedistance_to_center_km w=-0.1264 g=+0.0500 KKT=Truehas_pool w=+0.0391 g=-0.0500 KKT=Trueexact zeros: 1 / 6, all KKT satisfied: Truehouses = 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 weightsHint 1
The Lipschitz constant of 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.05L_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 = Truefor 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 >= 1assert kkt_oksqft w=+0.3172 g=-0.0500 KKT=Truebedrooms w=+0.0000 g=-0.0442 KKT=Truebathrooms w=+0.0140 g=-0.0500 KKT=Truecondition w=+0.0843 g=-0.0500 KKT=Truedistance_to_center_km w=-0.1264 g=+0.0500 KKT=Truehas_pool w=+0.0391 g=-0.0500 KKT=Trueexact zeros: 1 / 6, all KKT satisfied: TrueHow it works:
- The proximal operator of is soft-thresholding, which clips any weight inside directly to exact
0.0. - Checking the KKT subgradient conditions proves mathematically that
wis the exact global minimum of the non-smooth Lasso objective.
Alternative: FISTA (Fast ISTA) adds Nesterov momentum to the proximal step, improving convergence from to .
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”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.
loss: Value=0.470636, torch=0.470636w1: Value=-0.298814, torch=-0.298814, diff=5.6e-17w2: Value=+0.045597, torch=+0.045597, diff=1.4e-17b: Value=-0.155951, torch=-0.155951, diff=0.0e+00import 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.autogradHint 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 + termloss_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-12loss: Value=0.470636, torch=0.470636w1: Value=-0.298814, torch=-0.298814, diff=5.6e-17w2: Value=+0.045597, torch=+0.045597, diff=1.4e-17b: Value=-0.155951, torch=-0.155951, diff=0.0e+00How it works:
- Adding
sigmoidandloglets the autograd graph build binary cross-entropy directly from elementary operations, and topological backprop automatically accumulates gradients across all three training rows. - Comparing against
torch.float64confirms 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”Estimate the rare tail probability for a standard normal using samples (default_rng(42)) in two ways:
- Naive Monte Carlo: draw and average .
- Importance sampling: draw (centered in the rare tail!) and average .
Print the exact value (stats.norm.sf(4.0)), both estimates, and their standard errors, showing how dramatically importance sampling reduces variance.
exact = 3.167e-05naive MC (N=20k) = 1.000e-04 (+/- 7.07e-05)imp. samp (N=20k) = 3.172e-05 (+/- 4.94e-07)SE reduction = 143.1xexact = float(stats.norm.sf(4.0))N = 20_000rng = np.random.default_rng(42)# TODO: compute naive MC and importance sampling (proposal N(4.5, 1)) estimates and SEsHint 1
Importance sampling rewrites .
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_000rng = 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.05assert se_is < se_naive / 10exact = 3.167e-05naive MC (N=20k) = 1.000e-04 (+/- 7.07e-05)imp. samp (N=20k) = 3.172e-05 (+/- 4.94e-07)SE reduction = 143.1xHow it works:
- Naive Monte Carlo sees barely 0–2 hits out of 20,000 draws in the tail, so its relative error is huge.
- Shifting the proposal distribution to puts over half the samples inside the tail and reweights each sample by the exact likelihood ratio , keeping the estimator unbiased while cutting standard error by over 140x!
Alternative: Compute the likelihood ratio analytically as without calling logpdf.