Tree models, neural networks, and SGD

Adapted from the course book: Tree Models, Neural Networks, Gradient Descent

Vadim Sokolov

George Mason University

Plan

  • Trees: splitting, pruning, classification trees, bagging, random forests, boosting
  • Neural networks: layers, activations, worked examples
  • Gradient descent: learning rate, SGD, automatic differentiation, momentum and Adam
  • All figures and formulas are from the book

Tree models

Trees as nested if-else rules

  • A predictive tree is a nested sequence of if-else statements that map an input xx to a predicted output yy
  • Each statement checks one feature of xx and sends the data left or right
  • At the end of the branch, a single value of yy is predicted
  • Prediction: traverse from the root to a leaf following the conditions

Elementary tree scheme; visualization of the splitting process.

Three components of building a tree

  1. Splitting: divide the training data into subsets by the value of a single feature, as homogeneous as possible
  2. Stopping: decide when to stop splitting, as accurate as possible without overfitting
  3. Pruning: remove nodes that do not improve accuracy, to get a smaller tree that predicts new data as well as the full one
  • At each step choose a feature index jj and a split location
  • Regression trees: best split minimizes the sum of squared errors
  • Classification trees: best split minimizes the Gini impurity

Example data: diamonds

  • 53,940 diamonds, 10 variables
Variable Description Values
carat Weight of the diamond Numeric
cut Quality of the cut Fair, Good, Very Good, Premium, Ideal
color Color of the diamond J, I, H, G, F, E, D
clarity Clarity of the diamond I1, SI2, SI1, VS2, VS1, VVS2, VVS1, IF
price Price in US dollars Numeric
  • Also in the data: depth, table, x, y, z

Regression tree for diamond price

Regression tree for price on carat and clarity. Each node shows the mean price and the share of diamonds.

Prediction regions of the tree

  • Each tile is one combination of carat and clarity, colored by predicted price
  • Carat is the strongest predictor: vertical bands of similar shades
  • The tree creates rectangular regions with sharp boundaries

Predicted price of the two-predictor tree on a grid of carat and clarity.

Building a tree via recursive binary splitting

  • Predictor space is divided into JJ non-overlapping boxes R1,…,RJR_1, \ldots, R_J
  • Prediction in box RjR_j is the mean of the training responses in it f(x)=y‾j, for x∈Rj, where y‾j=Average(yi∣xi∈Rj) f(x) = \bar y_j, \text{ for } x \in R_j, \text{ where } \bar y_j = \text{Average}(y_i \mid x_i \in R_j)
  • Goal: minimize the total residual sum of squares (RSS) RSS=∑j=1J∑i∈Rj(yi−y‾j)2→minimize \mathrm{RSS} = \sum_{j=1}^J\sum_{i \in R_j}(y_i - \bar{y}_j)^2 \rightarrow \mathrm{minimize}
  • Considering every partition into JJ boxes is NP-hard, so use the top-down CART algorithm

The splitting rule

  • At each step choose the variable jj and the split point ss R1(j,s)={x∣xj<s} and R2(j,s)={x∣xj≥s} R_1(j, s) = \{x\mid x_j < s\} \mbox{ and } R_2(j, s) = \{x\mid x_j \ge s\}
  • Regression tree: minimize minj,s[∑i:xi∈R1(yi−y‾1)2+∑i:xi∈R2(yi−y‾2)2] \min_{j,s}\left[ \sum_{i:x_i\in R_1}(y_i - \bar{y}_1)^2 + \sum_{i:x_i \in R_2}(y_i - \bar{y}_2)^2\right]
  • Here y‾1\bar y_1 and y‾2\bar y_2 are the mean responses in R1R_1 and R2R_2
  • Every observed input point belongs to a single region

Pruning: taming an overfit tree

  • nn regions: works like one-nearest neighbor. One region: every prediction is the average of the yy’s
  • Number of regions controls complexity on the variance-bias scale
  • Grow an extensive tree T0T_0, then trim to a subtree, with size chosen by cross-validation
  • Cost complexity (weakest link) pruning: for each α≥0\alpha \ge 0 find the subtree T⊂T0T \subset T_0 that minimizes ∑m=1|T|∑i:xi∈Rm(yi−y‾m)2+α|T| \sum_{m=1}^{|T|}\sum_{i:x_i\in R_m}(y_i - \bar{y}_m)^2 + \alpha |T|
  • |T||T| is the number of leaves, y‾m\bar y_m the mean in region RmR_m, α\alpha the tuning parameter
  • Raising α\alpha from zero prunes branches in sequence; pick α̂\hat \alpha by cross-validation, then take the matching subtree from the full data

