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:
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 ) ) / ( 2 h ) (f(x+h)-f(x-h))/(2h) ( f ( x + h ) − f ( x − h )) / ( 2 h )
O ( h 2 ) O(h^2) O ( h 2 ) error; pick h ≈ 10 − 5 h \approx 10^{-5} h ≈ 1 0 − 5
approximate a smooth function near a a a
2nd-order Taylor f ( a ) + f ′ ( a ) ( x − a ) + 1 2 f ′ ′ ( a ) ( x − a ) 2 f(a) + f'(a)(x-a) + \frac{1}{2}f''(a)(x-a)^2 f ( a ) + f ′ ( a ) ( x − a ) + 2 1 f ′′ ( a ) ( x − a ) 2
foundation of Newton’s method
check if a critical point (∇ f = 0 \nabla f = 0 ∇ f = 0 ) is a minimum
Hessian H H H positive definite (λ min ( H ) > 0 \lambda_{\min}(H) > 0 λ m i n ( 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)] E [ g ( X )]
Monte Carlo 1 N ∑ g ( X i ) \frac{1}{N}\sum g(X_i) N 1 ∑ g ( X i )
error O ( 1 / N ) O(1/\sqrt{N}) O ( 1/ N ) , independent of d d d
minimize a smooth unconstrained function
optimize.minimize(f, x0, jac=grad, method="L-BFGS-B")
quasi-Newton; fast on moderate d d d
minimize with bounds or constraints
method="L-BFGS-B" (box) or "SLSQP" (eq/ineq)
pass bounds= and constraints=
find a root g ( x ) = 0 g(x) = 0 g ( x ) = 0 on bracket [ a , b ] [a, b] [ a , b ]
optimize.brentq(g, a, b)
requires g ( a ) g(a) g ( a ) and g ( b ) 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 β 1 = 0.9 , β 2 = 0.999 )
adaptive per-parameter step sizes
Rule / Function
Formula
Derivative
Power
x n x^n x n
n x n − 1 n x^{n-1} n x n − 1
Exponential / Log
e a x e^{ax} e a x , ln ( x ) \ln(x) ln ( x )
a e a x a e^{ax} a e a x , 1 / x 1/x 1/ x
Product rule
u ( x ) v ( x ) u(x) v(x) u ( x ) v ( x )
u ′ v + u v ′ u' v + u v' u ′ v + u v ′
Quotient rule
u ( x ) / v ( x ) u(x) / v(x) u ( x ) / v ( x )
( u ′ v − u v ′ ) / v 2 (u' v - u v') / v^2 ( u ′ v − u v ′ ) / v 2
Chain rule
f ( g ( x ) ) f(g(x)) f ( g ( x ))
f ′ ( g ( x ) ) ⋅ g ′ ( x ) f'(g(x)) \cdot g'(x) f ′ ( g ( x )) ⋅ g ′ ( x )
Sigmoid
σ ( z ) = 1 1 + e − z \sigma(z) = \frac{1}{1 + e^{-z}} σ ( z ) = 1 + e − z 1
σ ( z ) ( 1 − σ ( z ) ) \sigma(z)(1 - \sigma(z)) σ ( z ) ( 1 − σ ( z ))
Hyperbolic tangent
tanh ( z ) \tanh(z) tanh ( z )
1 − tanh 2 ( z ) 1 - \tanh^2(z) 1 − tanh 2 ( z )
Softplus
ln ( 1 + e z ) \ln(1 + e^z) ln ( 1 + e z )
σ ( z ) \sigma(z) σ ( z )
ReLU
max ( 0 , z ) \max(0, z) max ( 0 , z )
1 1 1 if z > 0 z > 0 z > 0 , 0 0 0 if z < 0 z < 0 z < 0 (subgradient [ 0 , 1 ] [0, 1] [ 0 , 1 ] at 0 0 0 )
Huber loss (δ \delta δ )
1 2 r 2 \frac{1}{2}r^2 2 1 r 2 if ∣ r ∣ ≤ δ \vert r \vert \le \delta ∣ r ∣ ≤ δ else δ ( ∣ r ∣ − 1 2 δ ) \delta(\vert r \vert - \frac{1}{2}\delta) δ ( ∣ r ∣ − 2 1 δ )
r r r if ∣ r ∣ ≤ δ \vert r \vert \le \delta ∣ r ∣ ≤ δ else δ s i g n ( r ) \delta\,\mathrm{sign}(r) δ sign ( r )
Taylor series around a a a :
f ( x ) = ∑ k = 0 n f ( 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) f ( x ) = k = 0 ∑ n k ! f ( k ) ( a ) ( x − a ) k + O ( ( x − a ) n + 1 )
Useful expansions near x = 0 x = 0 x = 0 : e x ≈ 1 + x + x 2 2 e^x \approx 1 + x + \frac{x^2}{2} e x ≈ 1 + x + 2 x 2 , ln ( 1 + x ) ≈ x − x 2 2 \ln(1 + x) \approx x - \frac{x^2}{2} ln ( 1 + x ) ≈ x − 2 x 2 , and σ ( x ) ≈ 1 2 + x 4 − x 3 48 \sigma(x) \approx \frac{1}{2} + \frac{x}{4} - \frac{x^3}{48} σ ( x ) ≈ 2 1 + 4 x − 48 x 3 .
def sigmoid (z: np.ndarray | float ) -> np.ndarray | float :
return 1.0 / ( 1.0 + np.exp( - z))
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 } " )
sigmoid'(0.4) analytic=0.24026075, numeric=0.24026075
sigmoid(0.4) exact=0.598688, 3rd-order Taylor=0.598667
For f : R d → R f: \mathbb{R}^d \to \mathbb{R} f : R d → R and g : R d → R m g: \mathbb{R}^d \to \mathbb{R}^m g : R d → R m :
Gradient ∇ f ( x ) ∈ R d \nabla f(x) \in \mathbb{R}^d ∇ f ( x ) ∈ R d : points in the direction of steepest ascent; directional derivative along unit vector u u u is D u f ( x ) = ∇ f ( x ) ⊤ u D_u f(x) = \nabla f(x)^\top u D u f ( x ) = ∇ f ( x ) ⊤ u .
Jacobian ( J g ) i j = ∂ g i ∂ x j ∈ R m × d (J_g)_{ij} = \frac{\partial g_i}{\partial x_j} \in \mathbb{R}^{m \times d} ( J g ) ij = ∂ x j ∂ g i ∈ R m × d : multivariable chain rule is matrix multiplication J h ∘ g ( x ) = J h ( g ( x ) ) J g ( x ) J_{h \circ g}(x) = J_h(g(x)) J_g(x) J h ∘ g ( x ) = J h ( g ( x )) J g ( x ) .
Hessian ( H f ) i j = ∂ 2 f ∂ x i ∂ x j ∈ R d × d (H_f)_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j} \in \mathbb{R}^{d \times d} ( H f ) ij = ∂ x i ∂ x j ∂ 2 f ∈ R d × d : symmetric for smooth f f f . At ∇ f ( x ∗ ) = 0 \nabla f(x^*) = 0 ∇ f ( x ∗ ) = 0 : all λ i > 0 ⇒ \lambda_i > 0 \Rightarrow λ i > 0 ⇒ strict local min; all λ i < 0 ⇒ \lambda_i < 0 \Rightarrow λ i < 0 ⇒ strict local max; mixed signs ⇒ \Rightarrow ⇒ saddle point.
Expression f ( w ) f(w) f ( w )
Gradient ∇ w f \nabla_w f ∇ w f
Hessian ∇ w 2 f \nabla_w^2 f ∇ w 2 f
a ⊤ w a^\top w a ⊤ w
a a a
0 0 0
w ⊤ A w w^\top A w w ⊤ A w (general A A A )
( A + A ⊤ ) w (A + A^\top) w ( A + A ⊤ ) w
A + A ⊤ A + A^\top A + A ⊤
1 2 w ⊤ S w \frac{1}{2} w^\top S w 2 1 w ⊤ S w (symmetric S S S )
S w S w S w
S S S
1 2 n ∥ X w − y ∥ 2 2 \frac{1}{2n}\Vert Xw - y \Vert_2^2 2 n 1 ∥ X w − y ∥ 2 2 (MSE)
1 n X ⊤ ( X w − y ) \frac{1}{n} X^\top (Xw - y) n 1 X ⊤ ( X w − y )
1 n X ⊤ X \frac{1}{n} X^\top X n 1 X ⊤ X
1 2 n ∥ X w − y ∥ 2 2 + λ 2 ∥ w ∥ 2 2 \frac{1}{2n}\Vert Xw - y \Vert_2^2 + \frac{\lambda}{2}\Vert w \Vert_2^2 2 n 1 ∥ X w − y ∥ 2 2 + 2 λ ∥ w ∥ 2 2 (Ridge)
1 n X ⊤ ( X w − y ) + λ w \frac{1}{n} X^\top (Xw - y) + \lambda w n 1 X ⊤ ( X w − y ) + λ w
1 n X ⊤ X + λ I \frac{1}{n} X^\top X + \lambda I n 1 X ⊤ X + λ I
Binary log-loss − 1 n ∑ [ y i ln p i + ( 1 − y i ) ln ( 1 − p i ) ] -\frac{1}{n}\sum [y_i \ln p_i + (1-y_i)\ln(1-p_i)] − n 1 ∑ [ y i ln p i + ( 1 − y i ) ln ( 1 − p i )]
1 n X ⊤ ( p − y ) \frac{1}{n} X^\top (p - y) n 1 X ⊤ ( p − y )
1 n X ⊤ d i a g ( p ( 1 − p ) ) X \frac{1}{n} X^\top \mathrm{diag}(p(1-p)) X n 1 X ⊤ diag ( p ( 1 − p )) X
Softmax + cross-entropy (logits Z = X W Z = XW Z = X W )
∂ L ∂ Z = 1 n ( P − Y ) \frac{\partial L}{\partial Z} = \frac{1}{n}(P - Y) ∂ Z ∂ L = n 1 ( P − Y ) , ∂ L ∂ W = 1 n X ⊤ ( P − Y ) \frac{\partial L}{\partial W} = \frac{1}{n} X^\top (P - Y) ∂ W ∂ L = n 1 X ⊤ ( 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 :
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:
g = (X.T @ (p - y)) / len (y)
def log_hess (w: np.ndarray, reg: float = 1e-2 ) -> np.ndarray:
H = (X.T * (p * ( 1.0 - p))) @ X / len (y)
H[ 1 :, 1 :] += reg * np.eye(X.shape[ 1 ] - 1 )
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 ))
max |analytic - numeric grad|: 1.30e-07
min Hessian eigenvalue at w=0: 0.2084
Method
Formula / Call
Best for
Fundamental Theorem
∫ a b f ( x ) d x = F ( b ) − F ( a ) \int_a^b f(x)\,dx = F(b) - F(a) ∫ a b f ( x ) d x = 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 ) ] ≈ 1 N ∑ i = 1 N g ( X i ) \mathbb{E}[g(X)] \approx \frac{1}{N} \sum_{i=1}^N g(X_i) E [ g ( X )] ≈ N 1 ∑ 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 } " )
P(20 <= X <= 60): quad=0.60726, cdf=0.60726
E[revenue]: quad=42.42, exact=42.42, MC=42.46
A function f f f is convex if f ( t x + ( 1 − t ) y ) ≤ t f ( x ) + ( 1 − t ) f ( y ) f(tx + (1-t)y) \le t f(x) + (1-t) f(y) f ( t x + ( 1 − t ) y ) ≤ t f ( x ) + ( 1 − t ) f ( y ) for t ∈ [ 0 , 1 ] t \in [0, 1] t ∈ [ 0 , 1 ] (equivalently, H f ( x ) ⪰ 0 H_f(x) \succeq 0 H f ( x ) ⪰ 0 everywhere). Every local minimum of a convex function is a global minimum; if H f ( x ) ≻ 0 H_f(x) \succ 0 H f ( x ) ≻ 0 (strictly convex ), the global minimum is unique.
To minimize f ( x ) f(x) f ( x ) subject to g ( x ) = 0 g(x) = 0 g ( x ) = 0 , form the Lagrangian L ( x , λ ) = f ( x ) + λ g ( x ) \mathcal{L}(x, \lambda) = f(x) + \lambda g(x) L ( x , λ ) = f ( x ) + λ g ( x ) and solve ∇ x L = 0 , g ( x ) = 0 \nabla_x \mathcal{L} = 0, \, g(x) = 0 ∇ x L = 0 , g ( x ) = 0 — meaning ∇ f ( x ∗ ) \nabla f(x^*) ∇ f ( x ∗ ) is parallel to ∇ g ( x ∗ ) \nabla g(x^*) ∇ g ( x ∗ ) (contours are tangent). For inequality constraints g ( x ) ≤ 0 g(x) \le 0 g ( x ) ≤ 0 , the KKT conditions add dual feasibility (λ ≥ 0 \lambda \ge 0 λ ≥ 0 ) and complementary slackness (λ g ( x ∗ ) = 0 \lambda g(x^*) = 0 λ g ( x ∗ ) = 0 ). In regularization, the L 1 L_1 L 1 diamond ∥ w ∥ 1 ≤ t \Vert w \Vert_1 \le t ∥ w ∥ 1 ≤ t has sharp corners on the axes (driving exact zeros in Lasso), while the L 2 L_2 L 2 sphere ∥ w ∥ 2 2 ≤ t \Vert w \Vert_2^2 \le t ∥ w ∥ 2 2 ≤ t shrinks weights smoothly (Ridge).
# Minimize (w0 - 2)^2 + (w1 - 1)^2 subject to w0^2 + w1^2 <= 1 (L2 ball)
lambda w: (w[ 0 ] - 2.0 ) ** 2 + (w[ 1 ] - 1.0 ) ** 2 ,
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)
constrained optimum: [0.8944 0.4472] norm: 1.0
Optimizer
Update rule
Order
Strengths / Best for
Gradient Descent (GD)
w ← w − η g w \leftarrow w - \eta g w ← w − η g
1st
simple; slow in ill-conditioned valleys
SGD + Momentum
v ← β v + g v \leftarrow \beta v + g v ← β v + g , w ← w − η v w \leftarrow w - \eta v w ← w − η v
1st
damps oscillations; strong generalization on vision CNNs
RMSProp
s ← β s + ( 1 − β ) g 2 s \leftarrow \beta s + (1-\beta) g^2 s ← β s + ( 1 − β ) g 2 , w ← w − η s + ϵ g w \leftarrow w - \frac{\eta}{\sqrt{s}+\epsilon} g w ← w − s + ϵ η g
1st
scales step size per coordinate
Adam
bias-corrected 1st (m m m ) and 2nd (v v v ) moments of g g g
1st
default for deep learning; use AdamW for weight decay
Newton’s method
w ← w − H − 1 g w \leftarrow w - H^{-1} g w ← w − H − 1 g
2nd
quadratic convergence; O ( d 3 ) O(d^3) O ( d 3 ) Hessian solve limits d d d
L-BFGS / L-BFGS-B
approximates H − 1 g H^{-1} g H − 1 g from last m m m steps
quasi-2nd
O ( m d ) O(md) O ( m d ) 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 ])
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)
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 ])
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 } " )
Newton (5): loss=0.413856
L-BFGS (8): loss=0.413856
Mode
Propagates
Cost for f : R d → R m f: \mathbb{R}^d \to \mathbb{R}^m f : R d → R m
Used for
Finite differences
perturbed function evaluations
O ( d ) O(d) O ( d ) evals, truncation/roundoff error
gradient checking only
Forward-mode AD
tangents v ˙ = ∂ v / ∂ x i \dot{v} = \partial v / \partial x_i v ˙ = ∂ v / ∂ x i (dual numbers)
O ( d ) O(d) O ( d ) passes
few inputs, many outputs (d ≪ m d \ll m d ≪ m )
Reverse-mode AD (backprop)
adjoints v ˉ = ∂ L / ∂ v \bar{v} = \partial L / \partial v v ˉ = ∂ L / ∂ v in reverse topo order
O ( m ) O(m) O ( m ) passes (1 1 1 pass for scalar loss)
neural networks (d ≫ 1 , m = 1 d \gg 1, m = 1 d ≫ 1 , m = 1 )
"""Minimal reverse-mode autograd scalar node."""
def __init__ (self, data: float , children: tuple[ "Value" , ... ] = ()) -> None :
self ._backward = lambda : None
self ._prev = set (children)
def __add__ (self, other: "Value" ) -> "Value" :
out = Value( self .data + other.data, ( self , other))
def __mul__ (self, other: "Value" ) -> "Value" :
out = Value( self .data * other.data, ( self , other))
self .grad += other.data * out.grad
other.grad += self .data * out.grad
def backward (self) -> None :
def build (node: Value) -> None :
for node in reversed (topo):
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
print ( f "loss= { loss.data :.1f } , da= { a.grad :.1f } , db= { b.grad :.1f } , dc= { c.grad :.1f } " )
loss=1.0, da=6.0, db=-4.0, dc=-2.0
Trap
Symptom
Fix
choosing finite-difference h = 10 − 12 h = 10^{-12} h = 1 0 − 12
catastrophic cancellation gives noisy gradients
use centered difference with h ≈ 10 − 5 h \approx 10^{-5} h ≈ 1 0 − 5 to 10 − 6 10^{-6} 1 0 − 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