Learning From a Few Records at a Time
Botie has more training records than he can process in one step. A batch gives him a manageable estimate of the direction in which to change the model.
13 sections · 4 questions · 2 coding challenges
The arrow keys move between sections too.
Trading an Exact Gradient for a Useful Estimate
BOTIE
This lesson isolates the gradient of a mean squared-error objective with a one-half factor. Our tiny batches make every contribution visible; the same averaging principle applies to gradients obtained through backpropagation.
Sources for this history
Must We Read Every Record Before Changing One Weight?
Botie’s prediction model has one weight, but the records keep growing. Calculating the effect of every record before each update can become expensive.
Using a smaller batch means we can make an update before reading the entire dataset. But different batches may suggest different directions. We will calculate the contribution from each observation first, then see how averaging a batch affects the update, including a short batch at the end of an epoch.
This small regression batch uses half mean squared error.
Step 1 of 3
Predict with the current weight
Each row gives an input and a target.
| Observation | Input x | Target y | Prediction (1 × x) |
|---|---|---|---|
| 1 | 1 | 2 | 1 |
| 2 | 2 | 4 | 2 |
1
- Input x
- 1
- Target y
- 2
- Prediction (1 × x)
- 1
2
- Input x
- 2
- Target y
- 4
- Prediction (1 × x)
- 2
Step 2 of 3
Inspect each contribution
The residual is multiplied by its input.
| Same observation | Residuals | Gradient contributions |
|---|---|---|
| Observation 1 | -1 | -1 |
| Observation 2 | -2 | -4 |
Observation 1
- Residuals
- -1
- Gradient contributions
- -1
Observation 2
- Residuals
- -2
- Gradient contributions
- -4
Step 3 of 3
Average before updating
The rate controls how far to move against that batch gradient.
Mean gradient = (−1 + −4) / 2 = −2.5 Learning rate = 0.1 New weight = 1 − (0.1 × −2.5) = 1.25
A batch estimates a direction from the observations it contains
Averaging keeps the gradient consistent with a mean loss.
What adjustment does this batch suggest?
Each observation contributes a prediction error and an input value. Follow their contributions into the average gradient, then check how a different batch changes the proposed direction.
BOTIE
Weight after the batch update
1.25
Follow the operations
1. Current weight
1
2. Learning rate
0.1
3. Batch inputs
- 01
- 12
4. Multiply
- 01
- 12
5. Batch targets
- 02
- 14
6. Subtract
- 0-1
- 1-2
7. Multiply
- 0-1
- 1-4
8. Mean
-2.5
9. Multiply
-0.25
10. Subtract
1.25
11. Result
1.25
This model has one weight, no intercept, and half mean squared error.
1. Keep the Objective Explicit
Use a model with one weight and no intercept. Its prediction multiplies each input by the weight. We minimise half the mean squared residual, so one record’s derivative is its residual multiplied by its input.
The half factor cancels the factor from differentiating a square. If you choose ordinary mean squared error instead, its gradient has an additional factor of two. Neither convention is wrong, but the loss and derivative must agree.
Write the objective before diagnosing a surprising update.
2. Average the Contributions in This Batch
For a batch, calculate predictions using the same current weight, then residuals and per-record gradient contributions. Average those contributions before updating once.
x = [1, 2]; y = [2, 4]; weight = 1
Residuals = [-1, -2]
Gradient = mean([-1 × 1, -2 × 2]) = -2.5
New weight = 1 - 0.1 × (-2.5) = 1.25Updating after each row is a different sequence because later rows see changed weights.
3. Distinguish an Epoch From an Update
An epoch is a pass through the training records. An update happens after one batch. If the final batch is shorter, average by its actual length, not the usual configured batch size.
Shuffling independent training records can avoid systematic ordering effects. Time-series evaluation must still respect time, and sequence models may need order within sequences preserved. Sampling and evaluation splits solve different problems.
A batch is a two-dimensional feature array in a multi-feature model; targets remain aligned with its rows.
Find the contribution from one training record
For half squared error, one observation contributes its prediction error multiplied by its input. Inspect that contribution before averaging several of them in a batch.
import numpy as np
x, target, weight = 2.0, 6.0, 2.0
rate = 0.1
error = weight * x - target
gradient = error * x
print(error)
print(gradient)
print(weight - rate * gradient)-2.0
-4.0
2.4The prediction is too small and the input is positive, so increasing the weight helps locally. A minibatch combines such contributions using its actual number of observations.
4. Compare Cost and Variability
Small batches give cheaper, noisier gradient estimates. Larger batches usually average away more sampling variation, but require more memory per update. Equal epochs do not imply equal numbers of updates.
Compare methods with a declared budget, fixed evaluation records, and repeatable sampling. A lower training loss after one batch does not establish better performance on new data.
The workshop computes a batch update from raw inputs, so the averaging step cannot disappear inside a model call.
5. An Epoch Is a Pass through the Training Records
Choose one permutation of the training indices, divide it into batches and use each batch to estimate a gradient. The final batch may be shorter. Divide its summed gradient by its actual size, not the usual batch size.
The parameters change between batches, so averaging the gradients observed during an epoch is not generally the full-dataset gradient at one fixed parameter. Keep the distinction between the sampling operation and the sequence of updates.
6. Combine Unequal Batch Means without Changing the Objective
If memory forces us to accumulate several batches before one update, their means need weights proportional to batch size. Equal weighting gives a short final batch too much influence.
This example holds the parameter fixed and supplies per-record gradients so that only the bookkeeping changes. An accumulated update matches the full mean here because all contributions were evaluated at that same parameter.
Three records and one final record
The first batch contains three gradient contributions and the second contains one.
import numpy as np
gradient = np.array([1., 2., 3., 10.])
batch_means = np.array([gradient[:3].mean(), gradient[3:].mean()])
sizes = np.array([3,1])
print(float(batch_means.mean()))
print(float(np.average(batch_means, weights=sizes)))
print(float(gradient.mean()))6.0
4.0
4.0The equal average of batch means is wrong for the mean per-record objective. Weighting by record count recovers it.
7. Batch Size Changes More Than Memory Use
A smaller batch usually gives a noisier gradient estimate and more updates per epoch. Holding epochs fixed while changing batch size therefore also changes the update count. Comparing runs requires stating which training budget is fixed.
Inspect validation behaviour and optimisation stability. Do not assume that noise is always harmful or always useful. Correlated records within a batch can make it less representative than its row count suggests.
Check yourself
Questions on Parts 1 to 7
Question 1 of 4
What is the batch gradient?
Use the information below.
Per-record gradients [-1,-4], mean loss convention.Try it with Botie
Build with Botie
Write and run Python