Boston housing: pruned tree for medv on lstat

  • medv: median value of owner-occupied homes in $1000s. lstat: lower status of the population percent
  • Grow a big tree, then prune it down to one with 7 leaves

Pruned tree.

Step function fit, with cutpoints as dashed lines.

Two predictors: partition and fitted surface

  • dis: weighted mean of distances to five Boston employment centres
  • Tree for medv on dis and lstat

Partition of the (dis, lstat) plane.

Perspective plot of the tree prediction of medv over dis and lstat.

Classification trees

  • Prediction by majority vote within the region
  • pmkp_{mk}: proportion of class kk in region mm, with NmN_m observations in the region and RmR_m the region pmk=1Nm∑xi∈RmI(yi=k) p_{mk} = \dfrac{1}{N_m}\sum_{x_i \in R_m} I(y_i=k)
  • pmp_m: proportion of the most frequent class. EmE_m: error rate, the share not in the majority class pm=maxkpmk,Em=1−pm p_m = \max_k p_{mk},~~~ E_m = 1-p_m
  • Predicted class probability P(y=k∣x)=∑m=1JpmkI(x∈Rm) P(y=k \mid x) = \sum_{m=1}^J p_{mk} I(x \in R_m)

Gini index and cross-entropy

  • Example: 400 observations in each of two classes. Tree A has regions (300,100) and (100,300). Tree B has regions (200,400) and (200,0)
  • Both have misclassification rate 0.25, but B is more desirable: region (200,0) is pure
  • Gini index and cross-entropy are more sensitive to node purity
  • Gini index (KK classes): a variance across classes, small if all pmkp_{mk} are close to zero or one Gm=∑k=1Kpmk(1−pmk) G_m = \sum_{k=1}^K p_{mk}(1-p_{mk})
  • Cross-entropy (deviance): near zero if all pmkp_{mk} are near zero or one Dm=−∑k=1Kpmklogpmk D_m = -\sum_{k=1}^Kp_{mk}\log p_{mk}
  • Gini and cross-entropy lead to similar results

Example: classifying diamond quality

  • Binary problem: “Ideal” cut against others, from price, carat and clarity

Classification tree for an Ideal cut. Each node shows the predicted class, the probability of the Non-Ideal class and the share of diamonds.

Ensemble methods

  • Two alternatives to pruning: Random Forests (averaging many trees) and Boosting (sequentially fitting trees to residuals)
  • The variance of the average is lower than the variance of individual models
  • Combine BB models f1(x),…,fB(x)f_1(x),\ldots,f_B(x) favg(x)=1B∑b=1Bfb(x) f_{avg}(x) = \dfrac{1}{B}\sum_{b=1}^Bf_b(x)
  • Combining models fights overfitting. Cost: harder to interpret than a single tree

Bagging

  • Treat the sample as the population and draw with replacement
  • Take BB bootstrap samples of the same size as the training data
  • Fit a large tree to each sample
  • Combine the BB trees: average for numeric yy, vote or average the probabilities for categorical yy
  • Each bootstrap sample leaves out about 37% of the observations, since (1−1/n)n→e−1(1-1/n)^n \to e^{-1}
  • Out-of-bag (OOB) prediction uses only trees that did not see the observation. OOB error estimates test error without a validation set

Bagging on Boston: 10, 500 and 5,000 trees

  • With 10 trees the fit is too jumbly (high variance). A few points were in every bootstrap sample, so they have no out-of-bag prediction and the curve skips them
  • With 500 and 5,000 trees the fit is smoother and very similar
  • Averaging trees with different cutpoints gives a step function with very many small steps

10 trees.

500 trees.

5,000 trees.

