A training table with ten million rows makes every step of gradient descent expensive, because the exact gradient of the training objective averages one gradient per row. Stochastic gradient descent takes a step after reading only a few rows. Can such a cheap step still lead to a minimizer, and how would we notice if it does not? This lesson shows in what sense a mini-batch gradient is a correct estimate, what epochs and learning-rate schedules control, why feature scaling decides which step sizes work, and which evidence separates ordinary noise from a failed training run.
Key terms
Full-batch gradient descent
Definition Let the training objective be the empirical risk
the average over the training examples of the loss of the model with parameters on example , where every is differentiable. Full-batch gradient descent starts at a vector and repeats
with a learning rate , so each update evaluates all example gradients at the current parameters. For a linear model with half squared loss , the gradient of one example is its residual, prediction minus target, times its feature vector,
and is a quadratic with Hessian . When is positive definite, gradient descent with a constant rate converges to the unique minimizer from every starting point exactly when , where is the largest eigenvalue of .
In plain words Each step uses the exact slope of the training objective, so the path is deterministic, and each step costs a full pass over the data. The rate has to suit the most sharply curved direction. If one feature is recorded on a much larger scale than another, the objective is sharply curved in one direction and nearly flat in another, and a rate small enough to stay stable in the sharp direction crawls in the flat one. Standardizing the features balances the curvature. The means and standard deviations it uses are computed from the training rows only and reused unchanged on validation, test and future rows. A training column with standard deviation zero cannot be divided by it, so the pipeline needs a stated policy, such as using a scale of for that column, which leaves a centered column of zeros, or dropping the column.
Example Four constructed training rows have features , , and and targets , , and . The training means of the features are and , and their standard deviations with divisor are and . Take the intercept to be the training mean of the targets and fit two coefficients to the centered targets , , and , starting from , where . With centered but unscaled features, is diagonal with entries and , the gradient at is , and one step with gives and . Stability would need . After standardization the four rows are , , and , the Hessian is the identity, the gradient at is and the same step gives and . With this rate every step multiplies by , so twenty steps leave about . Both coordinate systems describe the same prediction rules, and the exact fit is in the original units.
Stochastic gradient
Definition A stochastic gradient is an estimate of computed from training examples chosen at random. The simplest one fixes , draws an index uniformly from and uses . Each index has probability , so
and the estimate is unbiased. Inside an algorithm the same argument gives conditionally on everything that happened before update , provided each index is drawn afresh and independently of all earlier draws. It does not hold for every batch of an epoch that walks through one shuffled order, because given the earlier batches of that epoch, the later ones can contain only examples not yet used.
In plain words One example’s gradient is a noisy guess of the full gradient. Averaged over the random choice it is exactly right, but a single draw can point the wrong way, and the step it produces can then raise the training objective.
Example A constant predictor is fitted to the targets , and with , so is smallest at the mean . At the example gradients are , and , and the full gradient is their mean, . With the full-batch step moves to and lowers from to . If the first example is drawn, the gradient is , the step moves to , and rises to . The three possible one-example steps end at , and , and their average is the full-batch result .
Mini-batch
Definition A mini-batch is a selection of training examples with , and the mini-batch gradient is
averaged over the actual number of examples in . With it is a one-example stochastic gradient, and with all examples it is the full gradient. Let be the covariance matrix of a one-example stochastic gradient, the average of over the examples at . When the indices are drawn independently and uniformly with replacement, the mini-batch gradient is unbiased with covariance . When is a uniformly random set of distinct examples and , it is still unbiased, and its covariance is
which is zero when .
In plain words Averaging several gradients cancels part of their noise. Under sampling with replacement, the variance of each coordinate falls in proportion to and its standard deviation in proportion to , so four times the batch size halves the typical size of the noise while each update costs about four times as much computation. When does not divide , the last batch of an epoch is smaller, and its summed gradient must be divided by its own size.
Example For the targets , and at , the one-example gradients , and have mean and variance . A batch of two indices drawn with replacement has variance . The three sets of two distinct examples have batch gradients , and , with mean and variance , which equals as the formula predicts. The set of the first two examples still gives a gradient of the wrong sign.
Stochastic gradient descent
Definition Stochastic gradient descent (SGD) starts at and repeats
where is the gradient of a mini-batch evaluated at the current parameters and is the learning rate of update . The name covers the one-example version and the mini-batch versions. In the version whose gradients are unbiased given the past, each is drawn afresh, uniformly and independently of earlier batches. In common practice the training rows are shuffled at the start of every epoch and taken in consecutive batches. An epoch is one pass through the training examples. When an epoch walks through a shuffled order with batch size , it has updates, while full-batch gradient descent makes one update per epoch.
In plain words SGD trades exact steps for cheap ones and makes many updates in the time full-batch descent makes one. Runs that differ only in the random seed follow different paths and can stop at different parameters. That spread is randomness of the optimizer on fixed training data. It is not uncertainty about future outcomes, and it does not measure how much the fitted model would change with a new training sample. Fixing the seed makes the shuffles repeatable on the same software, but library versions, hardware and parallel execution can still change the results.
Example Take the standardized four-row example with batch size , and . Suppose the first shuffle orders the rows as 2, 3, 1, 4. Rows 2 and 3 have centered target and prediction , so the first batch gradient is and nothing moves. Rows 1 and 4 have residuals and , so the second batch gradient is , the step gives , and falls to after the first epoch, against after one full-batch step. In one seeded run of twenty epochs the mini-batch version reaches with updates and the full-batch version with updates, although both evaluate example gradients. That ranking belongs to this tiny constructed problem and is not a general guarantee.
Learning-rate schedule
Definition A learning-rate schedule is a rule that sets the rate for each update . A constant schedule keeps . A common decreasing schedule is
with and , and step decay, which multiplies the rate by a fixed factor after a fixed number of updates or epochs, is another. The counter has to be stated. A schedule written in epochs gives a different sequence of rates per update when the batch size changes, because an epoch then contains a different number of updates. The rate also depends on how the objective is normalized, since the gradient of a sum of losses is times the gradient of their average.
In plain words Large early steps make fast progress far from a minimizer, and small later steps damp the noise of stochastic gradients near one. With a constant rate, SGD cannot settle on a minimizer unless every example gradient is zero there, and with a small constant rate it keeps moving around near one.
Example With and , the rate is at update , at update and about at update . On training rows one epoch has updates with batch size but only updates with batch size . After one epoch the first run has reached the rate , while the second is still at about .
Convergence
Definition A sequence of parameter vectors converges to if as . SGD produces random iterates, so its convergence results are probability statements, such as convergence with probability one or , and each holds only under stated assumptions. For full-batch descent on a quadratic with positive definite Hessian, the condition suffices. Classical stochastic approximation results for SGD use rates with
together with conditions on the objective and the gradient noise, for example a strongly convex objective with Lipschitz continuous gradient and stochastic gradients that are unbiased given the past and have suitably bounded second moments. The schedule meets both step conditions, and a constant rate fails the second. For nonconvex objectives, such as the losses of neural networks, results of this kind concern stationary points rather than a global minimum. In practice “the run converged” often means only that a stopping rule was met, such as a small change of the full training objective over several checkpoints.
In plain words Convergence is a claim about a limit, and the step conditions alone do not establish it. To monitor a run, evaluate the full training objective at fixed checkpoints instead of comparing the loss of one batch with the loss of a different batch, since an easy batch can look better while the model has become worse. Signs of failure are nonfinite values, a full training objective that keeps growing across checkpoints, and oscillations whose size grows. A noisy trace of batch losses is not by itself a failure, and a smooth falling training curve does not show that the model will do well on new data. Batch size and schedule are development choices, so compare them on validation data and keep the test set for the final evaluation.
Example For the targets , and , one-example SGD with the constant rate gives . The sampled target has variance , so the variance of obeys and approaches , a standard deviation of about around the minimizer that never dies out. The schedule , which is with , makes the average of the first sampled targets for every . Its variance is , and by the law of large numbers it converges to with probability one. The four-row regression converged with a constant rate because its model fits every training row exactly, which makes every example gradient zero at the minimizer.
Check yourself
- A training set has rows and is reshuffled every epoch into batches of size , with a smaller last batch. How many updates does one epoch contain, how many do five epochs contain, and by what number should the summed gradient of the last batch be divided?
Show the answer
The batches have sizes , and , so one epoch has updates and five epochs have . The summed gradient of the last batch is divided by , its actual size. Dividing it by would make that step half as large as the averaged objective calls for. Full-batch gradient descent would make only updates in five epochs, each reading all rows.
- A constant predictor has the targets and and the objective . Start at with . Find the full-batch update, the two possible one-example updates when each example is drawn with probability , and their average. Does each one-example step lower ?
Show the answer
The objective is the average of , so the example gradients at are and and the full gradient is . The full-batch update is . The one-example updates are and , and their average is , the full-batch update, as unbiasedness at a fixed starting point requires. Since , and , both steps lower here, because both example gradients have the same sign as the full gradient. With the targets , and one possible step raised . The equality of averages concerns this single step from a fixed start. After it, the stochastic path does not follow the full-batch path.
- In the four-row example, a run on centered but unscaled features with reports values of , and about after zero, one and two updates. Does this show that a linear model cannot fit these data? Which constant rates would converge, and what would you change?
Show the answer
No. The coefficients and on the centered features fit every row exactly, with , which is in the original units. The Hessian is diagonal with entries and , so with the error in the second coordinate is multiplied by at every step and the run diverges. That is a failure of the step size, not of the model. A constant rate converges only when , and then the error in the first coordinate shrinks by the factor per step, so a tenfold reduction takes more than 11,500 steps. Standardizing the features with the training means and standard deviations makes the Hessian the identity. Every rate with then converges, and multiplies by per step. The same saved scaling is then applied to validation and test rows.