Skip to content

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.

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 Lδ(r)L_\delta(r)
compute the Huber derivative np.clip(r, -delta, delta) Lδ′(r)L'_\delta(r)
approximate a smooth function near aa f(a)+f′(a)(x−a)+12f′′(a)(x−a)2f(a) + f'(a)(x-a) + \frac{1}{2}f''(a)(x-a)^2 2nd-order Taylor
compute a directional derivative grad @ (u / np.linalg.norm(u)) Duf=∇f⋅uD_{\mathbf{u}} f = \nabla f \cdot \mathbf{u}
build a softmax Jacobian np.diag(p) - np.outer(p, p) diag⁡(p)−pp⊤\operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top
classify a stationary point np.linalg.eigvalsh(H) all >0> 0 min, all <0< 0 max, mixed saddle
check curvature conditioning eigs[-1] / eigs[0] or np.linalg.cond(H) κ(H)=λmax⁡/λmin⁡\kappa(H) = \lambda_{\max}/\lambda_{\min}
integrate a 1D PDF or expectation scipy.integrate.quad(fn, a, b) ∫abf(x) dx\int_a^b f(x)\,dx
estimate a high-D expectation np.mean(g(rng.normal(size=(N, d)))) Monte Carlo O(1/N)O(1/\sqrt{N})
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") ∇f=λ∇g\nabla f = \lambda \nabla g
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) w−H−1∇L\mathbf{w} - H^{-1}\nabla L
apply the L1 proximal step (ISTA) np.sign(u) * np.maximum(np.abs(u) - tau, 0.0) soft-thresholding Sτ(u)S_\tau(u)
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()) O(1)O(1) backward pass

Single-variable derivative rules and Taylor series

Section titled “Single-variable derivative rules and Taylor series”
Rule Formula Example
Product (fg)′=f′g+fg′(fg)' = f'g + fg' (−plog⁡p)′=−log⁡p−1(-p \log p)' = -\log p - 1
Quotient (f/g)′=(f′g−fg′)/g2(f/g)' = (f'g - fg') / g^2 σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z))
Chain (f(g(x)))′=f′(g(x)) g′(x)(f(g(x)))' = f'(g(x))\,g'(x) (log⁡(1+ez))′=σ(z)(\log(1 + e^z))' = \sigma(z)
Power / exp / log (xk)′=kxk−1(x^k)' = kx^{k-1}, (ex)′=ex(e^x)' = e^x, (log⁡x)′=1/x(\log x)' = 1/x core building blocks
Taylor (kk-th order) ∑j=0kf(j)(a)j!(x−a)j\sum_{j=0}^{k} \frac{f^{(j)}(a)}{j!}(x - a)^j ex≈1+x+x22+x36e^x \approx 1 + x + \frac{x^2}{2} + \frac{x^3}{6}
import numpy as np
from 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.5
t3_exp = 1 + x + x**2 / 2 + x**3 / 6
print(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}")
Output
exp(0.5): exact=1.648721, T3=1.645833
softplus'(0.5): num=0.622459, sigmoid=0.622459

Multivariable calculus: gradients, Jacobians and Hessians

Section titled “Multivariable calculus: gradients, Jacobians and Hessians”
Object Shape Definition Role in ML
Gradient ∇f(w)\nabla f(\mathbf{w}) (p,) (∂f/∂w1,…,∂f/∂wp)(\partial f / \partial w_1, \dots, \partial f / \partial w_p) steepest ascent direction; perpendicular to level curves
Directional derivative DufD_{\mathbf{u}} f scalar ∇f(w)⋅u\nabla f(\mathbf{w}) \cdot \mathbf{u} (∥u∥2=1\lVert \mathbf{u} \rVert_2 = 1) slope along unit direction u\mathbf{u}
Jacobian Jg(x)J_{\mathbf{g}}(\mathbf{x}) (m, p) Jij=∂gi/∂xjJ_{ij} = \partial g_i / \partial x_j derivatives of vector-valued layers (linear, softmax)
Hessian Hf(w)H_f(\mathbf{w}) (p, p) Hjk=∂2f/(∂wj∂wk)H_{jk} = \partial^2 f / (\partial w_j \partial w_k) curvature, convexity test, Newton steps
Hessian eigenvalues at ∇f=0\nabla f = \mathbf{0} Matrix class Point type
All λi>0\lambda_i > 0 Positive definite (H≻0H \succ 0) Strict local minimum
All λi<0\lambda_i < 0 Negative definite (H≺0H \prec 0) Strict local maximum
Both λi>0\lambda_i > 0 and λj<0\lambda_j < 0 Indefinite Saddle point
All λi≥0\lambda_i \ge 0, some λi=0\lambda_i = 0 Positive semidefinite (H⪰0H \succeq 0) 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))
Output
saddle eigs: [-1. 3.]
min eigs: [2.382 4.618]

Denominator-layout convention: ∇WL\nabla_W L always has the same shape as WW.