Random forest

  • In bagging the trees become correlated: most use the most influential predictor in the top split, so a 1/B1/B reduction in variance is not achieved
  • Random forests decorrelate the trees: at each split a random sample of mm of the pp predictors is the candidate set, different for each split
  • Typical mm: p\sqrt{p} for classification, p/3p/3 for regression

Random Forest fit (red) on all predictors, in-sample, plotted against lstat.

Variable importance

  • Right panel (IncNodePurity): total decrease in loss (residual sum of squares) due to splits over a predictor, averaged over all trees
  • Left panel (%IncMSE): permutation importance, the increase in out-of-bag mean squared error when the predictor is permuted, averaged over trees and divided by its standard deviation

Variable importance in a Random Forest for the Boston data: permutation importance (left) and total decrease in node impurity (right).

Boosting

  1. Fit a single intentionally weak tree
  2. Examine the residuals, the part of yy the tree does not explain
  3. Fit a new tree to the residuals
  4. Shrink it by a learning rate λ\lambda and add it to the previous trees
  5. Repeat. The final model is the sum of all shrunk trees
  • The key idea: improve the model by focusing on what it does not explain yet

Boosting as gradient descent in function space

  • Minimize a loss ℒ\mathcal{L} over nn observations; for regression ℒ(yi,θi)=12(yi−θi)2\mathcal{L}(y_i , \theta_i ) = \frac{1}{2}(y_i - \theta_i )^2 minimizeβ∈ℝB∑i=1nℒ(yi,∑b=1Bβb⋅Tb(xi))\mathrm{minimize}_{\beta \in \mathbb{R}^B} \sum_{i=1}^n \mathcal{L} \left(y_i, \sum_{b=1}^B \beta_b \cdot T_b(x_i)\right)
  • Here TbT_b are trees and βb\beta_b their weights. Start from θ(0)=T0\theta^{(0)} = T_0, a single tree. Repeat: gi=[∂ℒ(yi,θi)∂θi]|θi=θi(k−1),i=1,…,ng_i = \left.\left[\frac{\partial \mathcal{L}(y_i, \theta_i)}{\partial \theta_i}\right]\right|_{\theta_i = \theta_i^{(k-1)}},\ i=1,\ldots,n minimizetrees T∑i=1n(−gi−T(xi))2\mathrm{minimize}_{\text{trees }T} \sum_{i=1}^n (-g_i - T(x_i))^2 θ(k)=θ(k−1)+λ⋅Tk\theta^{(k)} = \theta^{(k-1)} + \lambda \cdot T_k
  • gg is the gradient at the latest prediction; TkT_k is the tree closest to −g-g

Boosting algorithm

  1. Set f̂(x)=0\hat{f}(x)=0 and ri=yir_i=y_i for all ii in the training set
  2. For b=1,2,…,Bb=1,2,\ldots,B repeat:
    • Fit a tree f̂b\hat{f}^b with dd splits (interactions) to the data (X,r)(X, r)
    • Update f̂(x)←f̂(x)+λf̂b(x)\hat{f}(x) \leftarrow \hat{f}(x) +\lambda \hat{f}^b(x)
    • Update the residuals ri←ri−λf̂b(xi)r_i \leftarrow r_i - \lambda \hat{f}^b(x_i)
  3. Output f̂(x)=∑b=1Bλf̂b(x)\hat{f}(x) = \sum_{b=1}^B \lambda \hat{f}^b(x)
  • λ\lambda: learning rate or shrinkage, e.g., 0.01 or 0.1. A small value prevents adapting too quickly to outliers or noise
  • Example: 5,000 trees, interaction depth 4, gbm default λ=0.1\lambda = 0.1

Partial dependence

  • Partial dependence plots show the effect of the two most influential variables, rm and lstat, on medv after integrating out the others

rm.

lstat.

Boosting versus random forests

  • Boosting: often more accurate by correcting residuals, but more prone to overfitting and noise. Needs careful tuning of λ\lambda and BB
  • Random forests: more robust out of the box, easier to parallelize (trees are independent), less prone to overfitting, may not reach the peak accuracy of well-tuned boosting

Neural networks

