Skip to content

Calculus and optimization

Training a model means minimizing a loss function with derivatives. This reference gathers scalar and matrix calculus identities, numerical integration, convexity and Lagrange multipliers, scipy.optimize, modern gradient optimizers, and reverse-mode automatic differentiation. All blocks share one session using data/customers.csv and data/ab_test.csv:

import numpy as np
import pandas as pd
from scipy import integrate, optimize, stats
customers = pd.read_csv("data/customers.csv")
ab = pd.read_csv("data/ab_test.csv")
I want to… Use… Notes
verify an analytical gradient numerically centered difference (f(x+h)−f(x−h))/(2h)(f(x+h)-f(x-h))/(2h) O(h2)O(h^2) error; pick h≈10−5h \approx 10^{-5}
approximate a smooth function near aa 2nd-order Taylor f(a)+f′(a)(x−a)+12f′′(a)(x−a)2f(a) + f'(a)(x-a) + \frac{1}{2}f''(a)(x-a)^2 foundation of Newton’s method
check if a critical point (∇f=0\nabla f = 0) is a minimum Hessian HH positive definite (λmin⁡(H)>0\lambda_{\min}(H) > 0) mixed signs ⇒\Rightarrow saddle point
integrate a 1D function or PDF numerically scipy.integrate.quad(f, a, b) returns (value, abs_error)
integrate sampled grid values np.trapezoid(y, x) or scipy.integrate.simpson replaces deprecated np.trapz
estimate a high-D expectation E[g(X)]\mathbb{E}[g(X)] Monte Carlo 1N∑g(Xi)\frac{1}{N}\sum g(X_i) error O(1/N)O(1/\sqrt{N}), independent of dd
minimize a smooth unconstrained function optimize.minimize(f, x0, jac=grad, method="L-BFGS-B") quasi-Newton; fast on moderate dd
minimize with bounds or constraints method="L-BFGS-B" (box) or "SLSQP" (eq/ineq) pass bounds= and constraints=
find a root g(x)=0g(x) = 0 on bracket [a,b][a, b] optimize.brentq(g, a, b) requires g(a)g(a) and g(b)g(b) opposite signs
train large mini-batch neural networks Adam (lr=1e-3, β1=0.9,β2=0.999\beta_1=0.9, \beta_2=0.999) adaptive per-parameter step sizes
Rule / Function Formula Derivative
Power xnx^n nxn−1n x^{n-1}
Exponential / Log eaxe^{ax}, ln⁡(x)\ln(x) aeaxa e^{ax}, 1/x1/x
Product rule u(x)v(x)u(x) v(x) u′v+uv′u' v + u v'
Quotient rule u(x)/v(x)u(x) / v(x) (u′v−uv′)/v2(u' v - u v') / v^2
Chain rule f(g(x))f(g(x)) f′(g(x))⋅g′(x)f'(g(x)) \cdot g'(x)
Sigmoid σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}} σ(z)(1−σ(z))\sigma(z)(1 - \sigma(z))
Hyperbolic tangent tanh⁡(z)\tanh(z) 1−tanh⁡2(z)1 - \tanh^2(z)
Softplus ln⁡(1+ez)\ln(1 + e^z) σ(z)\sigma(z)
ReLU max⁡(0,z)\max(0, z) 11 if z>0z > 0, 00 if z<0z < 0 (subgradient [0,1][0, 1] at 00)
Huber loss (δ\delta) 12r2\frac{1}{2}r^2 if ∣r∣≤δ\vert r \vert \le \delta else δ(∣r∣−12δ)\delta(\vert r \vert - \frac{1}{2}\delta) rr if ∣r∣≤δ\vert r \vert \le \delta else δ sign(r)\delta\,\mathrm{sign}(r)

Taylor series around aa:

f(x)=∑k=0nf(k)(a)k!(x−a)k+O ⁣((x−a)n+1)f(x) = \sum_{k=0}^{n} \frac{f^{(k)}(a)}{k!} (x - a)^k + O\!\left((x - a)^{n+1}\right)

Useful expansions near x=0x = 0: ex≈1+x+x22e^x \approx 1 + x + \frac{x^2}{2}, ln⁡(1+x)≈x−x22\ln(1 + x) \approx x - \frac{x^2}{2}, and σ(x)≈12+x4−x348\sigma(x) \approx \frac{1}{2} + \frac{x}{4} - \frac{x^3}{48}.

