Skip to content

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.

  • 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.quad and 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.

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 plt
import numpy as np
import pandas as pd
import torch
from 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)

A limit lim⁡x→af(x)=L\lim_{x \to a} f(x) = L is the value f(x)f(x) approaches as xx gets arbitrarily close to aa from both sides. A function is continuous at aa when the limit exists and equals f(a)f(a) — no jumps or holes. A function is differentiable at aa when the difference quotient has the same limit from the left and the right:

f′(a)=lim⁡h→0f(a+h)−f(a)hf'(a) = \lim_{h \to 0} \frac{f(a + h) - f(a)}{h}

Continuity is necessary for differentiability, but not sufficient. Two everyday ML building blocks are continuous everywhere yet have a sharp kink at 00:

  • ReLU, max⁡(0,z)\max(0, z), has left slope 00 and right slope 11 at z=0z = 0.
  • Absolute error (MAE / L1), ∣r∣\lvert r \rvert, has left slope −1-1 and right slope +1+1 at r=0r = 0.

At a kink, gradient-based methods pick any slope between the left and right derivatives — a subgradient (for example, 00 for both ReLU and ∣r∣\lvert r \rvert at 00). When you want a loss that resists outliers like MAE yet stays smoothly differentiable at 00 so second-order optimizers work cleanly, use the Huber loss, which stitches a quadratic bowl inside ∣r∣≤δ\lvert r \rvert \le \delta to linear tails outside:

Lδ(r)={12r2if ∣r∣≤δδ(∣r∣−12δ)if ∣r∣>δLδ′(r)={rif ∣r∣≤δδsign⁡(r)if ∣r∣>δL_\delta(r) = \begin{cases} \frac{1}{2} r^2 & \text{if } \lvert r \rvert \le \delta \\ \delta \left(\lvert r \rvert - \frac{1}{2}\delta\right) & \text{if } \lvert r \rvert > \delta \end{cases} \qquad L'_\delta(r) = \begin{cases} r & \text{if } \lvert r \rvert \le \delta \\ \delta \operatorname{sign}(r) & \text{if } \lvert r \rvert > \delta \end{cases}

Check the left and right slopes of ∣r∣\lvert r \rvert and Huber loss at r=0r = 0, 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-6
mae_left = (abs(0.0) - abs(-h)) / h
mae_right = (abs(h) - abs(0.0)) / h
hub_left = (float(huber(np.array(0.0))) - float(huber(np.array(-h)))) / h
hub_right = (float(huber(np.array(h))) - float(huber(np.array(0.0)))) / h
print(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}")
Output
MAE at 0: left slope = -1.0000, right slope = +1.0000
Huber at 0: left slope = -0.0000, right slope = +0.0000
r_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.
Huber loss removes the kink at zero while keeping bounded gradients for large outlier residuals.

Notice the derivative panel: MSE’s gradient grows without bound for outliers, MAE’s gradient jumps abruptly from −1-1 to +1+1 at 00, and Huber’s gradient is continuous everywhere and clipped to [−δ,+δ][-\delta, +\delta].

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: (f⋅g)′=f′g+fg′(f \cdot g)' = f' g + f g'.
  • The quotient rule differentiates a ratio: (fg)′=f′g−fg′g2\left(\frac{f}{g}\right)' = \frac{f' g - f g'}{g^2} whenever g(x)≠0g(x) \ne 0.
Rule Formula ML appearance
Product (fg)′=f′g+fg′(f g)' = f' g + f g' expected value derivatives, entropy −plog⁡p-p \log p
Quotient (f/g)′=(f′g−fg′)/g2(f / g)' = (f' g - f g') / g^2 sigmoid 11+e−z\frac{1}{1+e^{-z}}, softmax ratios, F1 score
Chain (f(g(x)))′=f′(g(x)) g′(x)(f(g(x)))' = f'(g(x)) \, g'(x) backpropagation through every network layer
Inverse / log (log⁡f(x))′=f′(x)/f(x)(\log f(x))' = f'(x) / f(x) log-likelihoods, softplus log⁡(1+ez)\log(1 + e^z)

Derive the sigmoid derivative with the quotient rule on σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}} (f=1f = 1, f′=0f' = 0, g=1+e−zg = 1 + e^{-z}, g′=−e−zg' = -e^{-z}):

σ′(z)=0⋅(1+e−z)−1⋅(−e−z)(1+e−z)2=11+e−z⋅e−z1+e−z=σ(z)(1−σ(z))\sigma'(z) = \frac{0 \cdot (1 + e^{-z}) - 1 \cdot (-e^{-z})}{(1 + e^{-z})^2} = \frac{1}{1 + e^{-z}} \cdot \frac{e^{-z}}{1 + e^{-z}} = \sigma(z)\big(1 - \sigma(z)\big)