Loss / function Gradient Hessian
a⊤w\mathbf{a}^\top \mathbf{w} a\mathbf{a} 00
w⊤Aw\mathbf{w}^\top A \mathbf{w} (A=A⊤A = A^\top) 2Aw2 A \mathbf{w} 2A2 A
MSE: 1n∥Xw−y∥22\frac{1}{n}\lVert X\mathbf{w} - \mathbf{y} \rVert_2^2 2nX⊤(Xw−y)\frac{2}{n} X^\top (X\mathbf{w} - \mathbf{y}) 2nX⊤X\frac{2}{n} X^\top X
Ridge: MSE +λ∥w∥22+ \lambda \lVert \mathbf{w} \rVert_2^2 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}(\mathbf{p}(1-\mathbf{p})) X
Softmax + CE (P=softmax⁡(XW)P = \operatorname{softmax}(XW)) 1nX⊤(P−Y)\frac{1}{n} X^\top (P - Y) HV=1nX⊤(P⊙(S−∑kPkSk))HV = \frac{1}{n} X^\top (P \odot (S - \sum_k P_k S_k))
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 1N∑g(Xi)\frac{1}{N} \sum g(X_i) high-D expectations, Bayesian posteriors O(1/N)O(1 / \sqrt{N}) independent of dd
Importance sampling 1N∑g(Xi)p(Xi)q(Xi)\frac{1}{N} \sum g(X_i) \frac{p(X_i)}{q(X_i)} 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}")
Output
quad P(|Z|<=1.96) = 0.950004
E[|Z|]: exact=0.7979, MC=0.7987
  • Convexity: f(tu+(1−t)v)≤tf(u)+(1−t)f(v)f(t\mathbf{u} + (1-t)\mathbf{v}) \le t f(\mathbf{u}) + (1-t) f(\mathbf{v}), or H(w)⪰0H(\mathbf{w}) \succeq 0 everywhere. Every local minimum is global; H(w)≻0H(\mathbf{w}) \succ 0 guarantees a unique global minimum.
  • Lagrangian: L(w,λ)=f(w)+λ(g(w)−c)\mathcal{L}(\mathbf{w}, \lambda) = f(\mathbf{w}) + \lambda(g(\mathbf{w}) - c). At an active boundary optimum, ∇f(w)=−λ∇g(w)\nabla f(\mathbf{w}) = -\lambda \nabla g(\mathbf{w}) — level curve and constraint are tangent.
  • Ridge vs. Lasso geometry: ∥w∥22≤t\lVert \mathbf{w} \rVert_2^2 \le t is a smooth sphere (shrinks all weights smoothly); ∥w∥1≤t\lVert \mathbf{w} \rVert_1 \le t is a diamond with corners on the axes (drives weak weights to exact 0).
Optimizer Core update Typical use
Vanilla GD / SGD w←w−ηg\mathbf{w} \leftarrow \mathbf{w} - \eta \mathbf{g} well-conditioned convex models, baseline
Momentum v←βv+g\mathbf{v} \leftarrow \beta \mathbf{v} + \mathbf{g}; w←w−ηv\mathbf{w} \leftarrow \mathbf{w} - \eta \mathbf{v} narrow valleys, CNNs
RMSProp s←ρs+(1−ρ)g2\mathbf{s} \leftarrow \rho \mathbf{s} + (1-\rho)\mathbf{g}^2; w←w−ηs+ϵg\mathbf{w} \leftarrow \mathbf{w} - \frac{\eta}{\sqrt{\mathbf{s}}+\epsilon}\mathbf{g} non-stationary objectives, RNNs
Adam bias-corrected m^,v^\hat{\mathbf{m}}, \hat{\mathbf{v}}; w←w−ηm^v^+ϵ\mathbf{w} \leftarrow \mathbf{w} - \eta \frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{v}}}+\epsilon} default for deep learning and mini-batches
L-BFGS quasi-Newton from last m≈10m \approx 10 gradient diffs full-batch convex models (p≤105p \le 10^5)
Newton solve HΔw=−gH \Delta \mathbf{w} = -\mathbf{g}; w←w+αΔw\mathbf{w} \leftarrow \mathbf{w} + \alpha \Delta \mathbf{w} low-D (p≤103p \le 10^3) 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)
)
Output
L-BFGS-B: [ 0.6383 -0.5532] iters: 6 matches solve: True
Mode Propagates Cost (pp inputs, mm outputs) Best when
Forward-mode (dual numbers) ∂node∂xj\frac{\partial \text{node}}{\partial x_j} input →\to output O(p)O(p) passes p≪mp \ll m (few parameters, many outputs)
Reverse-mode (backprop) ∂L∂node\frac{\partial L}{\partial \text{node}} output →\to inputs O(m)O(m) passes m≪pm \ll p (scalar ML loss, millions of weights)
Finite differences (f(x+h)−f(x−h))/2h(f(x+h) - f(x-h)) / 2h 2p2p 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.

  • Unscaled features ruin conditioning. A 10710^7 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 -1 and 3 (a saddle point). Always check np.linalg.eigvalsh(H).
  • Softmax overflow and log(0). Always subtract row-wise max before np.exp, and use np.logaddexp(0, z) - y * z for binary log loss.
  • Forgetting jac= in scipy.optimize.minimize. Without it, SciPy falls back to slow, noisy finite-difference gradients.
  • Using = instead of += in autograd. Overwriting .grad silently 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 1−β1t1 - \beta_1^t and 1−β2t1 - \beta_2^t, early steps overshoot dramatically because vt\mathbf{v}_t starts at zero.
  • Calling np.linalg.inv(H) @ g. Always solve np.linalg.solve(H, g), and add Armijo backtracking when starting far from the optimum.
  • Calling float(tensor) on a PyTorch scalar with requires_grad=True. Use tensor.item() (or tensor.detach()) to avoid warnings.