def sigmoid(z: np.ndarray | float) -> np.ndarray | float:
return 1.0 / (1.0 + np.exp(-z))
z = 0.4
h = 1e-5
analytic = sigmoid(z) * (1.0 - sigmoid(z))
numeric = (sigmoid(z + h) - sigmoid(z - h)) / (2.0 * h)
taylor3 = 0.5 + z / 4.0 - (z**3) / 48.0
print(f"sigmoid'(0.4) analytic={analytic:.8f}, numeric={numeric:.8f}")
print(f"sigmoid(0.4) exact={sigmoid(z):.6f}, 3rd-order Taylor={taylor3:.6f}")
Output
sigmoid'(0.4) analytic=0.24026075, numeric=0.24026075
sigmoid(0.4) exact=0.598688, 3rd-order Taylor=0.598667

For f:Rd→Rf: \mathbb{R}^d \to \mathbb{R} and g:Rd→Rmg: \mathbb{R}^d \to \mathbb{R}^m:

  • Gradient ∇f(x)∈Rd\nabla f(x) \in \mathbb{R}^d: points in the direction of steepest ascent; directional derivative along unit vector uu is Duf(x)=∇f(x)⊤uD_u f(x) = \nabla f(x)^\top u.
  • Jacobian (Jg)ij=∂gi∂xj∈Rm×d(J_g)_{ij} = \frac{\partial g_i}{\partial x_j} \in \mathbb{R}^{m \times d}: multivariable chain rule is matrix multiplication Jh∘g(x)=Jh(g(x))Jg(x)J_{h \circ g}(x) = J_h(g(x)) J_g(x).
  • Hessian (Hf)ij=∂2f∂xi∂xj∈Rd×d(H_f)_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j} \in \mathbb{R}^{d \times d}: symmetric for smooth ff. At ∇f(x∗)=0\nabla f(x^*) = 0: all λi>0⇒\lambda_i > 0 \Rightarrow strict local min; all λi<0⇒\lambda_i < 0 \Rightarrow strict local max; mixed signs ⇒\Rightarrow saddle point.
Expression f(w)f(w) Gradient ∇wf\nabla_w f Hessian ∇w2f\nabla_w^2 f
a⊤wa^\top w aa 00
w⊤Aww^\top A w (general AA) (A+A⊤)w(A + A^\top) w A+A⊤A + A^\top
12w⊤Sw\frac{1}{2} w^\top S w (symmetric SS) SwS w SS
12n∥Xw−y∥22\frac{1}{2n}\Vert Xw - y \Vert_2^2 (MSE) 1nX⊤(Xw−y)\frac{1}{n} X^\top (Xw - y) 1nX⊤X\frac{1}{n} X^\top X
12n∥Xw−y∥22+λ2∥w∥22\frac{1}{2n}\Vert Xw - y \Vert_2^2 + \frac{\lambda}{2}\Vert w \Vert_2^2 (Ridge) 1nX⊤(Xw−y)+λw\frac{1}{n} X^\top (Xw - y) + \lambda w 1nX⊤X+λI\frac{1}{n} X^\top X + \lambda I
Binary log-loss −1n∑[yiln⁡pi+(1−yi)ln⁡(1−pi)]-\frac{1}{n}\sum [y_i \ln p_i + (1-y_i)\ln(1-p_i)] 1nX⊤(p−y)\frac{1}{n} X^\top (p - y) 1nX⊤diag(p(1−p))X\frac{1}{n} X^\top \mathrm{diag}(p(1-p)) X
Softmax + cross-entropy (logits Z=XWZ = XW) ∂L∂Z=1n(P−Y)\frac{\partial L}{\partial Z} = \frac{1}{n}(P - Y), ∂L∂W=1nX⊤(P−Y)\frac{\partial L}{\partial W} = \frac{1}{n} X^\top (P - Y) positive semi-definite
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
raw = customers[cols].to_numpy(dtype=float)
X = np.column_stack([np.ones(len(raw)), (raw - raw.mean(0)) / raw.std(0)])
y = customers["churned"].to_numpy(dtype=float)
def log_loss(w: np.ndarray, reg: float = 1e-2) -> float:
z = X @ w
loss = np.mean(np.logaddexp(0.0, z) - y * z)
return float(loss + 0.5 * reg * np.dot(w[1:], w[1:]))
def log_grad(w: np.ndarray, reg: float = 1e-2) -> np.ndarray:
p = sigmoid(X @ w)
g = (X.T @ (p - y)) / len(y)
g[1:] += reg * w[1:]
return g
def log_hess(w: np.ndarray, reg: float = 1e-2) -> np.ndarray:
p = sigmoid(X @ w)
H = (X.T * (p * (1.0 - p))) @ X / len(y)
H[1:, 1:] += reg * np.eye(X.shape[1] - 1)
return H
w0 = np.zeros(X.shape[1])
num_grad = optimize.approx_fprime(w0, log_loss, 1e-6)
eigvals = np.linalg.eigvalsh(log_hess(w0))
err = np.max(np.abs(log_grad(w0) - num_grad))
print("max |analytic - numeric grad|:", f"{err:.2e}")
print("min Hessian eigenvalue at w=0:", round(float(eigvals.min()), 4))
Output
max |analytic - numeric grad|: 1.30e-07
min Hessian eigenvalue at w=0: 0.2084
Method Formula / Call Best for
Fundamental Theorem ∫abf(x) dx=F(b)−F(a)\int_a^b f(x)\,dx = F(b) - F(a) verifying CDF from PDF
Adaptive quadrature integrate.quad(f, a, b) smooth 1D integrals (supports np.inf)
Grid trapezoid rule np.trapezoid(y, x) tabulated curves, ROC AUC
Monte Carlo expectation E[g(X)]≈1N∑i=1Ng(Xi)\mathbb{E}[g(X)] \approx \frac{1}{N} \sum_{i=1}^N g(X_i) high-dimensional expectations and Bayesian posteriors
rev = ab.loc[ab["converted"] == 1, "revenue"].to_numpy()
s, _, scale = stats.lognorm.fit(rev, floc=0)
dist = stats.lognorm(s=s, loc=0, scale=scale)
prob_quad, _ = integrate.quad(dist.pdf, 20.0, 60.0)
prob_cdf = dist.cdf(60.0) - dist.cdf(20.0)
ev_quad, _ = integrate.quad(lambda x: x * dist.pdf(x), 0.0, np.inf)
rng = np.random.default_rng(42)
ev_mc = float(dist.rvs(size=50_000, random_state=rng).mean())
print(f"P(20 <= X <= 60): quad={prob_quad:.5f}, cdf={prob_cdf:.5f}")
print(f"E[revenue]: quad={ev_quad:.2f}, exact={dist.mean():.2f}, MC={ev_mc:.2f}")
Output
P(20 <= X <= 60): quad=0.60726, cdf=0.60726
E[revenue]: quad=42.42, exact=42.42, MC=42.46