Neural networks: the deep predictor

  • Deep learning extends generalized linear models with multiple layers of nonlinear transformations
  • Classical methods are wide and shallow. Deep learning is deep and narrow: many successive transformations, fewer units per layer
  • Let f1,…,fLf_1 , \ldots , f_L be univariate activation functions for the LL layers. A nonlinear activation of an affine transformation: flW,b(Z)=fl(WlZ+bl) f_l^{W,b}(Z) = f_l ( W_l Z + b_l )
  • WlW_l is the weight matrix with NlN_l rows (hidden units of layer ll), blb_l the bias. The deep predictor is the composite map Ŷ(X)=F(X)=(fLWL,bL∘…∘f1W1,b1)(X) \hat{Y}(X) = F(X) = \left ( f_L^{W_L,b_L} \circ \ldots \circ f_1^{W_1,b_1} \right ) ( X)

Layers and hidden features

  • Z(l)Z^{(l)} is the llth layer, X=Z(0)X = Z^{(0)} Ŷ(X)=W(L)Z(L)+b(L)Z(1)=f(1)(W(0)X+b(0))Z(2)=f(2)(W(1)Z(1)+b(1))…Z(L)=f(L)(W(L−1)Z(L−1)+b(L−1)) \begin{aligned} \hat{Y} (X) & = W^{(L)} Z^{(L)} + b^{(L)} \\ Z^{(1)} & = f^{(1)} \left ( W^{(0)} X + b^{(0)} \right ) \\ Z^{(2)} & = f^{(2)} \left ( W^{(1)} Z^{(1)} + b^{(1)} \right ) \\ \ldots & \\ Z^{(L)} & = f^{(L)} \left ( W^{(L-1)} Z^{(L-1)} + b^{(L-1)} \right ) \end{aligned}
  • W(l)W^{(l)}: weight matrix. b(l)b^{(l)}: bias terms that shift the activation functions
  • Z(l)Z^{(l)} are hidden features (latent representations) extracted from the data
  • Layers 11 to LL are hidden layers. LL is the depth

Products and maxima from univariate functions

  • Interactions and thresholds are built from univariate functions of linear projections of the input x1x2=14(x1+x2)2−14(x1−x2)2 x_1x_2 = \frac{1}{4} ( x_1+x_2 )^2 - \frac{1}{4} (x_1-x_2)^2 max(x1,x2)=12(x1+x2)+12|x1−x2| \max(x_1,x_2) = \frac{1}{2} ( x_1+x_2 ) + \frac{1}{2} | x_1-x_2 |
  • This is precisely what neural networks do
  • ReLU compositions: with x+=max(x,0)x^+ = \max(x,0), (fx1∘…∘fxk)(0)=(x1+(x2+…+(xk−1+xk+)+)+)+=max1≤j≤k(x1+…+xj)+ ( f_{x_1} \circ \ldots \circ f_{x_k} ) (0) = ( x_1 + ( x_2 + \ldots + ( x_{k-1} + x_k^+ )^+ )^+ )^+ = \max_{1 \leq j \leq k} ( x_1 + \ldots + x_j )^+
  • A composition of such maps reduces to a single maximum of partial sums

Classification: from logistic regression to four lines

  • Simulated data: the inner cluster is one class, the outer ring the other
  • Logistic regression fails because the data are not linearly separable. Multiple lines can separate the data; apply the logistic function to each line

Logistic regression boundary on the circle data.

Four lines that separate the inner cluster from the outer ring.

First layer and output layer

  • First layer: a 2-dimensional input xx gives a 4-dimensional feature vector zz z=σ(Wx+b),W=[11−1−1−111−1],b=[6666],σ(z)=11+e−z z = \sigma(Wx + b), ~ W = \begin{bmatrix} 1 & 1 \\ -1 & -1 \\ -1 & 1 \\ 1 & -1 \end{bmatrix}, ~ b = \begin{bmatrix} 6 \\ 6 \\ 6 \\ 6 \end{bmatrix}, ~ \sigma(z) = \frac{1}{1+e^{-z}}
  • Output layer: logistic regression on the feature vector; ŷ\hat y is the probability of the inner class ŷ=σ(w⊤z+b),w=[1111],b=−3.1 \hat{y} = \sigma(w^\top z + b), ~ w = \begin{bmatrix} 1 \\ 1 \\ 1 \\ 1 \end{bmatrix}, ~ b = -3.1