Verify the product rule on binary entropy h(p)=−plog⁡ph(p) = -p \log p, the quotient rule on σ(z)\sigma(z), and the chain rule on softplus s(z)=log⁡(1+ez)s(z) = \log(1 + e^z) (whose derivative is σ(z)\sigma(z)!):

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}")
Output
product -p*log(p) at 0.3 num=+0.203973 ana=+0.203973 err=1.5e-11
quotient sigmoid(z) at 0.8 num=+0.213910 ana=+0.213910 err=8.8e-12
chain softplus(z) at 0.8 num=+0.689974 ana=+0.689974 err=8.8e-11

Every analytic rule agrees with central differences to at least 9 significant digits. Notice that the derivative of softplus log⁡(1+ez)\log(1 + e^z) 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 f′′(x)=d2fdx2f''(x) = \frac{d^2 f}{dx^2} is the derivative of the derivative: it measures curvature, or how fast the slope is changing.

  • f′′(x)>0f''(x) > 0: the curve bends upward (convex / concave up, like a cup). A stationary point (f′(x)=0f'(x) = 0) with f′′(x)>0f''(x) > 0 is a local minimum.
  • f′′(x)<0f''(x) < 0: the curve bends downward (concave down, like a cap). A stationary point with f′′(x)<0f''(x) < 0 is a local maximum.
  • f′′(x)=0f''(x) = 0: inconclusive — it may be an inflection point (such as f(x)=x3f(x) = x^3 at x=0x = 0, which is flat at 00 but neither a minimum nor a maximum).

Near a point aa, you can approximate any smooth function by its Taylor polynomial of degree kk, matching its value and first kk derivatives at aa:

Tk(x)=f(a)+f′(a)(x−a)+f′′(a)2!(x−a)2+⋯+f(k)(a)k!(x−a)kT_k(x) = f(a) + f'(a)(x - a) + \frac{f''(a)}{2!}(x - a)^2 + \dots + \frac{f^{(k)}(a)}{k!}(x - a)^k

Optimization uses the first-order and second-order Taylor models everywhere:

  • Gradient descent replaces the loss locally with the linear model f(w0)+f′(w0)Δwf(w_0) + f'(w_0)\Delta w plus a step-size penalty.
  • Newton’s method replaces the loss locally with the quadratic model f(w0)+f′(w0)Δw+12f′′(w0)Δw2f(w_0) + f'(w_0)\Delta w + \frac{1}{2} f''(w_0)\Delta w^2 and jumps straight to the bottom of that parabola: Δw=−f′(w0)/f′′(w0)\Delta w = -f'(w_0) / f''(w_0).

Check the curvature of f(w)=ew−2wf(w) = e^w - 2w at its stationary point w∗=log⁡2w^* = \log 2:

w_star = float(np.log(2.0))
f_prime = np.exp(w_star) - 2.0
f_second = np.exp(w_star)
print(
f"w* = {w_star:.4f}, f'(w*) = {f_prime:.1e}, "
f"f''(w*) = {f_second:.4f} > 0 (minimum)"
)
Output
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 f(w)f(\mathbf{w}) takes pp inputs, the gradient ∇f(w)∈Rp\nabla f(\mathbf{w}) \in \mathbb{R}^p collects all partial derivatives. How fast does ff change if you move in an arbitrary unit direction u\mathbf{u} (∥u∥2=1\lVert \mathbf{u} \rVert_2 = 1)? That rate is the directional derivative:

Duf(w)=∇f(w)⋅u=∥∇f(w)∥2cos⁡θD_{\mathbf{u}} f(\mathbf{w}) = \nabla f(\mathbf{w}) \cdot \mathbf{u} = \lVert \nabla f(\mathbf{w}) \rVert_2 \cos\theta

Two geometric facts fall right out of that dot product:

  1. Steepest ascent and descent: cos⁡θ\cos\theta is maximized at +1+1 (along +∇f+\nabla f) and minimized at −1-1 (along −∇f-\nabla f).
  2. Perpendicular to level curves: along a level curve (contour of constant loss, f(w)=cf(\mathbf{w}) = c), the value does not change, so Duf=0D_{\mathbf{u}} f = 0. Therefore ∇f\nabla f is always perpendicular to the contour lines!

Now suppose a function maps a vector to a vector: g:Rp→Rm\mathbf{g} : \mathbb{R}^p \to \mathbb{R}^m (for example, a softmax layer mapping pp logits to m=pm = p probabilities, or a linear layer mapping inputs to hidden units). Its derivative is no longer a single vector — it is the m×pm \times p Jacobian matrix JJ, where row ii is the gradient of output component gig_i:

Jij=∂gi∂xjJ_{ij} = \frac{\partial g_i}{\partial x_j}

For the softmax function pi=ezi∑kezkp_i = \frac{e^{z_i}}{\sum_k e^{z_k}}, applying the quotient rule gives a compact Jacobian:

∂pi∂zj=pi(δij−pj)⟺Jsoftmax(z)=diag⁡(p)−pp⊤\frac{\partial p_i}{\partial z_j} = p_i (\delta_{ij} - p_j) \qquad \Longleftrightarrow \qquad J_{\text{softmax}}(\mathbf{z}) = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top

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}")
Output
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-11