A function ff is convex if f(tx+(1−t)y)≤tf(x)+(1−t)f(y)f(tx + (1-t)y) \le t f(x) + (1-t) f(y) for t∈[0,1]t \in [0, 1] (equivalently, Hf(x)⪰0H_f(x) \succeq 0 everywhere). Every local minimum of a convex function is a global minimum; if Hf(x)≻0H_f(x) \succ 0 (strictly convex), the global minimum is unique.

To minimize f(x)f(x) subject to g(x)=0g(x) = 0, form the Lagrangian L(x,λ)=f(x)+λg(x)\mathcal{L}(x, \lambda) = f(x) + \lambda g(x) and solve ∇xL=0, g(x)=0\nabla_x \mathcal{L} = 0, \, g(x) = 0 — meaning ∇f(x∗)\nabla f(x^*) is parallel to ∇g(x∗)\nabla g(x^*) (contours are tangent). For inequality constraints g(x)≤0g(x) \le 0, the KKT conditions add dual feasibility (λ≥0\lambda \ge 0) and complementary slackness (λg(x∗)=0\lambda g(x^*) = 0). In regularization, the L1L_1 diamond ∥w∥1≤t\Vert w \Vert_1 \le t has sharp corners on the axes (driving exact zeros in Lasso), while the L2L_2 sphere ∥w∥22≤t\Vert w \Vert_2^2 \le t shrinks weights smoothly (Ridge).