Predicted probability on a grid

  • Evaluated on a grid of 10,000 points (100 values for each of the two inputs)

Predicted probability of the inner class on a grid, with the data and the four lines.

Regression: noisy quadratic

  • Simulate from y=0.5+0.3x2+ϵ,ϵ∼N(0,0.022) y = 0.5 + 0.3x^2 + \epsilon, ~ \epsilon \sim N(0,0.02^2)
  • One hidden layer with 3 units and ReLU, one linear output unit, 8 parameters (1 shared hidden bias, 3 weights, 1 output bias, 3 output weights)
  • Fit by BFGS, minimizing the sum of squared errors

Noisy quadratic function approximated by a neural network with ReLU activation function. Solid: network. Broken: hidden units, shifted up by 0.5.

Regression: tanh activation

  • The network did not need an explicit quadratic term; it discovered the structure from the data

Noisy quadratic function approximated by a neural network with tanh activation function. The broken lines are the hidden units, rescaled.

Learning an interaction

  • Data-generating process, with x1,x2x_1, x_2 independent uniform on (−1,1)(-1, 1), 200 observations y=0.5+0.1x1+0.2x2+0.5x1x2+ϵ,ϵ∼N(0,0.022) y = 0.5 + 0.1x_1 + 0.2x_2 + 0.5x_1x_2+ \epsilon, ~ \epsilon \sim N(0,0.02^2)
  • Two inputs, two hidden units with tanh. The model approximately learns the interaction

Interaction data, network output and rescaled hidden units.

Activation functions and ReLU

  • Output layer: sigmoid for binary output, no activation for continuous output
  • Hidden layers: most common are tanh and ReLU tanh(z)=ez−e−zez+e−z,tanh(z)=2σ(2z)−1 \tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}}, ~~ \tanh(z) = 2\,\sigma(2z) - 1
  • Sigmoid and tanh saturate at extreme inputs, where the gradient is nearly zero. Gradients multiply across layers and become negligible: the vanishing gradient problem