Look at the entries: diagonal terms are positive (raising logit ii raises pip_i), off-diagonal terms are negative (raising logit jj steals probability mass from pip_i), and every row sums to 00 because the probabilities always sum to 11.

The Hessian matrix: curvature, saddle points and positive definiteness

Section titled “The Hessian matrix: curvature, saddle points and positive definiteness”

The multivariable analogue of f′′(x)f''(x) is the p×pp \times p Hessian matrix H(w)H(\mathbf{w}) of all second partial derivatives:

Hjk(w)=∂2f∂wj ∂wkH_{jk}(\mathbf{w}) = \frac{\partial^2 f}{\partial w_j \, \partial w_k}

For smooth functions, the order of differentiation does not matter (Hjk=HkjH_{jk} = H_{kj}), so the Hessian is always symmetric. By the spectral theorem (Module 46), a symmetric matrix has real eigenvalues λ1,…,λp\lambda_1, \dots, \lambda_p pointing along orthogonal principal curvature directions. At a stationary point where ∇f(w∗)=0\nabla f(\mathbf{w}^*) = \mathbf{0}, the signs of the eigenvalues classify the point completely:

Eigenvalues of H(w∗)H(\mathbf{w}^*) Matrix property Type of stationary point
All λi>0\lambda_i > 0 Positive definite (H≻0H \succ 0) Strict local minimum (bowl curving up in every direction)
All λi<0\lambda_i < 0 Negative definite (H≺0H \prec 0) Strict local maximum (cap curving down in every direction)
Some λi>0\lambda_i > 0 and some λj<0\lambda_j < 0 Indefinite Saddle point (curves up in some directions, down in others)
All λi≥0\lambda_i \ge 0, some λi=0\lambda_i = 0 Positive semidefinite (H⪰0H \succeq 0) 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 κ(H)=λmax⁡/λmin⁡\kappa(H) = \lambda_{\max} / \lambda_{\min} is the condition number of the curvature. When κ(H)\kappa(H) is huge, contours are narrow ellipses: a learning rate small enough not to blow up along the steep axis (λmax⁡\lambda_{\max}) crawls painfully slowly along the flat axis (λmin⁡\lambda_{\min}).

Classify three 2D quadratic surfaces at the origin (0,0)(0, 0) 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}")
Output
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)

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 f(w)f(\mathbf{w}) or f(W)f(W) Gradient ∇f\nabla f Hessian HH
a⊤w\mathbf{a}^\top \mathbf{w} a\mathbf{a} 00
w⊤Aw\mathbf{w}^\top A \mathbf{w} (symmetric AA) 2Aw2 A \mathbf{w} 2A2 A
1n∥Xw−y∥22\frac{1}{n}\lVert X\mathbf{w} - \mathbf{y} \rVert_2^2 (MSE) 2nX⊤(Xw−y)\frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y}) 2nX⊤X\frac{2}{n} X^\top X
1n∥Xw−y∥22+λ∥w∥22\frac{1}{n}\lVert X\mathbf{w} - \mathbf{y} \rVert_2^2 + \lambda \lVert \mathbf{w} \rVert_2^2 (Ridge) 2nX⊤(Xw−y)+2λw\frac{2}{n} X^\top(X\mathbf{w} - \mathbf{y}) + 2\lambda \mathbf{w} 2nX⊤X+2λI\frac{2}{n} X^\top X + 2\lambda I
Binary log loss, p=σ(Xw)p = \sigma(X\mathbf{w}) 1nX⊤(p−y)\frac{1}{n} X^\top (\mathbf{p} - \mathbf{y}) 1nX⊤diag⁡(p(1−p))X\frac{1}{n} X^\top \operatorname{diag}\big(\mathbf{p}(1-\mathbf{p})\big) X
Softmax + cross-entropy, P=softmax⁡(XW)P = \operatorname{softmax}(XW) 1nX⊤(P−Y)\frac{1}{n} X^\top (P - Y) block-structured PSD

Verify the quadratic form identity ∇(w⊤Aw)=2Aw\nabla (\mathbf{w}^\top A \mathbf{w}) = 2 A \mathbf{w} for a symmetric matrix AA:

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_test
g_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))
Output
analytic : [ 2.7204 -1.4349 2.0594]
numerical: [ 2.7204 -1.4349 2.0594]
match : True

Differentiation breaks change into infinitesimal slopes; integration puts infinitesimal pieces back together. A definite integral ∫abf(x) dx\int_a^b f(x)\,dx is the signed area under f(x)f(x) from aa to bb. By the Fundamental Theorem of Calculus, if F′(x)=f(x)F'(x) = f(x), then:

∫abf(x) dx=F(b)−F(a)\int_a^b f(x)\,dx = F(b) - F(a)

In probability and ML, integration turns continuous probability densities into probabilities and expectations:

  • Probability from a PDF: P(a≤X≤b)=∫abf(x) dx=F(b)−F(a)P(a \le X \le b) = \int_a^b f(x)\,dx = F(b) - F(a), where FF is the CDF.
  • Continuous expectation: E[g(X)]=∫−∞∞g(x) f(x) dx\mathbb{E}[g(X)] = \int_{-\infty}^{\infty} g(x)\,f(x)\,dx.
  • Marginalizing a latent variable (Bayesian posteriors, variational inference): p(y)=∫p(y∣θ)p(θ) dθp(y) = \int p(y \mid \theta) p(\theta)\,d\theta.

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 NN i.i.d. samples X1,…,XN∼fX_1, \dots, X_N \sim f and average g(Xi)g(X_i):

E[g(X)]=∫g(x) f(x) dx≈1N∑i=1Ng(Xi)\mathbb{E}[g(X)] = \int g(x)\,f(x)\,dx \approx \frac{1}{N} \sum_{i=1}^{N} g(X_i)

Monte Carlo’s standard error shrinks as O(1/N)O(1/\sqrt{N}) regardless of dimension! Check both on the standard normal PDF for P(−1≤Z≤1)P(-1 \le Z \le 1) and E[Z2]=1\mathbb{E}[Z^2] = 1:

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}")
Output
P(-1 <= Z <= 1): quad=0.682689 (err 7.6e-15), CDF diff=0.682689
E[Z^2]: quad=1.000000, Monte Carlo (N=50k)=1.0056

A function ff is a convex function if the line segment joining any two points on its graph lies on or above the curve (Jensen’s inequality):

f(tu+(1−t)v)≤tf(u)+(1−t)f(v)for all u,v and t∈[0,1]f\big(t\mathbf{u} + (1 - t)\mathbf{v}\big) \le t f(\mathbf{u}) + (1 - t) f(\mathbf{v}) \qquad \text{for all } \mathbf{u}, \mathbf{v} \text{ and } t \in [0, 1]

For twice-differentiable functions, convexity has a direct curvature test: ff is convex if and only if its Hessian H(w)H(\mathbf{w}) is positive semidefinite (H(w)⪰0H(\mathbf{w}) \succeq 0, all eigenvalues ≥0\ge 0) everywhere. If H(w)≻0H(\mathbf{w}) \succ 0 everywhere, ff is strictly convex.

Why does convexity matter so much in ML?

  • Every local minimum of a convex function is a global minimum. If ff is strictly convex, the global minimum is unique — your starting point does not matter!
  • Linear regression (H=2nX⊤X⪰0H = \frac{2}{n} X^\top X \succeq 0), Ridge regression (H=2nX⊤X+2λI≻0H = \frac{2}{n} X^\top X + 2\lambda I \succ 0), logistic regression (H=1nX⊤diag⁡(p(1−p))X⪰0H = \frac{1}{n} X^\top \operatorname{diag}(p(1-p)) X \succeq 0), 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 −log⁡(σ(z))-\log(\sigma(z)) versus a non-convex wavy loss z2+3sin⁡(2z)z^2 + 3\sin(2z):

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.5
mid = t * u + (1 - t) * v
print(
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)}"
)
Output
convex f(mid)=0.4741 <= chord=0.7201: True
nonconvex f(mid)=0.8665 <= chord=-0.5830: False

Constrained optimization and Lagrange multipliers

Section titled “Constrained optimization and Lagrange multipliers”

Many ML problems minimize a loss f(w)f(\mathbf{w}) subject to a budget or geometric constraint g(w)=cg(\mathbf{w}) = c:

  • Ridge regression: minimize MSE subject to ∥w∥22≤t\lVert \mathbf{w} \rVert_2^2 \le t (a circle/sphere).
  • Lasso regression: minimize MSE subject to ∥w∥1≤t\lVert \mathbf{w} \rVert_1 \le t (a diamond/cross-polytope).
  • PCA (Module 46): maximize variance v⊤Σv\mathbf{v}^\top \Sigma \mathbf{v} subject to ∥v∥22=1\lVert \mathbf{v} \rVert_2^2 = 1.
  • Support Vector Machines: minimize 12∥w∥22\frac{1}{2}\lVert \mathbf{w} \rVert_2^2 subject to margin inequalities yi(w⊤xi+b)≥1y_i(\mathbf{w}^\top \mathbf{x}_i + b) \ge 1.

At a constrained optimum on the boundary g(w)=cg(\mathbf{w}) = c, the level curve of ff must be tangent to the constraint surface g(w)=cg(\mathbf{w}) = c. (If the two curves crossed, you could slide along the constraint to lower ff further!) Since gradients are perpendicular to level curves, tangency means the two gradients are parallel:

∇f(w)=λ ∇g(w)or equivalently∇wL(w,λ)=0\nabla f(\mathbf{w}) = \lambda \, \nabla g(\mathbf{w}) \qquad \text{or equivalently} \qquad \nabla_{\mathbf{w}} \mathcal{L}(\mathbf{w}, \lambda) = \mathbf{0}

where L(w,λ)=f(w)+λ(g(w)−c)\mathcal{L}(\mathbf{w}, \lambda) = f(\mathbf{w}) + \lambda\big(g(\mathbf{w}) - c\big) is the Lagrangian and λ\lambda is the Lagrange multiplier. For inequality constraints g(w)≤cg(\mathbf{w}) \le c, the Karush–Kuhn–Tucker (KKT) conditions generalize this rule: either the constraint is inactive (λ=0\lambda = 0, unconstrained minimum lies inside the budget) or active (λ>0\lambda > 0, optimum sits on the boundary with parallel gradients).

This single equation explains why the penalized form L(w)+λ∥w∥22L(\mathbf{w}) + \lambda \lVert \mathbf{w} \rVert_2^2 used in scikit-learn is mathematically equivalent to solving MSE inside a ball ∥w∥22≤t\lVert \mathbf{w} \rVert_2^2 \le t! Check the gradient alignment on a concrete 2D example — minimizing (w1−3)2+(w2−2)2(w_1 - 3)^2 + (w_2 - 2)^2 on the unit circle w12+w22=1w_1^2 + w_2^2 = 1:

target = np.array([3.0, 2.0])
w_opt = target / np.linalg.norm(target) # closest point on the unit circle
grad_f = 2 * (w_opt - target)
grad_g = 2 * w_opt
lam = -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}")
Output
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-16

The residual is zero to machine precision: ∇f\nabla f and ∇g\nabla g 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 wt+1=wt−η∇L(wt)\mathbf{w}_{t+1} = \mathbf{w}_t - \eta \nabla L(\mathbf{w}_t) treats every coordinate with the same fixed step size and ignores both past momentum and local curvature. Modern ML uses two families of upgrades:

  1. 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: wt+1=wt−H(wt)−1∇L(wt)\mathbf{w}_{t+1} = \mathbf{w}_t - H(\mathbf{w}_t)^{-1} \nabla L(\mathbf{w}_t) In code, solve HΔw=−∇LH \Delta \mathbf{w} = -\nabla L with np.linalg.solve (never invert HH). Near a strictly convex minimum, Newton converges quadratically (the number of accurate digits roughly doubles every step!), but building and solving a p×pp \times p Hessian costs O(p3)O(p^3) per step.
    • L-BFGS (Limited-memory Broyden–Fletcher–Goldfarb–Shanno, scipy.optimize.minimize(..., method="L-BFGS-B")) approximates the inverse Hessian from the last m≈10m \approx 10 gradient differences in O(mp)O(mp) time and memory. It is the default solver inside scikit-learn’s LogisticRegression.
  2. 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 vt=βvt−1+∇L\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla L), 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 (st=ρst−1+(1−ρ)(∇L)2\mathbf{s}_t = \rho \mathbf{s}_{t-1} + (1 - \rho)(\nabla L)^2), giving each coordinate its own adaptive step size.
    • Adam combines Momentum (mt\mathbf{m}_t, β1=0.9\beta_1 = 0.9) and RMSProp (vt\mathbf{v}_t, β2=0.999\beta_2 = 0.999) with bias corrections m^t=mt/(1−β1t)\hat{\mathbf{m}}_t = \mathbf{m}_t / (1 - \beta_1^t) and v^t=vt/(1−β2t)\hat{\mathbf{v}}_t = \mathbf{v}_t / (1 - \beta_2^t): wt+1=wt−ηm^tv^t+ϵ\mathbf{w}_{t+1} = \mathbf{w}_t - \eta \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}
