47. Calculus and optimization for ML
Module 32 introduced derivatives as slopes and gradient descent as walking downhill on a loss. That intuition is enough to fit linear and logistic regression, yet modern machine learning relies on a much richer calculus toolkit: curvature to tell minima from saddle points, matrix derivatives to vectorize backpropagation, integration to compute expectations over continuous outcomes, constrained optimization to explain why Lasso zeroes out features, second-order and adaptive optimizers that converge in a handful of steps, and automatic differentiation engines that compute exact gradients for million-parameter graphs.
This module builds every piece of that toolkit from first principles and verifies every formula numerically in Python on the course datasets.
What you will learn
Section titled “What you will learn”- Apply product, quotient, chain, and higher-order derivative rules, and approximate smooth functions with Taylor polynomials.
- Compute directional derivatives, Jacobians, Hessians, and core ML matrix derivatives, and classify minima, maxima, and saddle points by curvature.
- Compute definite integrals and continuous expectations numerically with
scipy.integrate.quadand with Monte Carlo sampling. - Use convexity and Lagrange multipliers to explain why linear and logistic regression have a single global minimum and why L1 regularization produces sparse weights.
- Compare Newton’s method, L-BFGS, Momentum, RMSProp, and Adam, and build a reverse-mode automatic differentiation engine verified against
torch.autograd.
Prerequisites
Section titled “Prerequisites”- Derivatives, gradients, the chain rule, and batch gradient descent: 32. Math for ML.
- Eigenvalues, positive definiteness, condition numbers, and matrix geometry: 46. Linear algebra in depth (recommended).
- Topological sorting on directed acyclic graphs: 45. Algorithms and data structures II (used inside reverse-mode autodiff).
- Vectorized NumPy arrays and linear algebra routines: 23. NumPy, and PyTorch basics from 42. Deep learning with PyTorch.
- The course datasets
data/customers.csv,data/houses.csv,data/ab_test.csv, anddata/reviews.csv, documented in the data dictionary.
Concepts
Section titled “Concepts”Start with a shared setup block. It imports NumPy, pandas, Matplotlib, SciPy, and PyTorch (pinned to one CPU thread for fast, predictable runs), formats floating-point output, and loads the datasets used throughout the lesson.
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport torchfrom scipy import integrate, optimize, stats
torch.set_num_threads(1)np.set_printoptions(precision=4, suppress=True)
customers = pd.read_csv("data/customers.csv")houses = pd.read_csv("data/houses.csv")ab_test = pd.read_csv("data/ab_test.csv")reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)Limits, continuity and differentiability
Section titled “Limits, continuity and differentiability”A limit is the value approaches as gets arbitrarily close to from both sides. A function is continuous at when the limit exists and equals — no jumps or holes. A function is differentiable at when the difference quotient has the same limit from the left and the right:
Continuity is necessary for differentiability, but not sufficient. Two everyday ML building blocks are continuous everywhere yet have a sharp kink at :
- ReLU, , has left slope and right slope at .
- Absolute error (MAE / L1), , has left slope and right slope at .
At a kink, gradient-based methods pick any slope between the left and right derivatives — a subgradient (for example, for both ReLU and at ). When you want a loss that resists outliers like MAE yet stays smoothly differentiable at so second-order optimizers work cleanly, use the Huber loss, which stitches a quadratic bowl inside to linear tails outside:
Check the left and right slopes of and Huber loss at , and plot both curves side by side:
def huber(r: np.ndarray, delta: float = 1.0) -> np.ndarray: abs_r = np.abs(r) return np.where(abs_r <= delta, 0.5 * r**2, delta * (abs_r - 0.5 * delta))
def huber_grad(r: np.ndarray, delta: float = 1.0) -> np.ndarray: return np.where(np.abs(r) <= delta, r, delta * np.sign(r))
h = 1e-6mae_left = (abs(0.0) - abs(-h)) / hmae_right = (abs(h) - abs(0.0)) / hhub_left = (float(huber(np.array(0.0))) - float(huber(np.array(-h)))) / hhub_right = (float(huber(np.array(h))) - float(huber(np.array(0.0)))) / hprint(f"MAE at 0: left slope = {mae_left:+.4f}, right slope = {mae_right:+.4f}")print(f"Huber at 0: left slope = {hub_left:+.4f}, right slope = {hub_right:+.4f}")MAE at 0: left slope = -1.0000, right slope = +1.0000Huber at 0: left slope = -0.0000, right slope = +0.0000r_grid = np.linspace(-3.0, 3.0, 300)fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5))ax1.plot(r_grid, 0.5 * r_grid**2, "--", label="0.5 * r^2 (MSE)")ax1.plot(r_grid, np.abs(r_grid), label="|r| (MAE)")ax1.plot(r_grid, huber(r_grid, delta=1.0), lw=2, label="Huber (delta=1)")ax1.set_title("Loss functions")ax1.set_xlabel("residual r")ax1.set_ylabel("loss")ax1.set_ylim(0, 4.0)ax1.legend()
ax2.plot(r_grid, r_grid, "--", label="MSE derivative")ax2.plot(r_grid, np.sign(r_grid), label="MAE derivative (jump at 0)")ax2.plot(r_grid, huber_grad(r_grid, delta=1.0), lw=2, label="Huber derivative")ax2.set_title("First derivatives")ax2.set_xlabel("residual r")ax2.set_ylabel("dL / dr")ax2.set_ylim(-2.5, 2.5)ax2.legend()fig.tight_layout()plt.show()![Two side-by-side panels comparing MSE, MAE, and Huber loss. Left: MSE is a steep parabola, MAE is a V-shape with a corner at zero, and Huber smoothly curves near zero before becoming linear. Right: the MAE derivative jumps discontinuously from -1 to +1 at zero while the Huber derivative transitions linearly across [-1, 1] and caps at plus or minus 1.](/generated/foundations-deep-dive/47-calculus-and-optimization/index/fig-01.png)
Notice the derivative panel: MSE’s gradient grows without bound for outliers, MAE’s gradient jumps abruptly from to at , and Huber’s gradient is continuous everywhere and clipped to .
Full derivative toolkit: product, quotient and chain rules
Section titled “Full derivative toolkit: product, quotient and chain rules”Module 32 covered power, sum, exponential, log, and simple chain rules. Two more rules complete single-variable differentiation:
- The product rule differentiates a product of two functions: .
- The quotient rule differentiates a ratio: whenever .
| Rule | Formula | ML appearance |
|---|---|---|
| Product | expected value derivatives, entropy | |
| Quotient | sigmoid , softmax ratios, F1 score | |
| Chain | backpropagation through every network layer | |
| Inverse / log | log-likelihoods, softplus |
Derive the sigmoid derivative with the quotient rule on (, , , ):
Verify the product rule on binary entropy , the quotient rule on , and the chain rule on softplus (whose derivative is !):
def central_diff(f, x: float, h: float = 1e-6) -> float: return float((f(x + h) - f(x - h)) / (2 * h))
def sigmoid(z): return 1.0 / (1.0 + np.exp(-z))
checks = [ ("product -p*log(p) at 0.3", lambda p: -p * np.log(p), 0.3, -np.log(0.3) - 1.0), ("quotient sigmoid(z) at 0.8", sigmoid, 0.8, sigmoid(0.8) * (1 - sigmoid(0.8))), ("chain softplus(z) at 0.8", lambda z: np.log1p(np.exp(z)), 0.8, sigmoid(0.8)),]for label, fn, x0, analytic in checks: num = central_diff(fn, x0) err = abs(num - analytic) print(f"{label:28} num={num:+.6f} ana={analytic:+.6f} err={err:.1e}")product -p*log(p) at 0.3 num=+0.203973 ana=+0.203973 err=1.5e-11quotient sigmoid(z) at 0.8 num=+0.213910 ana=+0.213910 err=8.8e-12chain softplus(z) at 0.8 num=+0.689974 ana=+0.689974 err=8.8e-11Every analytic rule agrees with central differences to at least 9 significant digits. Notice that the derivative of softplus is the sigmoid — softplus is a smooth approximation of ReLU whose derivative smoothly approximates the step function.
Second derivatives, concavity and Taylor series
Section titled “Second derivatives, concavity and Taylor series”The second derivative is the derivative of the derivative: it measures curvature, or how fast the slope is changing.
- : the curve bends upward (convex / concave up, like a cup). A stationary point () with is a local minimum.
- : the curve bends downward (concave down, like a cap). A stationary point with is a local maximum.
- : inconclusive — it may be an inflection point (such as at , which is flat at but neither a minimum nor a maximum).
Near a point , you can approximate any smooth function by its Taylor polynomial of degree , matching its value and first derivatives at :
Optimization uses the first-order and second-order Taylor models everywhere:
- Gradient descent replaces the loss locally with the linear model plus a step-size penalty.
- Newton’s method replaces the loss locally with the quadratic model and jumps straight to the bottom of that parabola: .
Check the curvature of at its stationary point :
w_star = float(np.log(2.0))f_prime = np.exp(w_star) - 2.0f_second = np.exp(w_star)print( f"w* = {w_star:.4f}, f'(w*) = {f_prime:.1e}, " f"f''(w*) = {f_second:.4f} > 0 (minimum)")w* = 0.6931, f'(w*) = 0.0e+00, f''(w*) = 2.0000 > 0 (minimum)Example 1 plots 1st-, 2nd-, and 3rd-order Taylor polynomials and measures their exact approximation errors.
Multivariable calculus: directional derivatives, level curves and the Jacobian
Section titled “Multivariable calculus: directional derivatives, level curves and the Jacobian”When a loss takes inputs, the gradient collects all partial derivatives. How fast does change if you move in an arbitrary unit direction ()? That rate is the directional derivative:
Two geometric facts fall right out of that dot product:
- Steepest ascent and descent: is maximized at (along ) and minimized at (along ).
- Perpendicular to level curves: along a level curve (contour of constant loss, ), the value does not change, so . Therefore is always perpendicular to the contour lines!
Now suppose a function maps a vector to a vector: (for example, a softmax layer mapping logits to probabilities, or a linear layer mapping inputs to hidden units). Its derivative is no longer a single vector — it is the Jacobian matrix , where row is the gradient of output component :
For the softmax function , applying the quotient rule gives a compact Jacobian:
Verify the softmax Jacobian numerically:
def softmax(z: np.ndarray) -> np.ndarray: shifted = z - np.max(z) exps = np.exp(shifted) return exps / exps.sum()
def softmax_jacobian(z: np.ndarray) -> np.ndarray: p = softmax(z) return np.diag(p) - np.outer(p, p)
def numerical_jacobian(f, x: np.ndarray, h: float = 1e-6) -> np.ndarray: m, p_dim = len(f(x)), len(x) jac = np.zeros((m, p_dim)) for j in range(p_dim): step = np.zeros(p_dim) step[j] = h jac[:, j] = (f(x + step) - f(x - step)) / (2 * h) return jac
z0 = np.array([1.2, -0.4, 0.7])j_ana = softmax_jacobian(z0)j_num = numerical_jacobian(softmax, z0)print("analytic Jacobian:\n", j_ana)print(f"max abs error vs numerical: {np.max(np.abs(j_ana - j_num)):.1e}")analytic Jacobian: [[ 0.2472 -0.0617 -0.1855] [-0.0617 0.0992 -0.0374] [-0.1855 -0.0374 0.2229]]max abs error vs numerical: 2.7e-11Look at the entries: diagonal terms are positive (raising logit raises ), off-diagonal terms are negative (raising logit steals probability mass from ), and every row sums to because the probabilities always sum to .
The Hessian matrix: curvature, saddle points and positive definiteness
Section titled “The Hessian matrix: curvature, saddle points and positive definiteness”The multivariable analogue of is the Hessian matrix of all second partial derivatives:
For smooth functions, the order of differentiation does not matter (), so the Hessian is always symmetric. By the spectral theorem (Module 46), a symmetric matrix has real eigenvalues pointing along orthogonal principal curvature directions. At a stationary point where , the signs of the eigenvalues classify the point completely:
| Eigenvalues of | Matrix property | Type of stationary point |
|---|---|---|
| All | Positive definite () | Strict local minimum (bowl curving up in every direction) |
| All | Negative definite () | Strict local maximum (cap curving down in every direction) |
| Some and some | Indefinite | Saddle point (curves up in some directions, down in others) |
| All , some | Positive semidefinite () | Flat valley or degenerate point (higher derivatives needed) |
In deep neural networks, most stationary points in high dimensions are saddle points, not bad local minima: with 1,000 parameters, needing all 1,000 eigenvalues to be positive at once is far rarer than having a mix of positive and negative curvatures.
The Hessian also explains why unscaled features cripple gradient descent. Around a minimum, the ratio is the condition number of the curvature. When is huge, contours are narrow ellipses: a learning rate small enough not to blow up along the steep axis () crawls painfully slowly along the flat axis ().
Classify three 2D quadratic surfaces at the origin using np.linalg.eigvalsh:
surfaces = { "bowl x^2 + 3y^2": np.array([[2.0, 0.0], [0.0, 6.0]]), "cap -2x^2 - y^2": np.array([[-4.0, 0.0], [0.0, -2.0]]), "saddle x^2 - 2y^2": np.array([[2.0, 0.0], [0.0, -4.0]]),}for name, H in surfaces.items(): eigs = np.linalg.eigvalsh(H) if np.all(eigs > 0): kind = "local minimum (positive definite)" elif np.all(eigs < 0): kind = "local maximum (negative definite)" else: kind = "saddle point (indefinite)" print(f"{name:18} eigs={eigs} -> {kind}")bowl x^2 + 3y^2 eigs=[2. 6.] -> local minimum (positive definite)cap -2x^2 - y^2 eigs=[-4. -2.] -> local maximum (negative definite)saddle x^2 - 2y^2 eigs=[-4. 2.] -> saddle point (indefinite)Matrix calculus recipes for ML
Section titled “Matrix calculus recipes for ML”Writing gradients element by element is slow and error-prone. Instead, ML derivations rely on a handful of matrix calculus identities (in denominator-layout convention, where the gradient of a scalar with respect to a vector or matrix has the exact same shape as that parameter):
| Expression or | Gradient | Hessian |
|---|---|---|
| (symmetric ) | ||
| (MSE) | ||
| (Ridge) | ||
| Binary log loss, | ||
| Softmax + cross-entropy, | block-structured PSD |
Verify the quadratic form identity for a symmetric matrix :
rng = np.random.default_rng(42)M = rng.normal(size=(3, 3))A_sym = 0.5 * (M + M.T)w_test = np.array([1.5, -0.5, 2.0])
def quad_form(w: np.ndarray) -> float: return float(w @ A_sym @ w)
g_ana = 2 * A_sym @ w_testg_num = np.array([ (quad_form(w_test + 1e-6 * e) - quad_form(w_test - 1e-6 * e)) / 2e-6 for e in np.eye(3)])print("analytic :", g_ana)print("numerical:", g_num)print("match :", np.allclose(g_ana, g_num, atol=1e-7))analytic : [ 2.7204 -1.4349 2.0594]numerical: [ 2.7204 -1.4349 2.0594]match : TrueIntegration as area and expectation
Section titled “Integration as area and expectation”Differentiation breaks change into infinitesimal slopes; integration puts infinitesimal pieces back together. A definite integral is the signed area under from to . By the Fundamental Theorem of Calculus, if , then:
In probability and ML, integration turns continuous probability densities into probabilities and expectations:
- Probability from a PDF: , where is the CDF.
- Continuous expectation: .
- Marginalizing a latent variable (Bayesian posteriors, variational inference): .
In 1 dimension, adaptive quadrature (scipy.integrate.quad) evaluates integrals to ~14 digits of precision in milliseconds. In 10 or 10,000 dimensions (where grid-based quadrature suffers the curse of dimensionality), ML switches to Monte Carlo integration: draw i.i.d. samples and average :
Monte Carlo’s standard error shrinks as regardless of dimension! Check both on the standard normal PDF for and :
area, est_err = integrate.quad(stats.norm.pdf, -1.0, 1.0)cdf_diff = stats.norm.cdf(1.0) - stats.norm.cdf(-1.0)ez2_quad, _ = integrate.quad(lambda x: x**2 * stats.norm.pdf(x), -np.inf, np.inf)samples = rng.standard_normal(50_000)ez2_mc = float(np.mean(samples**2))print(f"P(-1 <= Z <= 1): quad={area:.6f} (err {est_err:.1e}), CDF diff={cdf_diff:.6f}")print(f"E[Z^2]: quad={ez2_quad:.6f}, Monte Carlo (N=50k)={ez2_mc:.4f}")P(-1 <= Z <= 1): quad=0.682689 (err 7.6e-15), CDF diff=0.682689E[Z^2]: quad=1.000000, Monte Carlo (N=50k)=1.0056Convexity: global vs. local minima
Section titled “Convexity: global vs. local minima”A function is a convex function if the line segment joining any two points on its graph lies on or above the curve (Jensen’s inequality):
For twice-differentiable functions, convexity has a direct curvature test: is convex if and only if its Hessian is positive semidefinite (, all eigenvalues ) everywhere. If everywhere, is strictly convex.
Why does convexity matter so much in ML?
- Every local minimum of a convex function is a global minimum. If is strictly convex, the global minimum is unique — your starting point does not matter!
- Linear regression (), Ridge regression (), logistic regression (), and SVMs are all convex.
- Deep neural networks compose non-linear activations with matrix products, making their loss surface non-convex with many local minima and saddle points. That is why initialization, adaptive optimizers, and learning-rate schedules matter so much in deep learning.
Verify Jensen’s inequality on convex binary log loss versus a non-convex wavy loss :
def convex_loss(z: float) -> float: return float(np.log1p(np.exp(-z))) # -log(sigmoid(z)) for y=1
def nonconvex_loss(z: float) -> float: return float(0.1 * z**2 + np.sin(2.0 * z))
u, v, t = -1.0, 2.0, 0.5mid = t * u + (1 - t) * vprint( f"convex f(mid)={convex_loss(mid):.4f} <= " f"chord={t * convex_loss(u) + (1 - t) * convex_loss(v):.4f}: " f"{convex_loss(mid) <= t * convex_loss(u) + (1 - t) * convex_loss(v)}")print( f"nonconvex f(mid)={nonconvex_loss(mid):.4f} <= " f"chord={t * nonconvex_loss(u) + (1 - t) * nonconvex_loss(v):.4f}: " f"{nonconvex_loss(mid) <= t * nonconvex_loss(u) + (1 - t) * nonconvex_loss(v)}")convex f(mid)=0.4741 <= chord=0.7201: Truenonconvex f(mid)=0.8665 <= chord=-0.5830: FalseConstrained optimization and Lagrange multipliers
Section titled “Constrained optimization and Lagrange multipliers”Many ML problems minimize a loss subject to a budget or geometric constraint :
- Ridge regression: minimize MSE subject to (a circle/sphere).
- Lasso regression: minimize MSE subject to (a diamond/cross-polytope).
- PCA (Module 46): maximize variance subject to .
- Support Vector Machines: minimize subject to margin inequalities .
At a constrained optimum on the boundary , the level curve of must be tangent to the constraint surface . (If the two curves crossed, you could slide along the constraint to lower further!) Since gradients are perpendicular to level curves, tangency means the two gradients are parallel:
where is the Lagrangian and is the Lagrange multiplier. For inequality constraints , the Karush–Kuhn–Tucker (KKT) conditions generalize this rule: either the constraint is inactive (, unconstrained minimum lies inside the budget) or active (, optimum sits on the boundary with parallel gradients).
This single equation explains why the penalized form used in scikit-learn is mathematically equivalent to solving MSE inside a ball ! Check the gradient alignment on a concrete 2D example — minimizing on the unit circle :
target = np.array([3.0, 2.0])w_opt = target / np.linalg.norm(target) # closest point on the unit circlegrad_f = 2 * (w_opt - target)grad_g = 2 * w_optlam = -float(grad_f @ grad_g) / float(grad_g @ grad_g)print("w_opt :", w_opt)print("grad_f:", grad_f)print("grad_g:", grad_g)print(f"lambda = {lam:.4f}, residual ||grad_f + lam*grad_g|| = " f"{np.linalg.norm(grad_f + lam * grad_g):.1e}")w_opt : [0.8321 0.5547]grad_f: [-4.3359 -2.8906]grad_g: [1.6641 1.1094]lambda = 2.6056, residual ||grad_f + lam*grad_g|| = 9.9e-16The residual is zero to machine precision: and point along the exact same line at the constrained optimum. Example 4 draws this geometry on real house-price contours for both Ridge and Lasso.
Beyond vanilla gradient descent: Newton, L-BFGS, Momentum, RMSProp and Adam
Section titled “Beyond vanilla gradient descent: Newton, L-BFGS, Momentum, RMSProp and Adam”Vanilla gradient descent treats every coordinate with the same fixed step size and ignores both past momentum and local curvature. Modern ML uses two families of upgrades:
- Second-order and quasi-Newton methods (best for small/medium convex problems, full batches):
- Newton’s method uses the exact Hessian to rescale and rotate the gradient:
In code, solve with
np.linalg.solve(never invert ). Near a strictly convex minimum, Newton converges quadratically (the number of accurate digits roughly doubles every step!), but building and solving a Hessian costs per step. - L-BFGS (Limited-memory Broyden–Fletcher–Goldfarb–Shanno,
scipy.optimize.minimize(..., method="L-BFGS-B")) approximates the inverse Hessian from the last gradient differences in time and memory. It is the default solver inside scikit-learn’sLogisticRegression.
- Newton’s method uses the exact Hessian to rescale and rotate the gradient:
In code, solve with
- Accelerated and adaptive first-order methods (best for large-scale, mini-batch, non-convex neural networks):
- Momentum keeps an exponential moving average of gradients (velocity ), damping oscillations across narrow valleys and accelerating along flat directions.
- RMSProp divides each parameter’s step by the root-mean-square of its recent squared gradients (), giving each coordinate its own adaptive step size.
- Adam combines Momentum (, ) and RMSProp (, ) with bias corrections and :
| Optimizer | Order / Memory | Cost per step | Best suited for |
|---|---|---|---|
| Vanilla GD / SGD | 1st / | teaching, well-conditioned linear models | |
| Momentum | 1st / | CNNs, narrow valleys with tuned | |
| RMSProp | 1st / | noisy/non-stationary objectives, RNNs | |
| Adam | 1st / | default for deep nets and mini-batches | |
| L-BFGS | quasi-2nd / | full-batch convex models (), LogisticRegression |
|
| Newton | 2nd / | low-dimensional () strictly convex problems |
Automatic differentiation: forward-mode vs. reverse-mode
Section titled “Automatic differentiation: forward-mode vs. reverse-mode”How does PyTorch compute exact gradients for a 100-million-parameter model without hand-derived formulas and without the rounding error of finite differences? It uses automatic differentiation (autodiff) — neither symbolic algebra (which suffers expression swell) nor numerical finite differences (which suffer truncation/roundoff error and cost evaluations).
Autodiff represents any program as a computation graph (a DAG of elementary operations +, *, exp, tanh). Every node knows its local partial derivatives. Then the chain rule runs in one of two directions:
flowchart LR
X["x = 2.0"] -->|"du/dx = w = -3.0"| U["u = x·w = -6.0"]
W["w = -3.0"] -->|"du/dw = x = 2.0"| U
U -->|"dz/du = 1.0"| Z["z = u + b = -4.0"]
B["b = 2.0"] -->|"dz/db = 1.0"| Z
Z -->|"dL/dz = 2z = -8.0"| L["L = z² = 16.0"]
- Forward-mode autodiff propagates from one input forward to all outputs using dual numbers. Cost: passes for inputs and outputs (great when ).
- Reverse-mode automatic differentiation (backpropagation) runs one forward pass to record values, then walks the graph in reverse topological order (Module 45) propagating backward from the scalar loss to every parameter in one sweep! Cost: passes — just one backward pass when the loss is a scalar (), whether or .
When a node feeds two branches downstream, its gradients add (child.grad += local_grad * parent.grad) by the multivariable chain rule. Example 6 implements a full working engine in ~45 lines of Python.
Worked examples
Section titled “Worked examples”Example 1 — Taylor approximations of exp, log(1 + x) and sigmoid
Section titled “Example 1 — Taylor approximations of exp, log(1 + x) and sigmoid”Goal: Approximate , , and around with 1st-, 2nd-, and 3rd-order Taylor polynomials, measure their worst-case errors on , and visualize how higher orders hug each curve further from the center.
Step 1 — Define the exact functions and Taylor polynomials at 0
Section titled “Step 1 — Define the exact functions and Taylor polynomials at 0”Around :
- (the quadratic term vanishes because : the sigmoid has an inflection point at !)
xs = np.linspace(-0.5, 0.5, 201)
taylors = { "exp(x)": ( np.exp(xs), [1 + xs, 1 + xs + xs**2 / 2, 1 + xs + xs**2 / 2 + xs**3 / 6], ), "log(1+x)": ( np.log1p(xs), [xs, xs - xs**2 / 2, xs - xs**2 / 2 + xs**3 / 3], ), "sigmoid(x)": ( sigmoid(xs), [0.5 + xs / 4, 0.5 + xs / 4, 0.5 + xs / 4 - xs**3 / 48], ),}for name, (exact, polys) in taylors.items(): errs = [float(np.max(np.abs(exact - p))) for p in polys] print(f"{name:11} max |err| on [-0.5, 0.5]: " f"T1={errs[0]:.5f} T2={errs[1]:.5f} T3={errs[2]:.5f}")exp(x) max |err| on [-0.5, 0.5]: T1=0.14872 T2=0.02372 T3=0.00289log(1+x) max |err| on [-0.5, 0.5]: T1=0.19315 T2=0.06815 T3=0.02648sigmoid(x) max |err| on [-0.5, 0.5]: T1=0.00254 T2=0.00254 T3=0.00006Each extra order cuts the worst-case error sharply on — for sigmoid(x), and are identical because , and adding the cubic term drops the max error by more than 10x.
Step 2 — Plot the approximations over a wider interval
Section titled “Step 2 — Plot the approximations over a wider interval”xw = np.linspace(-1.5, 1.5, 300)x_log = np.linspace(-0.85, 1.5, 300)fig, axes = plt.subplots(1, 3, figsize=(11, 3.4))
axes[0].plot(xw, np.exp(xw), "k", lw=2, label="exact")axes[0].plot(xw, 1 + xw, "--", label="T1")axes[0].plot(xw, 1 + xw + xw**2 / 2, "-.", label="T2")axes[0].plot(xw, 1 + xw + xw**2 / 2 + xw**3 / 6, ":", lw=2, label="T3")axes[0].set_title("exp(x)")axes[0].set_ylim(-0.5, 5.0)axes[0].legend(fontsize=8)
axes[1].plot(x_log, np.log1p(x_log), "k", lw=2, label="exact")axes[1].plot(x_log, x_log, "--", label="T1")axes[1].plot(x_log, x_log - x_log**2 / 2, "-.", label="T2")axes[1].plot(x_log, x_log - x_log**2 / 2 + x_log**3 / 3, ":", lw=2, label="T3")axes[1].set_title("log(1 + x)")axes[1].set_ylim(-2.2, 1.5)axes[1].legend(fontsize=8)
axes[2].plot(xw, sigmoid(xw), "k", lw=2, label="exact")axes[2].plot(xw, 0.5 + xw / 4, "--", label="T1 = T2")axes[2].plot(xw, 0.5 + xw / 4 - xw**3 / 48, ":", lw=2, label="T3")axes[2].set_title("sigmoid(x)")axes[2].set_ylim(0.0, 1.0)axes[2].legend(fontsize=8)
for ax in axes: ax.set_xlabel("x")fig.tight_layout()plt.show()
Every polynomial is exact at , and tracks all three curves closely across before peeling away. Notice why diverges sharply beyond : its Taylor series only converges for .
Common mistakes:
- Using a Taylor polynomial far from its expansion point — local models are only trustworthy inside a small trust region around .
- Dropping the factorial denominator (writing instead of in ).
Example 2 — Hessian and Newton’s method for logistic regression on churn data
Section titled “Example 2 — Hessian and Newton’s method for logistic regression on churn data”Goal: Compute the analytic gradient and Hessian of L2-regularized logistic regression on data/customers.csv, verify strict convexity via the Hessian eigenvalues, and compare 6 iterations of Newton’s method against 500 iterations of gradient descent.
Step 1 — Build the standardized churn design matrix
Section titled “Step 1 — Build the standardized churn design matrix”churn_cols = [ "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes", "has_autopay",]Xc = customers[churn_cols].to_numpy(dtype=float)yc = customers["churned"].to_numpy(dtype=float)Xc_std = (Xc - Xc.mean(axis=0)) / Xc.std(axis=0)Ac = np.column_stack([np.ones(len(Xc_std)), Xc_std])print("design matrix shape:", Ac.shape, "positive rate:", round(float(yc.mean()), 4))design matrix shape: (5000, 7) positive rate: 0.1926Adding the leading column of ones gives 7 parameters (intercept plus 6 standardized customer features) across all 5,000 customers.
Step 2 — Write loss, gradient, and Hessian, and verify strict convexity
Section titled “Step 2 — Write loss, gradient, and Hessian, and verify strict convexity”For binary log loss with a small L2 penalty (leaving the intercept unpenalized):
where .
LAM = 1e-3D_reg = np.diag([0.0] + [1.0] * (Ac.shape[1] - 1))
def logit_loss(w: np.ndarray) -> float: z = Ac @ w # log(1 + exp(z)) - y*z is algebraically equal to log loss and avoids log(0) data_loss = float(np.mean(np.logaddexp(0.0, z) - yc * z)) return data_loss + 0.5 * LAM * float(w @ D_reg @ w)
def logit_grad(w: np.ndarray) -> np.ndarray: p = sigmoid(Ac @ w) return (Ac.T @ (p - yc)) / len(yc) + LAM * (D_reg @ w)
def logit_hess(w: np.ndarray) -> np.ndarray: p = sigmoid(Ac @ w) weights = p * (1.0 - p) return (Ac.T * weights) @ Ac / len(yc) + LAM * D_reg
w_init = np.zeros(Ac.shape[1])H0 = logit_hess(w_init)eigs = np.linalg.eigvalsh(H0)print(f"Hessian eigenvalues min={eigs.min():.4f}, max={eigs.max():.4f}, " f"cond={eigs.max() / eigs.min():.2f}")print("strictly convex (all eigs > 0):", bool(np.all(eigs > 0)))Hessian eigenvalues min=0.1704, max=0.3319, cond=1.95strictly convex (all eigs > 0): TrueEvery eigenvalue of is strictly positive (and stays strictly positive for every finite because and has full column rank). The loss is strictly convex: there is exactly one global minimum.
Step 3 — Compare 6 steps of Newton’s method against 500 steps of GD
Section titled “Step 3 — Compare 6 steps of Newton’s method against 500 steps of GD”w_newton = np.zeros(Ac.shape[1])for step in range(1, 7): g = logit_grad(w_newton) H = logit_hess(w_newton) w_newton = w_newton - np.linalg.solve(H, g) print(f"Newton step {step}: loss={logit_loss(w_newton):.10f}, " f"||grad||={np.linalg.norm(logit_grad(w_newton)):.2e}")
w_gd = np.zeros(Ac.shape[1])for _ in range(500): w_gd = w_gd - 0.5 * logit_grad(w_gd)print(f"GD step 500: loss={logit_loss(w_gd):.10f}, " f"||grad||={np.linalg.norm(logit_grad(w_gd)):.2e}")print("max weight diff Newton vs GD:", f"{np.max(np.abs(w_newton - w_gd)):.2e}")Newton step 1: loss=0.4333317386, ||grad||=7.13e-02Newton step 2: loss=0.4073580216, ||grad||=1.91e-02Newton step 3: loss=0.4038317926, ||grad||=3.05e-03Newton step 4: loss=0.4037134336, ||grad||=1.19e-04Newton step 5: loss=0.4037132499, ||grad||=1.96e-07Newton step 6: loss=0.4037132499, ||grad||=5.28e-13GD step 500: loss=0.4037132501, ||grad||=2.94e-06max weight diff Newton vs GD: 6.27e-05Watch the gradient norm under Newton’s method: it plunges quadratically from down to in 6 iterations, reaching near double-precision accuracy — while 500 steps of batch gradient descent still have a gradient norm of !
Common mistakes:
- Inverting the Hessian (
np.linalg.inv(H) @ g) instead of solvingnp.linalg.solve(H, g). - Computing
-(y * np.log(p) + (1 - y) * np.log(1 - p))directly without clipping ornp.logaddexp(0, z), which overflows tonanwhen is large.
Example 3 — Integrate buyer revenue densities with quad and Monte Carlo
Section titled “Example 3 — Integrate buyer revenue densities with quad and Monte Carlo”Goal: Fit a log-normal density to converted buyer revenue in data/ab_test.csv, verify the Fundamental Theorem of Calculus , and compute expected revenue with both scipy.integrate.quad and Monte Carlo sampling.
Step 1 — Fit a log-normal distribution to buyer revenue
Section titled “Step 1 — Fit a log-normal distribution to buyer revenue”buyer_rev = ab_test.loc[ab_test["converted"] == 1, "revenue"].to_numpy(dtype=float)log_mu = float(np.mean(np.log(buyer_rev)))log_sigma = float(np.std(np.log(buyer_rev), ddof=1))dist = stats.lognorm(s=log_sigma, scale=np.exp(log_mu))print(f"buyers = {len(buyer_rev)}, log_mu = {log_mu:.4f}, log_sigma = {log_sigma:.4f}")buyers = 1089, log_mu = 3.5410, log_sigma = 0.6430In scipy.stats.lognorm, the shape parameter s is of and scale is .
Step 2 — Verify probability as area under the PDF
Section titled “Step 2 — Verify probability as area under the PDF”prob_quad, quad_err = integrate.quad(dist.pdf, 20.0, 60.0)prob_cdf = float(dist.cdf(60.0) - dist.cdf(20.0))prob_emp = float(np.mean((buyer_rev >= 20.0) & (buyer_rev <= 60.0)))print(f"P(20 <= R <= 60) quad = {prob_quad:.6f} (est err {quad_err:.1e})")print(f"P(20 <= R <= 60) F(60)-F(20) = {prob_cdf:.6f}")print(f"P(20 <= R <= 60) empirical = {prob_emp:.4f}")P(20 <= R <= 60) quad = 0.607048 (est err 7.8e-15)P(20 <= R <= 60) F(60)-F(20) = 0.607048P(20 <= R <= 60) empirical = 0.6107quad matches F(60) - F(20) to 6 decimals (in fact ~14 digits), and the empirical fraction of buyers spending between USD 20 and USD 60 agrees closely with the fitted log-normal model.
Step 3 — Compute expected revenue by integration vs. Monte Carlo vs. sample mean
Section titled “Step 3 — Compute expected revenue by integration vs. Monte Carlo vs. sample mean”exp_quad, _ = integrate.quad(lambda x: x * dist.pdf(x), 0.0, np.inf)exp_formula = float(np.exp(log_mu + 0.5 * log_sigma**2))mc_draws = dist.rvs(size=50_000, random_state=np.random.default_rng(42))exp_mc = float(np.mean(mc_draws))exp_mc_se = float(np.std(mc_draws, ddof=1) / np.sqrt(len(mc_draws)))print(f"E[R] quad = USD {exp_quad:.2f}")print(f"E[R] closed form = USD {exp_formula:.2f}")print(f"E[R] Monte Carlo = USD {exp_mc:.2f} (+/- {exp_mc_se:.2f})")print(f"E[R] sample mean = USD {buyer_rev.mean():.2f}")E[R] quad = USD 42.42E[R] closed form = USD 42.42E[R] Monte Carlo = USD 42.47 (+/- 0.14)E[R] sample mean = USD 42.36All four agree tightly around USD 42–43. When an integrand has no closed form (for example, expected profit under a capped discount or multi-dimensional Bayesian expectation), quad handles 1D integrals cleanly while Monte Carlo generalizes effortlessly to arbitrary dimensions.
Common mistakes:
- Forgetting
scale=np.exp(log_mu)inscipy.stats.lognorm(passingloc=log_mushifts the support instead of scaling it). - Integrating a non-negative density from
-np.infwhen the PDF is defined on — start at0.0so adaptive quadrature does not waste subdivisions on zeros.
Example 4 — Visualize Lagrange multipliers on Ridge vs. Lasso contours
Section titled “Example 4 — Visualize Lagrange multipliers on Ridge vs. Lasso contours”Goal: Fit a 2-feature house-price regression (sqft and distance_to_center_km predicting centered log(price)) on data/houses.csv, plot the elliptical MSE level curves alongside the L2 circle (Ridge) and L1 diamond (Lasso) constraints, and verify the Lagrange multiplier condition at the Ridge optimum.
Step 1 — Compute the unconstrained OLS weights and constrained solutions
Section titled “Step 1 — Compute the unconstrained OLS weights and constrained solutions”X2 = houses[["sqft", "distance_to_center_km"]].to_numpy(dtype=float)Z2 = (X2 - X2.mean(axis=0)) / X2.std(axis=0)y2 = np.log(houses["price"].to_numpy(dtype=float))y2 = y2 - y2.mean()
def mse2(w: np.ndarray) -> float: return float(np.mean((Z2 @ w - y2) ** 2))
def grad_mse2(w: np.ndarray) -> np.ndarray: return 2.0 * (Z2.T @ (Z2 @ w - y2)) / len(y2)
w_ols, *_ = np.linalg.lstsq(Z2, y2, rcond=None)# Constrain ||w||_2 <= 0.20 (Ridge) and ||w||_1 <= 0.20 (Lasso)budget = 0.20res_ridge = optimize.minimize( mse2, x0=np.zeros(2), jac=grad_mse2, constraints={"type": "ineq", "fun": lambda w: budget**2 - w @ w}, method="SLSQP",)w_ridge = res_ridge.x# L1 ball: minimize over w = u - v with u >= 0, v >= 0, sum(u + v) <= budgetres_lasso = optimize.minimize( lambda uv: mse2(uv[:2] - uv[2:]), x0=np.full(4, 0.05), bounds=[(0.0, None)] * 4, constraints={"type": "ineq", "fun": lambda uv: budget - np.sum(uv)}, method="SLSQP",)w_lasso = res_lasso.x[:2] - res_lasso.x[2:]print("w_ols :", w_ols)print("w_ridge:", w_ridge, f" (||w||_2 = {np.linalg.norm(w_ridge):.4f})")print("w_lasso:", w_lasso, f" (||w||_1 = {np.linalg.norm(w_lasso, 1):.4f})")w_ols : [ 0.3972 -0.1663]w_ridge: [ 0.1874 -0.07 ] (||w||_2 = 0.2000)w_lasso: [0.2 0. ] (||w||_1 = 0.2000)Look closely at w_lasso: because sqft lowers MSE much faster than distance_to_center_km, the expanding loss contour hits the corner of the L1 diamond on the -axis, driving all the way to 0.0000! Meanwhile w_ridge shrinks both weights smoothly while keeping both non-zero.
Step 2 — Verify gradient alignment at the Ridge optimum and plot the contours
Section titled “Step 2 — Verify gradient alignment at the Ridge optimum and plot the contours”g_loss = grad_mse2(w_ridge)g_cons = 2.0 * w_ridge # gradient of g(w) = w1^2 + w2^2cos_angle = float((g_loss @ g_cons) / (np.linalg.norm(g_loss) * np.linalg.norm(g_cons)))print(f"cos(angle between grad_loss and grad_constraint) = {cos_angle:.6f}")
w1_g = np.linspace(-0.35, 0.55, 160)w2_g = np.linspace(-0.40, 0.40, 160)W1, W2 = np.meshgrid(w1_g, w2_g)pred_grid = Z2[:, 0:1, None] * W1[None] + Z2[:, 1:2, None] * W2[None]L_grid = np.mean((pred_grid - y2[:, None, None]) ** 2, axis=0)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.5, 4.0), sharex=True, sharey=True)levels = np.linspace(mse2(w_ols) + 0.005, mse2(np.zeros(2)) + 0.04, 12)theta = np.linspace(0, 2 * np.pi, 200)
panels = [ (ax1, "Ridge (L2 ball)", w_ridge), (ax2, "Lasso (L1 diamond)", w_lasso),]for ax, title, w_c in panels: ax.contour(W1, W2, L_grid, levels=levels, cmap="viridis") ax.scatter([w_ols[0]], [w_ols[1]], color="black", label="OLS") ax.scatter([w_c[0]], [w_c[1]], color="tab:red", zorder=5, label="constrained opt") ax.axhline(0, color="gray", lw=0.6) ax.axvline(0, color="gray", lw=0.6) ax.set_title(title) ax.set_xlabel("w1 (sqft)") ax.set_aspect("equal") ax.legend(fontsize=8)
ax1.fill(budget * np.cos(theta), budget * np.sin(theta), alpha=0.2, color="tab:blue")ax1.plot(budget * np.cos(theta), budget * np.sin(theta), color="tab:blue")ax1.set_ylabel("w2 (distance)")diamond_x = [budget, 0, -budget, 0, budget]diamond_y = [0, budget, 0, -budget, 0]ax2.fill(diamond_x, diamond_y, alpha=0.2, color="tab:orange")ax2.plot(diamond_x, diamond_y, color="tab:orange")fig.tight_layout()plt.show()cos(angle between grad_loss and grad_constraint) = -1.000000
At the Ridge optimum, the cosine of the angle between and is -1.000000 — they point in exact opposite directions ( with ), confirming the KKT tangency condition.
Common mistakes:
- Penalizing the intercept alongside the slopes — centering (or excluding
w[0]from the penalty) ensures regularization shrinks feature effects rather than biasing the baseline prediction. - Trying to pass
np.abs(w).sum()directly to a smooth gradient solver like SLSQP without splitting (): the corners of are non-differentiable.
Example 5 — Compare GD, Momentum, Adam and L-BFGS on churn classification
Section titled “Example 5 — Compare GD, Momentum, Adam and L-BFGS on churn classification”Goal: Minimize the regularized churn logistic loss from Example 2 using four optimizers — vanilla GD, Momentum, Adam, and scipy.optimize.minimize(method="L-BFGS-B") — and plot their convergence gap on a log scale.
Step 1 — Implement Momentum and Adam alongside GD and L-BFGS
Section titled “Step 1 — Implement Momentum and Adam alongside GD and L-BFGS”def run_gd(lr: float, steps: int = 120) -> list[float]: w = np.zeros(Ac.shape[1]) hist = [] for _ in range(steps): hist.append(logit_loss(w)) w = w - lr * logit_grad(w) return hist
def run_momentum(lr: float, beta: float = 0.9, steps: int = 120) -> list[float]: w = np.zeros(Ac.shape[1]) v = np.zeros_like(w) hist = [] for _ in range(steps): hist.append(logit_loss(w)) v = beta * v + logit_grad(w) w = w - lr * v return hist
def run_adam( lr: float = 0.1, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8, steps: int = 120,) -> list[float]: w = np.zeros(Ac.shape[1]) m = np.zeros_like(w) v = np.zeros_like(w) hist = [] for t in range(1, steps + 1): hist.append(logit_loss(w)) g = logit_grad(w) m = beta1 * m + (1 - beta1) * g v = beta2 * v + (1 - beta2) * (g**2) m_hat = m / (1 - beta1**t) v_hat = v / (1 - beta2**t) w = w - lr * m_hat / (np.sqrt(v_hat) + eps) return hist
lbfgs_hist: list[float] = [logit_loss(np.zeros(Ac.shape[1]))]res_lbfgs = optimize.minimize( logit_loss, x0=np.zeros(Ac.shape[1]), jac=logit_grad, method="L-BFGS-B", callback=lambda wk: lbfgs_hist.append(logit_loss(wk)),)loss_star = logit_loss(w_newton)
h_gd = run_gd(lr=0.5)h_mom = run_momentum(lr=0.2, beta=0.9)h_adam = run_adam(lr=0.1)
for name, hist in [("GD (lr=0.5)", h_gd), ("Momentum", h_mom), ("Adam", h_adam), ("L-BFGS-B", lbfgs_hist)]: gap = max(hist[-1] - loss_star, 1e-16) print( f"{name:12} steps={len(hist) - 1:3d} " f"final_loss={hist[-1]:.8f} gap={gap:.2e}" )GD (lr=0.5) steps=119 final_loss=0.40388737 gap=1.74e-04Momentum steps=119 final_loss=0.40371379 gap=5.36e-07Adam steps=119 final_loss=0.40371346 gap=2.06e-07L-BFGS-B steps= 9 final_loss=0.40371325 gap=2.96e-11Step 2 — Plot the optimization gap on a log scale
Section titled “Step 2 — Plot the optimization gap on a log scale”fig, ax = plt.subplots(figsize=(6.8, 4.0))for label, hist in [ ("GD (lr=0.5)", h_gd), ("Momentum (lr=0.2, b=0.9)", h_mom), ("Adam (lr=0.1)", h_adam), ("L-BFGS-B", lbfgs_hist),]: gaps = np.maximum(np.array(hist) - loss_star, 1e-15) ax.plot(gaps, lw=2, label=label)ax.set_yscale("log")ax.set_xlabel("iteration")ax.set_ylabel("loss gap L(w_t) - L*")ax.set_title("Optimizer convergence on churn logistic regression")ax.legend()fig.tight_layout()plt.show()
L-BFGS reaches a gap of in just 9 iterations using only gradients (no explicit Hessian). Momentum and Adam reach to within 120 iterations, beating vanilla GD by nearly three orders of magnitude — and they scale cleanly to mini-batch deep learning where full-batch L-BFGS does not apply.
Common mistakes:
- Omitting the
jac=logit_gradargument inscipy.optimize.minimize: without it, SciPy estimates gradients numerically with extra loss evaluations per step. - Comparing Adam with a tiny default learning rate (
0.001) on a tiny convex full-batch problem without tuning — Adam’s step size is roughly bounded bylr, so full-batch linear models often toleratelr = 0.05to0.1.
Example 6 — Build a reverse-mode autograd Value class from scratch
Section titled “Example 6 — Build a reverse-mode autograd Value class from scratch”Goal: Implement a minimal reverse-mode automatic differentiation Value class (~45 lines) using topological sorting for .backward(), and verify every computed gradient against both central differences and torch.autograd.
Step 1 — Implement the scalar Value engine
Section titled “Step 1 — Implement the scalar Value engine”Each Value stores its scalar data, accumulated grad, parent nodes _prev, and a closure _backward that pushes its local chain-rule contribution into its parents.
class Value: """Minimal scalar reverse-mode autograd node."""
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 __pow__(self, power: float) -> "Value": out = Value(self.data**power, (self,))
def _backward() -> None: self.grad += (power * (self.data ** (power - 1))) * out.grad
out._backward = _backward return out
def tanh(self) -> "Value": t = float(np.tanh(self.data)) out = Value(t, (self,))
def _backward() -> None: self.grad += (1.0 - t**2) * out.grad
out._backward = _backward return out
def backward(self) -> None: topo: list[Value] = [] visited: set[Value] = 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()Step 2 — Run a neuron expression and verify against torch.autograd
Section titled “Step 2 — Run a neuron expression and verify against torch.autograd”Compute with a shared variable used twice () to test gradient accumulation across fan-out branches:
w1, w2, b = Value(0.6), Value(-1.2), Value(0.3)x1, x2, y_true = Value(1.5), Value(-0.5), Value(0.8)out = (w1 * x1 + w2 * x2 + b + (w1**2) * 0.25).tanh()loss_v = (out + y_true * (-1.0)) ** 2loss_v.backward()
tw1 = torch.tensor(0.6, dtype=torch.float64, requires_grad=True)tw2 = torch.tensor(-1.2, dtype=torch.float64, requires_grad=True)tb = torch.tensor(0.3, dtype=torch.float64, requires_grad=True)tout = torch.tanh(tw1 * 1.5 + tw2 * (-0.5) + tb + (tw1**2) * 0.25)tloss = (tout - 0.8) ** 2tloss.backward()
for name, v_node, t_node in [("w1", w1, tw1), ("w2", w2, tw2), ("b", b, tb)]: diff = abs(v_node.grad - float(t_node.grad)) print(f"{name}: Value.grad={v_node.grad:+.6f} " f"torch.grad={float(t_node.grad):+.6f} diff={diff:.1e}")w1: Value.grad=+0.048810 torch.grad=+0.048810 diff=2.1e-17w2: Value.grad=-0.013558 torch.grad=-0.013558 diff=6.9e-18b: Value.grad=+0.027116 torch.grad=+0.027116 diff=1.4e-17Every single gradient matches torch.autograd to 1e-16 — full 64-bit floating-point precision! That 45-line class is the conceptual heart of PyTorch.
Common mistakes:
- Writing
self.grad = ...instead ofself.grad += ...: whenever a variable is used in more than one place (w1 * x1andw1**2), overwriting drops all earlier branches. - Running
_backward()in arbitrary order instead of reverse topological order, which sends gradients to a node before all downstream consumers have finished contributing toout.grad.
Example 7 — Derive and verify the Softmax + Cross-Entropy gradient on reviews
Section titled “Example 7 — Derive and verify the Softmax + Cross-Entropy gradient on reviews”Goal: Build a 3-class sentiment classifier (negative, neutral, positive) on data/reviews.csv using aspect keyword features, derive the vectorized Softmax + Cross-Entropy gradient , and verify it against a numerical gradient to 1e-7.
Step 1 — Extract aspect counts and 3-class one-hot labels
Section titled “Step 1 — Extract aspect counts and 3-class one-hot labels”aspect_words = ["great", "quality", "broken", "refund", "slow", "recommend"]texts = reviews["text"].str.lower()X_rev = np.column_stack( [texts.str.count(w).to_numpy(dtype=float) for w in aspect_words])A_rev = np.column_stack([np.ones(len(X_rev)), X_rev])
classes = ["negative", "neutral", "positive"]y_idx = reviews["sentiment"].map({c: i for i, c in enumerate(classes)}).to_numpy()Y_oh = np.eye(len(classes))[y_idx]print("A_rev shape:", A_rev.shape, "Y_oh shape:", Y_oh.shape)print("class counts:", Y_oh.sum(axis=0).astype(int))A_rev shape: (3000, 7) Y_oh shape: (3000, 3)class counts: [ 596 338 2066]Step 2 — Implement numerically stable Softmax + Cross-Entropy and verify its gradient
Section titled “Step 2 — Implement numerically stable Softmax + Cross-Entropy and verify its gradient”For logits of shape :
where prevents np.exp overflow. Remarkably, the Jacobian of softmax and the gradient of cross-entropy cancel into the clean residual , mirroring binary logistic regression!
def softmax_rows(Z: np.ndarray) -> np.ndarray: shifted = Z - np.max(Z, axis=1, keepdims=True) exps = np.exp(shifted) return exps / exps.sum(axis=1, keepdims=True)
def ce_loss(W: np.ndarray) -> float: Z = A_rev @ W shifted = Z - np.max(Z, axis=1, keepdims=True) log_probs = shifted - np.log(np.sum(np.exp(shifted), axis=1, keepdims=True)) return float(-np.sum(Y_oh * log_probs) / len(A_rev))
def ce_grad(W: np.ndarray) -> np.ndarray: P = softmax_rows(A_rev @ W) return (A_rev.T @ (P - Y_oh)) / len(A_rev)
W0 = np.random.default_rng(7).normal(scale=0.2, size=(A_rev.shape[1], len(classes)))G_ana = ce_grad(W0)G_num = np.zeros_like(W0)h_step = 1e-6for i in range(W0.shape[0]): for j in range(W0.shape[1]): W_plus, W_minus = W0.copy(), W0.copy() W_plus[i, j] += h_step W_minus[i, j] -= h_step G_num[i, j] = (ce_loss(W_plus) - ce_loss(W_minus)) / (2 * h_step)
rel_err = np.linalg.norm(G_ana - G_num) / np.linalg.norm(G_ana + G_num)print(f"initial CE loss = {ce_loss(W0):.4f}, grad shape = {G_ana.shape}")print(f"relative gradient error = {rel_err:.2e}, passed (< 1e-7): {rel_err < 1e-7}")initial CE loss = 1.1710, grad shape = (7, 3)relative gradient error = 2.16e-10, passed (< 1e-7): TrueWith the gradient verified to 1e-10, you can pass ce_loss and ce_grad directly to scipy.optimize.minimize(..., method="L-BFGS-B") or plug it straight into a neural network’s output layer.
Common mistakes:
- Taking
np.log(softmax_rows(Z))instead of the log-sum-exp formshifted - log(sum(exp(shifted))): extreme logits underflowsoftmaxto0.0, producinglog(0) = -inf. - Forgetting
keepdims=Truewhen subtracting row maxes or dividing by row sums in 2D arrays, which broadcasts across the wrong axis.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Optimizing raw, unscaled features | Huge Hessian condition number; GD zig-zags or diverges | Standardize features on the training split before optimizing |
Computing np.exp(z) directly in softmax |
RuntimeWarning: overflow and nan probabilities |
Subtract np.max(z, axis=1, keepdims=True) before np.exp |
Overwriting .grad = ... in autodiff |
Shared variables lose gradients from earlier branches | Always accumulate with += and reset .grad = 0.0 before each pass |
| Assuming implies a minimum | Optimizer stalls at a saddle point or local maximum | Inspect Hessian eigenvalues (or add momentum / noise to escape saddles) |
Forming np.linalg.inv(H) @ g in Newton |
Amplified rounding error and wasted work | Solve np.linalg.solve(H, g) (or use L-BFGS when is large) |
| Using finite differences with | Catastrophic cancellation produces noisy garbage slopes | Use central differences with to for float64 |
| Passing non-smooth L1 directly to BFGS | Line search fails or stalls at zero kink | Use proximal gradient (ISTA), coordinate descent, or split |
Ignoring jac= in scipy.optimize.minimize |
Optimizer runs times slower and less accurately | Supply your verified analytic gradient function via jac= |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Robotics and aerospace control: Trajectory optimization minimizes fuel or energy subject to obstacle and dynamics constraints using L-BFGS, sequential quadratic programming, and Lagrange multipliers.
- Quantitative finance: Option pricing and risk metrics (Value-at-Risk, Greeks) rely on numerical quadrature, Monte Carlo integration in high dimensions, and automatic differentiation to compute sensitivities rapidly.
- Computer graphics and physics simulation: Differentiable rendering and inverse physics engines use reverse-mode autodiff to tune lighting, material, or spring parameters so simulated images match observations.
- Operations research and supply chains: Pricing, inventory allocation, and power-grid dispatch solve constrained convex optimization problems where Lagrange multipliers represent shadow prices — the marginal value of relaxing a resource constraint by one unit.
Summary
Section titled “Summary”- Limits, continuity, and differentiability separate smooth losses (MSE, Huber, log loss) from kinked functions (MAE, ReLU), which require subgradients at zero.
- The product, quotient, and chain rules differentiate every ML building block; Taylor polynomials turn smooth functions into local linear (GD) or quadratic (Newton) models.
- The Jacobian collects all first partial derivatives of a vector-valued function; the Hessian collects all second partial derivatives of a scalar loss and classifies stationary points through its eigenvalues.
- Definite integrals compute continuous probabilities and expectations (
scipy.integrate.quadin 1D; Monte Carlo integration in high dimensions). - Convex functions ( everywhere) guarantee that every local minimum is global; Lagrange multipliers equate and at constrained optima, explaining Ridge shrinkage vs. Lasso sparsity.
- Second-order methods (Newton, L-BFGS) converge rapidly on small/medium full-batch convex problems; Momentum, RMSProp, and Adam dominate noisy mini-batch deep learning.
- Reverse-mode automatic differentiation traverses the computation graph in reverse topological order to compute exact gradients for all parameters in a single backward pass.
Self-check questions
Section titled “Self-check questions”Q1. Why is Huber loss preferred over MAE when using second-order optimizers like L-BFGS, even though both resist outliers?
Answer
MAE has a sharp corner at residual where its derivative jumps discontinuously from to , breaking smoothness assumptions of quasi-Newton line searches. Huber loss replaces the corner inside with a smooth parabola while keeping linear tails (bounded derivative ) for outliers.
Q2. What does the quadratic Taylor term tell you that the linear term cannot, and how does Newton’s method use it?
Answer
The linear term only tells you the local slope (which direction is downhill). The quadratic term measures curvature, telling you how far to step before the slope levels off. Newton’s method minimizes the quadratic model directly by stepping .
Q3. For a neural network layer mapping 64 input features to 10 output units, what is the shape of its Jacobian matrix?
Answer
: one row per output component and one column per input component, with .
Q4. You find a point with and Hessian eigenvalues [3.2, 0.8, -0.4]. What kind of point is , and what happens if you move along the third eigenvector?
Answer
Because the Hessian has both positive and negative eigenvalues, is a saddle point. Moving along the eigenvector corresponding to decreases the loss immediately.
Q5. Why does adding a Ridge penalty with make even a collinear least-squares problem strictly convex?
Answer
The OLS Hessian is positive semidefinite (it can have eigenvalues when columns are collinear). Adding shifts every eigenvalue up by , making the Hessian strictly positive definite () everywhere and guaranteeing a unique global minimum.
Q6. When should you reach for Monte Carlo integration instead of scipy.integrate.quad?
Answer
Use quad for 1D (or 2D) smooth integrals where it delivers near-machine precision fast. Switch to Monte Carlo integration in higher dimensions (say ), where grid quadrature grows exponentially in while Monte Carlo error shrinks as independent of dimension.
Q7. Geometrically, why does Lasso () set weights to exact zero while Ridge () usually keeps them small and non-zero?
Answer
The L1 constraint region is a diamond/cross-polytope with sharp corners lying directly on the coordinate axes, so expanding elliptical loss contours frequently touch a corner first (where one or more coordinates equal zero). The L2 circle/sphere is smooth with no corners, so tangency almost always occurs off the axes.
Q8. Why does L-BFGS usually beat both vanilla GD and exact Newton’s method on a 5,000-feature logistic regression problem?
Answer
Vanilla GD uses no curvature information and takes many steps when features are correlated. Exact Newton’s method requires forming and solving a Hessian ( per step). L-BFGS approximates the inverse Hessian from the last ~10 gradient steps in time, getting fast quasi-Newton convergence at first-order cost.
Q9. Why do deep learning frameworks use reverse-mode automatic differentiation rather than forward-mode?
Answer
Training minimizes a single scalar loss () with respect to millions of parameters (). Forward-mode requires passes (one per parameter), whereas reverse-mode computes all gradients in just backward pass.
Q10. In a reverse-mode autograd engine, what breaks if you use self.grad = local * out.grad instead of +=, and why must you zero gradients before the next optimization step?
Answer
Using = overwrites gradients whenever a node feeds multiple downstream operations (fan-out), violating the multivariable chain rule that sums contributions across all paths. Conversely, because gradients accumulate with +=, forgetting to reset .grad = 0.0 before the next training step mixes stale gradients from previous iterations into the new update.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Practice every concept on 25 graded problems in 47. Calculus and optimization for ML — Exercises.
- Build a vectorized autograd engine and optimizer suite in 47. Calculus and optimization for ML — Mini-project.
- Keep the formulas and recipes handy in the 47. Calculus and optimization for ML — Cheat sheet.
- Continue to 48. Probability, Bayesian statistics and information theory.