ReLU(z)=max(0,z),ReLU′(z)={0if z<01if z>0 \text{ReLU}(z) = \max(0,z), ~~ \text{ReLU}'(z) = \begin{cases} 0 & \text{if } z < 0 \\ 1 & \text{if } z > 0 \end{cases}

  • ReLU is piecewise linear, efficient, the most commonly used activation. Not differentiable at z=0z=0. Softplus log(1+ez)\log(1+e^z) is a smooth ReLU. Leaky ReLU: max(0.1z,z)\max(0.1z, z)

tanh

ReLU

softplus

sigmoid

Gradient descent

Gradient descent

  • Second-order methods (least squares, BFGS) use the Hessian and do not scale to millions of parameters. First-order methods need only the gradient
  • Parameter estimation is optimization, with ll the negative log-likelihood and θ\theta the parameter vector minθl(θ):=−1n∑i=1nlogp(yi∣xi,θ) \min_{\theta} l(\theta) := -\dfrac{1}{n} \sum_{i=1}^n \log p(y_i \mid x_i, \theta)
  • Start at θ0\theta^{0}; at iteration tt, with learning rate αt\alpha_t, θt+1=θt−αt∇l(θt),∇l(θt)=(∂l∂θ0,…,∂l∂θp) \theta^{t+1} = \theta^t - \alpha_t \nabla l(\theta^t), ~~ \nabla l(\theta^t) = \left(\frac{\partial l}{\partial \theta_0}, \ldots,\frac{\partial l}{\partial \theta_p}\right)
  • The negative gradient points in the direction of steepest descent

Non-differentiable points

  • Derivative: l′(θ)=limh→0l(θ+h)−l(θ)hl'(\theta) = \lim_{h \to 0} \frac{l(\theta+h) - l(\theta)}{h}, the slope of the tangent line
  • f(θ)=|θ|f(\theta) = |\theta| has a sharp corner at zero: derivative +1+1 for θ>0\theta > 0, −1-1 for θ<0\theta < 0, undefined at zero
  • ReLU max(0,x)\max(0, x) has such a point, yet gradient descent still works:
    • the probability of landing exactly on it is zero for continuous distributions
    • at a kink, software uses one of the one-sided derivatives

Learning rate

  • Too small: slow convergence. Too large: divergence or oscillation
  • For l(θ)=θ2l(\theta) = \theta^2 from θ0=2\theta_0 = 2: α=0.5\alpha = 0.5 converges in one step, α=0.25\alpha = 0.25 more slowly, α=1\alpha = 1 overshoots

α=1\alpha=1 (too large)

α=0.5\alpha=0.5 (ideal)

α=0.25\alpha=0.25 (working)

Deep learning and least squares

  • Training data D={xi,yi}i=1nD = \{x_i,y_i\}_{i=1}^n, model fθ(x)f_{\theta}(x), loss is the negative log-likelihood l(θ)=−∑i=1nlogp(yi∣xi,θ) l(\theta) = - \sum_{i=1}^n \log p(y_i \mid x_i, \theta)
  • Regression: yi=fθ(xi)+ϵi,ϵi∼N(0,σ2)y_i = f_{\theta}(x_i) + \epsilon_i, ~ \epsilon_i \sim N(0,\sigma^2). Dropping the constant nlog(σ2π)n\log(\sigma\sqrt{2\pi}), l(θ)∝∑i=1n(yi−fθ(xi))2 l(\theta) \propto \sum_{i=1}^n (y_i - f_{\theta}(x_i))^2

Example: linear regression by gradient descent

  • A degenerate neural network: one layer, no hidden units, identity activation
  • Model yi=θ0+θ1xi+ϵiy_i = \theta_0 + \theta_1 x_i + \epsilon_i, or y=Xθ+ϵy = X \theta + \epsilon, with design matrix X=[1x]X = [1 ~ x] (first column all ones)
  • Data: iris, y=y = Petal.Length, x=x = Petal.Width l(θ)=∑i=1n(yi−θ0−θ1xi)2,∇l(θ)=−2X⊤(y−Xθ) l(\theta) = \sum_{i=1}^n (y_i - \theta_0 - \theta_1 x_i)^2, ~~ \nabla l(\theta) = -2 X^\top (y - X \theta)

Example: logistic regression

  • Logit link, pp the probability of the positive class; the loss is the cross-entropy l(θ)=−∑i=1n[yilogpi+(1−yi)log(1−pi)] l(\theta) = - \sum_{i=1}^n \left[ y_i \log p_i + (1-y_i) \log (1-p_i) \right]
  • With pi=1/(1+exp(−θ0−θ1xi1−…−θpxip))p_i = 1/\left(1 + \exp(-\theta_0 - \theta_1 x_{i1} - \ldots - \theta_p x_{ip})\right) the gradient is ∇l(θ)=−X⊤(y−p) \nabla l(\theta) = - X^\top (y - p)

Logistic regression fitted by gradient descent on iris.

Stochastic gradient descent

  • Replace the full-data gradient with the gradient over a random batch B⊆{1,2,…,n}B \subseteq \{1,2,\ldots,n\}, with batch size |B||B| ∇l(θ)≈1|B|∑i∈B∇l(yi,f(xi,θ)) \nabla l(\theta) \approx \dfrac{1}{|B|} \sum_{i \in B} \nabla l(y_i, f(x_i, \theta))
  • Gradient descent with noisy gradients (mini-batch gradients). Works when data do not fit in memory
  • Rooted in stochastic approximation (Robbins and Monro, 1951): the expected gradient is replaced by its Monte Carlo approximation
  • Mini-batch regime: |B|≪n|B| \ll n, typically |B|∈{32,64,…,1024}|B| \in \{32,64,\ldots,1024\}

SGD: batch size

  • Shuffle the data first: sorted data make batches correlated and slow convergence
  • Larger batches need more memory, parallelize better and give less noisy gradients
  • For non-convex objectives, noisier gradients (small batches) often give higher-quality solutions

Intercept θ0\theta_0 for batch sizes 5, 15, 30 (dashed line: 27.83), by iteration and by computation (thousands of iterations with batch size 5):

Automatic differentiation: four ways to differentiate

  • By hand: slow and error-prone
  • Numerical: f′(x)≈(f(x+h)−f(x))/hf'(x) \approx (f(x+h)-f(x))/h. Large hh gives truncation error, small hh gives rounding error
  • Symbolic: analytical expression of the derivative
  • Automatic differentiation (AD): recursively applies the chain rule and gives the exact derivative value at a specific point, from code (including if statements and loops)
  • Example: the logistic function f(x)=11+e−(Wx+b) f(x) = \frac{1}{1+e^{-(Wx+b)}}
sigmoid = function(x,b,w){
  v1 = w*x
  v2 = v1 + b
  v3 = 1/(1+exp(-v2))
}

Chain rule for the sigmoid

  • With σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z}), σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1-\sigma(z)) ∂f∂w=∂v3∂v2⋅∂v2∂v1⋅∂v1∂w=v3(1−v3)⋅1⋅x \frac{\partial f}{\partial w} = \frac{\partial v_3}{\partial v_2} \cdot \frac{\partial v_2}{\partial v_1} \cdot \frac{\partial v_1}{\partial w} = v_3(1-v_3) \cdot 1 \cdot x ∂f∂b=∂v3∂v2⋅∂v2∂b=v3(1−v3)⋅1 \frac{\partial f}{\partial b} = \frac{\partial v_3}{\partial v_2} \cdot \frac{\partial v_2}{\partial b} = v_3(1-v_3) \cdot 1
  • Here v1=wxv_1 = wx, v2=v1+bv_2 = v_1 + b, v3=fv_3 = f