Optimizer Order / Memory Cost per step Best suited for
Vanilla GD / SGD 1st / O(p)O(p) O(np)O(np) teaching, well-conditioned linear models
Momentum 1st / O(p)O(p) O(np)O(np) CNNs, narrow valleys with tuned η\eta
RMSProp 1st / O(p)O(p) O(np)O(np) noisy/non-stationary objectives, RNNs
Adam 1st / O(p)O(p) O(np)O(np) default for deep nets and mini-batches
L-BFGS quasi-2nd / O(mp)O(mp) O(np+mp)O(np + mp) full-batch convex models (p≤105p \le 10^5), LogisticRegression
Newton 2nd / O(p2)O(p^2) O(np2+p3)O(np^2 + p^3) low-dimensional (p≤103p \le 10^3) 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 2p2p 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 ∂node∂xj\frac{\partial \text{node}}{\partial x_j} from one input xjx_j forward to all outputs using dual numbers. Cost: O(p)O(p) passes for pp inputs and mm outputs (great when p≪mp \ll m).
  • Reverse-mode automatic differentiation (backpropagation) runs one forward pass to record values, then walks the graph in reverse topological order (Module 45) propagating ∂L∂node\frac{\partial L}{\partial \text{node}} backward from the scalar loss to every parameter in one sweep! Cost: O(m)O(m) passes — just one backward pass when the loss is a scalar (m=1m = 1), whether p=10p = 10 or p=108p = 10^8.

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.

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 exe^x, log⁡(1+x)\log(1 + x), and σ(x)\sigma(x) around a=0a = 0 with 1st-, 2nd-, and 3rd-order Taylor polynomials, measure their worst-case errors on [−0.5,0.5][-0.5, 0.5], 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 a=0a = 0:

  • ex≈1+x+x22+x36e^x \approx 1 + x + \frac{x^2}{2} + \frac{x^3}{6}
  • log⁡(1+x)≈x−x22+x33\log(1 + x) \approx x - \frac{x^2}{2} + \frac{x^3}{3}
  • σ(x)≈12+x4+0⋅x2−x348\sigma(x) \approx \frac{1}{2} + \frac{x}{4} + 0 \cdot x^2 - \frac{x^3}{48} (the quadratic term vanishes because σ′′(0)=0\sigma''(0) = 0: the sigmoid has an inflection point at 00!)
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}")
Output
exp(x) max |err| on [-0.5, 0.5]: T1=0.14872 T2=0.02372 T3=0.00289
log(1+x) max |err| on [-0.5, 0.5]: T1=0.19315 T2=0.06815 T3=0.02648
sigmoid(x) max |err| on [-0.5, 0.5]: T1=0.00254 T2=0.00254 T3=0.00006

Each extra order cuts the worst-case error sharply on [−0.5,0.5][-0.5, 0.5] — for sigmoid(x), T1T_1 and T2T_2 are identical because σ′′(0)=0\sigma''(0) = 0, 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()
Three panels comparing exact curves in solid black against first-, second-, and third-order Taylor polynomials around zero for exp(x), log(1 + x), and sigmoid(x). All polynomials touch the exact curve at x = 0 and match closely near zero, while higher orders stay accurate farther out before diverging.
Taylor polynomials are local approximations: accurate near the expansion point, diverging outside their radius of trust.

Every polynomial is exact at x=0x = 0, and T3T_3 tracks all three curves closely across [−1,1][-1, 1] before peeling away. Notice why log⁡(1+x)\log(1 + x) diverges sharply beyond x=1x = 1: its Taylor series only converges for ∣x∣<1\lvert x \rvert < 1.

Common mistakes:

  • Using a Taylor polynomial far from its expansion point aa — local models are only trustworthy inside a small trust region around aa.
  • Dropping the factorial denominator k!k! (writing x3x^3 instead of x3/6x^3 / 6 in exe^x).

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))
Output
design matrix shape: (5000, 7) positive rate: 0.1926

Adding 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 λ2∥w1:∥22\frac{\lambda}{2} \lVert \mathbf{w}_{1:} \rVert_2^2 (leaving the intercept unpenalized):

∇L(w)=1nA⊤(p−y)+λDwH(w)=1nA⊤diag⁡(p(1−p))A+λD\nabla L(\mathbf{w}) = \frac{1}{n} A^\top (\mathbf{p} - \mathbf{y}) + \lambda D \mathbf{w} \qquad H(\mathbf{w}) = \frac{1}{n} A^\top \operatorname{diag}\big(\mathbf{p}(1 - \mathbf{p})\big) A + \lambda D

where D=diag⁡(0,1,…,1)D = \operatorname{diag}(0, 1, \dots, 1).

LAM = 1e-3
D_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)))
Output
Hessian eigenvalues min=0.1704, max=0.3319, cond=1.95
strictly convex (all eigs > 0): True

Every eigenvalue of H(0)H(\mathbf{0}) is strictly positive (and stays strictly positive for every finite w\mathbf{w} because p(1−p)>0p(1-p) > 0 and AA 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}")
Output
Newton step 1: loss=0.4333317386, ||grad||=7.13e-02
Newton step 2: loss=0.4073580216, ||grad||=1.91e-02
Newton step 3: loss=0.4038317926, ||grad||=3.05e-03
Newton step 4: loss=0.4037134336, ||grad||=1.19e-04
Newton step 5: loss=0.4037132499, ||grad||=1.96e-07
Newton step 6: loss=0.4037132499, ||grad||=5.28e-13
GD step 500: loss=0.4037132501, ||grad||=2.94e-06
max weight diff Newton vs GD: 6.27e-05

Watch the gradient norm under Newton’s method: it plunges quadratically from 7×10−27 \times 10^{-2} down to 5×10−135 \times 10^{-13} in 6 iterations, reaching near double-precision accuracy — while 500 steps of batch gradient descent still have a gradient norm of 2.9×10−62.9 \times 10^{-6}!