# Minimize (w0 - 2)^2 + (w1 - 1)^2 subject to w0^2 + w1^2 <= 1 (L2 ball)
res = optimize.minimize(
lambda w: (w[0] - 2.0) ** 2 + (w[1] - 1.0) ** 2,
x0=np.array([0.0, 0.0]),
method="SLSQP",
constraints={"type": "ineq", "fun": lambda w: 1.0 - np.dot(w, w)},
)
norm_opt = round(float(np.linalg.norm(res.x)), 4)
print("constrained optimum:", np.round(res.x, 4), "norm:", norm_opt)
Output
constrained optimum: [0.8944 0.4472] norm: 1.0
Optimizer Update rule Order Strengths / Best for
Gradient Descent (GD) w←w−ηgw \leftarrow w - \eta g 1st simple; slow in ill-conditioned valleys
SGD + Momentum v←βv+gv \leftarrow \beta v + g, w←w−ηvw \leftarrow w - \eta v 1st damps oscillations; strong generalization on vision CNNs
RMSProp s←βs+(1−β)g2s \leftarrow \beta s + (1-\beta) g^2, w←w−ηs+ϵgw \leftarrow w - \frac{\eta}{\sqrt{s}+\epsilon} g 1st scales step size per coordinate
Adam bias-corrected 1st (mm) and 2nd (vv) moments of gg 1st default for deep learning; use AdamW for weight decay
Newton’s method w←w−H−1gw \leftarrow w - H^{-1} g 2nd quadratic convergence; O(d3)O(d^3) Hessian solve limits dd
L-BFGS / L-BFGS-B approximates H−1gH^{-1} g from last mm steps quasi-2nd O(md)O(md) memory; gold standard for smooth batch convex models
# Compare 80 steps of GD, 80 steps of Adam, 5 steps of Newton, and L-BFGS-B
w_gd = np.zeros(X.shape[1])
for _ in range(80):
w_gd -= 0.5 * log_grad(w_gd)
w_adam = np.zeros(X.shape[1])
m = np.zeros_like(w_adam)
v = np.zeros_like(w_adam)
for t in range(1, 81):
g = log_grad(w_adam)
m = 0.9 * m + 0.1 * g
v = 0.999 * v + 0.001 * (g**2)
m_hat, v_hat = m / (1.0 - 0.9**t), v / (1.0 - 0.999**t)
w_adam -= 0.05 * m_hat / (np.sqrt(v_hat) + 1e-8)
w_newt = np.zeros(X.shape[1])
for _ in range(5):
w_newt -= np.linalg.solve(log_hess(w_newt), log_grad(w_newt))
res_lbfgs = optimize.minimize(
log_loss, np.zeros(X.shape[1]), jac=log_grad, method="L-BFGS-B"
)
print(f"GD (80): loss={log_loss(w_gd):.6f}")
print(f"Adam (80): loss={log_loss(w_adam):.6f}")
print(f"Newton (5): loss={log_loss(w_newt):.6f}")
print(f"L-BFGS ({res_lbfgs.nit}): loss={res_lbfgs.fun:.6f}")
Output
GD (80): loss=0.414188
Adam (80): loss=0.413867
Newton (5): loss=0.413856
L-BFGS (8): loss=0.413856
Mode Propagates Cost for f:Rd→Rmf: \mathbb{R}^d \to \mathbb{R}^m Used for
Finite differences perturbed function evaluations O(d)O(d) evals, truncation/roundoff error gradient checking only
Forward-mode AD tangents v˙=∂v/∂xi\dot{v} = \partial v / \partial x_i (dual numbers) O(d)O(d) passes few inputs, many outputs (d≪md \ll m)
Reverse-mode AD (backprop) adjoints vˉ=∂L/∂v\bar{v} = \partial L / \partial v in reverse topo order O(m)O(m) passes (11 pass for scalar loss) neural networks (d≫1,m=1d \gg 1, m = 1)
class Value:
"""Minimal reverse-mode autograd scalar node."""
def __init__(self, data: float, children: tuple["Value", ...] = ()) -> None:
self.data = float(data)
self.grad = 0.0
self._backward = lambda: None
self._prev = set(children)
def __add__(self, other: "Value") -> "Value":
out = Value(self.data + other.data, (self, other))
def _bw() -> None:
self.grad += out.grad
other.grad += out.grad
out._backward = _bw
return out
def __mul__(self, other: "Value") -> "Value":
out = Value(self.data * other.data, (self, other))
def _bw() -> None:
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out._backward = _bw
return out
def backward(self) -> None:
topo: list[Value] = []
seen: set[Value] = set()
def build(node: Value) -> None:
if node not in seen:
seen.add(node)
for ch in node._prev:
build(ch)
topo.append(node)
build(self)
self.grad = 1.0
for node in reversed(topo):
node._backward()
a, b, c = Value(2.0), Value(-3.0), Value(5.0)
loss = (a * b + c) * (a * b + c) # f(a, b, c) = (ab + c)^2
loss.backward()
print(f"loss={loss.data:.1f}, da={a.grad:.1f}, db={b.grad:.1f}, dc={c.grad:.1f}")
Output
loss=1.0, da=6.0, db=-4.0, dc=-2.0
Trap Symptom Fix
choosing finite-difference h=10−12h = 10^{-12} catastrophic cancellation gives noisy gradients use centered difference with h≈10−5h \approx 10^{-5} to 10−610^{-6}
computing np.log(1 + np.exp(z)) for large z RuntimeWarning: overflow and inf loss use np.logaddexp(0.0, z)
forgetting jac=grad in scipy.optimize.minimize slow finite-difference gradients inside the optimizer pass analytical jac= (and hess= for Newton methods)
ignoring res.success from scipy.optimize.minimize silently uses an unconverged vector check assert res.success, res.message
unscaled features in gradient descent zig-zagging along narrow contours; requires tiny η\eta standardize features to mean 0, std 1 before optimizing
applying L2 weight decay to the bias / intercept term shifts predictions toward zero regularize only w[1:], not the intercept w[0]
setting self.grad = ... instead of += in backprop wrong gradient whenever a node is used twice (fan-out) accumulate with += and zero grads before each pass
passing a one-sided step size too big for Newton’s method diverges far from the minimum add backtracking line search or use L-BFGS-B
assuming a zero gradient means a minimum stuck at a saddle point or local maximum check Hessian eigenvalues or perturb