Forward mode

  • An auxiliary dual variable tracks the derivative on each line. Take x=2, w=3, b=-5
Function calculations Derivative calculations
1. v1 = w*x = 6 1. dv1 = w = 3 (derivative of v1 with respect to x)
2. v2 = v1 + b = 1 2. dv2 = dv1 = 3 (derivative of v2 with respect to x)
3. v3 = 1/(1+exp(-v2)) = 0.731 3. dv3 = dv2*v3*(1-v3) = 0.590
  • dv1, dv2, dv3 are the derivatives of v1, v2, v3 with respect to xx, called dual variables
  • Implemented by source code modification or operator overloading

Reverse mode

  • Applies the chain rule recursively, starting from the outer function
Function calculations Derivative calculations
1. v1 = w*x = 6 4. dv1 = dv2*dv2dv1 = 0.197; df/dx = dv1*w = 0.590
2. v2 = v1 + b = 1 3. dv2dv1 = 1; dv2 = dv3*dv3dv2 = 0.197
3. v3 = 1/(1+exp(-v2)) = 0.731 2. dv3 = dv4 = 1; dv3dv2 = v3*(1-v3) = 0.197
4. v4 = v3 1. dv4 = 1

Forward versus reverse mode

  • Forward mode: propagates derivatives with the computation, from inputs to outputs. Efficient when the number of inputs is less than the number of outputs
  • Reverse mode: propagates derivatives against the computation, from outputs to inputs. Efficient when the number of outputs is less than the number of inputs
  • A neural network has millions of parameters (inputs to the loss) and one scalar loss (one output), so reverse mode is dramatically more efficient
  • In neural networks, reverse AD is called backpropagation

Computational graph

  • Single sigmoid unit, composition of affine and sigmoid functions
  • Numbers in the nodes are values at a specific point. Solid arrows: forward pass, from inputs (x, w, b) to the output v3. Dashed arrows: backward pass, gradient values flow from the output back to the inputs

Computational Graph for Sigmoid Function

Backpropagation in practice

  • For deep learning, derivatives come from reverse AD applied to a model defined as a composition of functions
  • PyTorch defines the model in a general-purpose language, TensorFlow through a sequence of function calls
  • PyTorch relies on the autograd library, which finds gradients by backpropagation
  • Delta rule for a single-layer perceptron with ŷ=σ(w⊤x+b)\hat{y} = \sigma(w^\top x + b), squared-error loss (ŷ−y)2/2(\hat{y}-y)^2/2 and learning rate α\alpha wt+1=wt−α(ŷ−y)σ′(w⊤x+b)x w^{t+1} = w^t - \alpha (\hat{y} - y) \sigma'(w^\top x + b) x
  • For a hidden layer h=σ1(W1x+b1)h = \sigma_1(W_1 x + b_1), ŷ=σ2(W2h+b2)\hat{y} = \sigma_2(W_2 h + b_2) and loss LL, the chain rule gives ∂L∂W1=∂L∂ŷ⋅∂ŷ∂h⋅∂h∂W1 \frac{\partial L}{\partial W_1} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial h} \cdot \frac{\partial h}{\partial W_1}