Common mistakes:

  • Inverting the Hessian (np.linalg.inv(H) @ g) instead of solving np.linalg.solve(H, g).
  • Computing -(y * np.log(p) + (1 - y) * np.log(1 - p)) directly without clipping or np.logaddexp(0, z), which overflows to nan when zz 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 ∫2060f(x) dx=F(60)−F(20)\int_{20}^{60} f(x)\,dx = F(60) - F(20), and compute expected revenue E[R]=∫0∞xf(x) dx\mathbb{E}[R] = \int_0^\infty x f(x)\,dx 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}")
Output
buyers = 1089, log_mu = 3.5410, log_sigma = 0.6430

In scipy.stats.lognorm, the shape parameter s is σ\sigma of log⁡R\log R and scale is eμe^\mu.

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}")
Output
P(20 <= R <= 60) quad = 0.607048 (est err 7.8e-15)
P(20 <= R <= 60) F(60)-F(20) = 0.607048
P(20 <= R <= 60) empirical = 0.6107

quad 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}")
Output
E[R] quad = USD 42.42
E[R] closed form = USD 42.42
E[R] Monte Carlo = USD 42.47 (+/- 0.14)
E[R] sample mean = USD 42.36

All 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) in scipy.stats.lognorm (passing loc=log_mu shifts the support instead of scaling it).
  • Integrating a non-negative density from -np.inf when the PDF is defined on [0,∞)[0, \infty) — start at 0.0 so 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 ∇L∥∇g\nabla L \parallel \nabla g 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.20
res_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) <= budget
res_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})")
Output
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 w1w_1-axis, driving w2w_2 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^2
cos_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()
Output
cos(angle between grad_loss and grad_constraint) = -1.000000
Two contour plots of house-price MSE over weights w1 (sqft) and w2 (distance). Left: the elliptical contours expand from the OLS point until they touch the blue circular L2 Ridge region smoothly where both weights remain non-zero. Right: the same contours first touch the orange diamond-shaped L1 Lasso region right at its corner on the w1 axis, setting w2 to zero.
Geometry of Lagrange multipliers: the smooth L2 circle shrinks both weights, whereas the pointy corners of the L1 diamond produce exact zeros.

At the Ridge optimum, the cosine of the angle between ∇L\nabla L and ∇g\nabla g is -1.000000 — they point in exact opposite directions (∇L=−λ∇g\nabla L = -\lambda \nabla g with λ>0\lambda > 0), confirming the KKT tangency condition.

Common mistakes:

  • Penalizing the intercept bb alongside the slopes — centering yy (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 w=u−vw = u - v (u,v≥0u, v \ge 0): the corners of ∣w∣\lvert w \rvert 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 L(wt)−L∗L(\mathbf{w}_t) - L^* 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}"
)
Output
GD (lr=0.5) steps=119 final_loss=0.40388737 gap=1.74e-04
Momentum steps=119 final_loss=0.40371379 gap=5.36e-07
Adam steps=119 final_loss=0.40371346 gap=2.06e-07
L-BFGS-B steps= 9 final_loss=0.40371325 gap=2.96e-11

Step 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()
Log-scale convergence plot of loss gap L(w_t) - L* versus iteration for four optimizers on churn logistic regression. L-BFGS-B drops sharply to 3e-11 in 9 iterations, Momentum and Adam reach around 2e-7 to 5e-7 within 120 iterations, and vanilla GD descends steadily to 1.7e-4.
On full-batch smooth convex problems, quasi-Newton L-BFGS converges an order of magnitude faster than first-order methods.

L-BFGS reaches a gap of 3×10−113 \times 10^{-11} in just 9 iterations using only gradients (no explicit Hessian). Momentum and Adam reach 2×10−72 \times 10^{-7} to 5×10−75 \times 10^{-7} 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_grad argument in scipy.optimize.minimize: without it, SciPy estimates gradients numerically with pp 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 by lr, so full-batch linear models often tolerate lr = 0.05 to 0.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 L=(tanh⁡(w1x1+w2x2+b)−y)2L = (\tanh(w_1 x_1 + w_2 x_2 + b) - y)^2 with a shared variable w1w_1 used twice (w1x1+w12w_1 x_1 + w_1^2) 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)) ** 2
loss_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) ** 2
tloss.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}")
Output
w1: Value.grad=+0.048810 torch.grad=+0.048810 diff=2.1e-17
w2: Value.grad=-0.013558 torch.grad=-0.013558 diff=6.9e-18
b: Value.grad=+0.027116 torch.grad=+0.027116 diff=1.4e-17

Every 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 of self.grad += ...: whenever a variable is used in more than one place (w1 * x1 and w1**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 to out.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 ∇WL=1nA⊤(P−Y)\nabla_W L = \frac{1}{n} A^\top (P - Y), 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))
Output
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 Z=AWZ = A W of shape (n,K)(n, K):

