47. Calculus and optimization for ML — Cheat sheet
The essentials of 47. Calculus and optimization for ML on one page: every formula next to its NumPy or SciPy implementation. Every runnable block is verified against its shown output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Math |
|---|---|---|
| check an analytic derivative numerically | (f(x + h) - f(x - h)) / (2 * h) (h=1e-6) |
central difference |
| smooth the MAE kink at zero | np.where(abs(r) <= d, 0.5*r**2, d*(abs(r) - 0.5*d)) |
Huber loss |
| compute the Huber derivative | np.clip(r, -delta, delta) |
|
| approximate a smooth function near | 2nd-order Taylor | |
| compute a directional derivative | grad @ (u / np.linalg.norm(u)) |
|
| build a softmax Jacobian | np.diag(p) - np.outer(p, p) |
|
| classify a stationary point | np.linalg.eigvalsh(H) |
all min, all max, mixed saddle |
| check curvature conditioning | eigs[-1] / eigs[0] or np.linalg.cond(H) |
|
| integrate a 1D PDF or expectation | scipy.integrate.quad(fn, a, b) |
|
| estimate a high-D expectation | np.mean(g(rng.normal(size=(N, d)))) |
Monte Carlo |
| verify convexity empirically | fn(t*u + (1-t)*v) <= t*fn(u) + (1-t)*fn(v) |
Jensen’s inequality |
| solve a constrained smooth problem | scipy.optimize.minimize(..., method="SLSQP") |
|
| minimize a smooth convex loss fast | scipy.optimize.minimize(f, x0, jac=g, method="L-BFGS-B") |
quasi-Newton |
| take one exact Newton step | w = w - np.linalg.solve(H, g) |
|
| apply the L1 proximal step (ISTA) | np.sign(u) * np.maximum(np.abs(u) - tau, 0.0) |
soft-thresholding |
| compute stable softmax (row-wise) | e = np.exp(Z - Z.max(axis=1, keepdims=True)); e / e.sum(1, keepdims=True) |
shift invariance |
| compute stable binary log loss | np.mean(np.logaddexp(0.0, z) - y * z) |
avoids log(0) |
| get exact gradients of a computation graph | reverse-mode autodiff (loss.backward()) |
backward pass |
Single-variable derivative rules and Taylor series
Section titled “Single-variable derivative rules and Taylor series”| Rule | Formula | Example |
|---|---|---|
| Product | ||
| Quotient | ||
| Chain | ||
| Power / exp / log | , , | core building blocks |
| Taylor (-th order) |
import numpy as npfrom scipy import integrate, optimize, stats
np.set_printoptions(precision=4, suppress=True)
def central_diff(fn, x: float, h: float = 1e-6) -> float: return float((fn(x + h) - fn(x - h)) / (2 * h))
x = 0.5t3_exp = 1 + x + x**2 / 2 + x**3 / 6print(f"exp(0.5): exact={np.exp(x):.6f}, T3={t3_exp:.6f}")print(f"softplus'(0.5): num={central_diff(lambda z: np.log1p(np.exp(z)), x):.6f}, " f"sigmoid={1 / (1 + np.exp(-x)):.6f}")exp(0.5): exact=1.648721, T3=1.645833softplus'(0.5): num=0.622459, sigmoid=0.622459Multivariable calculus: gradients, Jacobians and Hessians
Section titled “Multivariable calculus: gradients, Jacobians and Hessians”| Object | Shape | Definition | Role in ML |
|---|---|---|---|
| Gradient | (p,) |
steepest ascent direction; perpendicular to level curves | |
| Directional derivative | scalar | () | slope along unit direction |
| Jacobian | (m, p) |
derivatives of vector-valued layers (linear, softmax) | |
| Hessian | (p, p) |
curvature, convexity test, Newton steps |
| Hessian eigenvalues at | Matrix class | Point type |
|---|---|---|
| All | Positive definite () | Strict local minimum |
| All | Negative definite () | Strict local maximum |
| Both and | Indefinite | Saddle point |
| All , some | Positive semidefinite () | Flat valley / inconclusive |
H_saddle = np.array([[1.0, 2.0], [2.0, 1.0]])H_min = np.array([[4.0, 1.0], [1.0, 3.0]])print("saddle eigs:", np.linalg.eigvalsh(H_saddle))print("min eigs:", np.linalg.eigvalsh(H_min))saddle eigs: [-1. 3.]min eigs: [2.382 4.618]Matrix calculus identities for ML
Section titled “Matrix calculus identities for ML”Denominator-layout convention: always has the same shape as .
| Loss / function | Gradient | Hessian |
|---|---|---|
| () | ||
| MSE: | ||
| Ridge: MSE | ||
| Binary log loss () | ||
| Softmax + CE () |
Numerical integration and Monte Carlo
Section titled “Numerical integration and Monte Carlo”| Method | Best for | Error scaling |
|---|---|---|
scipy.integrate.quad(f, a, b) |
1D smooth integrals, PDFs, 1D expectations | ~14 digits (1e-14) |
scipy.integrate.dblquad / nquad |
2D–3D smooth integrals | slows rapidly with dimension |
| Monte Carlo | high-D expectations, Bayesian posteriors | independent of |
| Importance sampling | rare tails where naive MC misses | orders-of-magnitude variance reduction |
area, _ = integrate.quad(stats.norm.pdf, -1.96, 1.96)rng = np.random.default_rng(42)mc_e = float(np.mean(np.abs(rng.standard_normal(50_000))))exact_e = float(np.sqrt(2.0 / np.pi))print(f"quad P(|Z|<=1.96) = {area:.6f}")print(f"E[|Z|]: exact={exact_e:.4f}, MC={mc_e:.4f}")quad P(|Z|<=1.96) = 0.950004E[|Z|]: exact=0.7979, MC=0.7987Convexity and Lagrange multipliers
Section titled “Convexity and Lagrange multipliers”- Convexity: , or everywhere. Every local minimum is global; guarantees a unique global minimum.
- Lagrangian: . At an active boundary optimum, — level curve and constraint are tangent.
- Ridge vs. Lasso geometry: is a smooth sphere (shrinks all weights smoothly); is a diamond with corners on the axes (drives weak weights to exact
0).
Optimizer comparison and update rules
Section titled “Optimizer comparison and update rules”| Optimizer | Core update | Typical use |
|---|---|---|
| Vanilla GD / SGD | well-conditioned convex models, baseline | |
| Momentum | ; | narrow valleys, CNNs |
| RMSProp | ; | non-stationary objectives, RNNs |
| Adam | bias-corrected ; | default for deep learning and mini-batches |
| L-BFGS | quasi-Newton from last gradient diffs | full-batch convex models () |
| Newton | solve ; | low-D () strictly convex problems |
A = np.array([[2.0, 0.5], [0.5, 6.0]])b = np.array([1.0, -3.0])res = optimize.minimize( lambda w: 0.5 * float(w @ A @ w) - float(b @ w), x0=np.zeros(2), jac=lambda w: A @ w - b, method="L-BFGS-B",)w_exact = np.linalg.solve(A, b)print( "L-BFGS-B:", res.x, "iters:", res.nit, "matches solve:", np.allclose(res.x, w_exact))L-BFGS-B: [ 0.6383 -0.5532] iters: 6 matches solve: TrueAutomatic differentiation
Section titled “Automatic differentiation”| Mode | Propagates | Cost ( inputs, outputs) | Best when |
|---|---|---|---|
| Forward-mode (dual numbers) | input output | passes | (few parameters, many outputs) |
| Reverse-mode (backprop) | output inputs | passes | (scalar ML loss, millions of weights) |
| Finite differences | evaluations | gradient checking only (slow, truncation error) |
Reverse-mode checklist: (1) record forward ops in a DAG, (2) traverse nodes in reverse topological order, (3) accumulate into parents with += (never =), (4) reset .grad to zero before the next step.
Gotchas
Section titled “Gotchas”- Unscaled features ruin conditioning. A Hessian condition number forces tiny GD learning rates; standardize features on the training split first.
- Diagonal of the Hessian is not enough.
[[1, 2], [2, 1]]has positive diagonal entries yet eigenvalues-1and3(a saddle point). Always checknp.linalg.eigvalsh(H). - Softmax overflow and
log(0). Always subtract row-wise max beforenp.exp, and usenp.logaddexp(0, z) - y * zfor binary log loss. - Forgetting
jac=inscipy.optimize.minimize. Without it, SciPy falls back to slow, noisy finite-difference gradients. - Using
=instead of+=in autograd. Overwriting.gradsilently breaks any expression where a variable is used more than once. - Forgetting
zero_grad(). Because autograd accumulates with+=, stale gradients from prior batches corrupt the next step if not cleared. - Omitting Adam bias correction. Without and , early steps overshoot dramatically because starts at zero.
- Calling
np.linalg.inv(H) @ g. Always solvenp.linalg.solve(H, g), and add Armijo backtracking when starting far from the optimum. - Calling
float(tensor)on a PyTorch scalar withrequires_grad=True. Usetensor.item()(ortensor.detach()) to avoid warnings.