Momentum

  • Vanilla SGD does not guarantee descent at every iteration; progress can be slow when gradients are noisy
  • Momentum adds memory by combining new gradient information with previous search directions. vv is the velocity, tkt_k the step size, gg the gradient, (W,b)(W,b) the parameters vk+1=μvk−tkg((W,b)k),(W,b)k+1=(W,b)k+vk+1 v^{k+1} = \mu v^k - t_k g((W,b)^k), ~~ (W,b)^{k+1} = (W,b)^k + v^{k+1}
  • μ\mu controls the damping of the update
  • Nesterov momentum: gradient at the point predicted by the momentum (look-ahead) vk+1=μvk−tkg((W,b)k+μvk),(W,b)k+1=(W,b)k+vk+1 v^{k+1} = \mu v^k - t_k g((W,b)^k + \mu v^k), ~~ (W,b)^{k+1} = (W,b)^k + v^{k+1}

Adaptive learning rates

  • AdaGrad scales the learning rate per parameter by the history of gradients, cc the accumulated squared gradient and ϵ\epsilon a small constant (e.g., 10−810^{-8}) ck+1=ck+g(θk)2,θk+1=θk−tkck+1+ϵg(θk) c^{k+1} = c^k + g(\theta^k)^2, ~~ \theta^{k+1} = \theta^k - \frac{t_k}{\sqrt{c^{k+1}} + \epsilon} g(\theta^k)
  • RMSprop uses an exponentially weighted moving average, with decay ρ\rho ck+1=ρck+(1−ρ)g(θk)2 c^{k+1} = \rho c^k + (1-\rho) g(\theta^k)^2
  • Adam combines RMSprop with momentum, with first moment mm and second moment cc mk+1=β1mk+(1−β1)g(θk),ck+1=β2ck+(1−β2)g(θk)2 m^{k+1} = \beta_1 m^k + (1-\beta_1) g(\theta^k), ~~ c^{k+1} = \beta_2 c^k + (1-\beta_2) g(\theta^k)^2 θk+1=θk−tkĉk+1+ϵm̂k+1 \theta^{k+1} = \theta^k - \frac{t_k}{\sqrt{\hat{c}^{k+1}} + \epsilon} \hat{m}^{k+1}
  • Bias-corrected: m̂k+1=mk+1/(1−β1k+1)\hat{m}^{k+1} = m^{k+1}/(1-\beta_1^{k+1}), ĉk+1=ck+1/(1−β2k+1)\hat{c}^{k+1} = c^{k+1}/(1-\beta_2^{k+1}), m0=c0=0m^0 = c^0 = 0. Typical β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}

Summary of optimizers

Method Key Idea Update Rule
SGD Noisy gradient estimates θk+1=θk−tkgk\theta^{k+1} = \theta^k - t_k g^k
Momentum Accumulate gradient direction vk+1=μvk−tkgkv^{k+1} = \mu v^k - t_k g^k; θk+1=θk+vk+1\theta^{k+1} = \theta^k + v^{k+1}
Nesterov Look-ahead gradient vk+1=μvk−tkg(θk+μvk)v^{k+1} = \mu v^k - t_k g(\theta^k + \mu v^k); θk+1=θk+vk+1\theta^{k+1} = \theta^k + v^{k+1}
AdaGrad Per-parameter learning rates Scale by 1/∑g21/\sqrt{\sum g^2}
RMSprop Exponential moving average Scale by 1/EMA(g2)1/\sqrt{\text{EMA}(g^2)}
Adam Momentum + adaptive rates Combines first and second moment estimates
  • Second-order (Newton): θ+=θ−{∇2f(θ)}−1∇f(θ)\theta^{+} = \theta - \{ \nabla^2 f(\theta) \}^{-1} \nabla f(\theta). SGD approximates the inverse Hessian by tkIt_k I, with II the identity. Rarely used in deep learning because the Hessian is too large to compute and store