Pik=eZik−mi∑ceZic−mi,L(W)=−1n∑i=1n∑k=1KYiklog⁡Pik,∇WL=1nA⊤(P−Y)P_{ik} = \frac{e^{Z_{ik} - m_i}}{\sum_c e^{Z_{ic} - m_i}}, \qquad L(W) = -\frac{1}{n} \sum_{i=1}^{n} \sum_{k=1}^{K} Y_{ik} \log P_{ik}, \qquad \nabla_W L = \frac{1}{n} A^\top (P - Y)

where mi=max⁡cZicm_i = \max_c Z_{ic} prevents np.exp overflow. Remarkably, the Jacobian of softmax and the gradient of cross-entropy cancel into the clean residual P−YP - Y, 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-6
for 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}")
Output
initial CE loss = 1.1710, grad shape = (7, 3)
relative gradient error = 2.16e-10, passed (< 1e-7): True

With 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 form shifted - log(sum(exp(shifted))): extreme logits underflow softmax to 0.0, producing log(0) = -inf.
  • Forgetting keepdims=True when subtracting row maxes or dividing by row sums in 2D arrays, which broadcasts across the wrong axis.
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 ∇f=0\nabla f = \mathbf{0} 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 pp is large)
Using finite differences with h=10−14h = 10^{-14} Catastrophic cancellation produces noisy garbage slopes Use central differences with h≈10−5h \approx 10^{-5} to 10−610^{-6} 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 w=u−vw = u - v
Ignoring jac= in scipy.optimize.minimize Optimizer runs pp times slower and less accurately Supply your verified analytic gradient function via jac=
  • 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.
  • 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.quad in 1D; Monte Carlo integration in high dimensions).
  • Convex functions (H⪰0H \succeq 0 everywhere) guarantee that every local minimum is global; Lagrange multipliers equate ∇f\nabla f and λ∇g\lambda \nabla g 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.

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 r=0r = 0 where its derivative jumps discontinuously from −1-1 to +1+1, breaking smoothness assumptions of quasi-Newton line searches. Huber loss replaces the corner inside ∣r∣≤δ\lvert r \rvert \le \delta with a smooth parabola 12r2\frac{1}{2} r^2 while keeping linear tails (bounded derivative ±δ\pm \delta) 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 12f′′(w0)Δw2\frac{1}{2} f''(w_0) \Delta w^2 measures curvature, telling you how far to step before the slope levels off. Newton’s method minimizes the quadratic model directly by stepping Δw=−f′(w0)/f′′(w0)\Delta w = -f'(w_0)/f''(w_0).

Q3. For a neural network layer mapping 64 input features to 10 output units, what is the shape of its Jacobian matrix?

Answer

(10,64)(10, 64): one row per output component and one column per input component, with Jij=∂gi/∂xjJ_{ij} = \partial g_i / \partial x_j.

Q4. You find a point w∗\mathbf{w}^* with ∇L(w∗)=0\nabla L(\mathbf{w}^*) = \mathbf{0} and Hessian eigenvalues [3.2, 0.8, -0.4]. What kind of point is w∗\mathbf{w}^*, and what happens if you move along the third eigenvector?

Answer

Because the Hessian has both positive and negative eigenvalues, w∗\mathbf{w}^* is a saddle point. Moving along the eigenvector corresponding to −0.4-0.4 decreases the loss immediately.

Q5. Why does adding a Ridge penalty λ∥w∥22\lambda \lVert \mathbf{w} \rVert_2^2 with λ>0\lambda > 0 make even a collinear least-squares problem strictly convex?

Answer

The OLS Hessian 2nX⊤X\frac{2}{n} X^\top X is positive semidefinite (it can have 00 eigenvalues when columns are collinear). Adding 2λI2\lambda I shifts every eigenvalue up by 2λ>02\lambda > 0, making the Hessian strictly positive definite (H≻0H \succ 0) 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 d≥4d \ge 4), where grid quadrature grows exponentially in dd while Monte Carlo error shrinks as O(1/N)O(1/\sqrt{N}) independent of dimension.

Q7. Geometrically, why does Lasso (∥w∥1≤t\lVert \mathbf{w} \rVert_1 \le t) set weights to exact zero while Ridge (∥w∥22≤t\lVert \mathbf{w} \rVert_2^2 \le t) 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 5,000×5,0005{,}000 \times 5{,}000 Hessian (O(p3)O(p^3) per step). L-BFGS approximates the inverse Hessian from the last ~10 gradient steps in O(mp)O(mp) 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 (m=1m = 1) with respect to millions of parameters (p≫1p \gg 1). Forward-mode requires O(p)O(p) passes (one per parameter), whereas reverse-mode computes all pp gradients in just O(m)=1O(m) = 1 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.

Your progress

0 / 4 done