Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Batch Processing

In each iteration so far, we trained with a single sample. This approach is called stochastic gradient descent (SGD). It is simple, but it cannot make full use of NumPy’s vectorized, parallel computation. In fact, we can send several samples into the network model at once for training. This approach is called batch processing and is the standard practice in modern deep learning.

Depending on how many samples are used each time, gradient descent falls into three categories:

  • Stochastic gradient descent (SGD): each iteration uses one sample;

  • Batch gradient descent (Batch GD): each iteration uses all the samples. In practice, batch gradient descent is rarely used for training, because it needs a lot of memory and runs very slowly;

  • Mini-batch gradient descent (Mini-batch GD): each iteration uses a few samples. Mini-batch gradient descent makes full use of the vectorized, parallel computation of NumPy (and other computing libraries), and is the usual way to train models today.

Convergence

Convergence means that during model training, as the network model iterates, its loss no longer decreases significantly and the model parameters become stable.

  • Stochastic gradient descent: each iteration learns from only one sample, so the gradient fluctuates a lot, the direction of convergence tends to swing from side to side, and convergence is slow;

  • Batch gradient descent: each iteration learns from all the data, so it can keep a relatively correct direction of convergence, and convergence is fast;

  • Mini-batch gradient descent: a compromise that balances efficiency and stability.

Generalization

Generalization is an important measure of how well a model has been trained: the ability of the network model to handle new data. Put simply, does a network model that performs well on the training set also perform well on the test set?

Generally speaking, generalization ability comes from learning from diverse data. Therefore:

  • Stochastic gradient descent: training on one sample at a time usually gives better generalization;

  • Batch gradient descent: training on the same data every time lacks variety, which limits the improvement of generalization;

  • Mini-batch gradient descent: a compromise that balances diversity and stability.

Fitting

Fitting refers to the performance of the network model on the training set, that is, how well the model has learned the patterns in the data.

Poor generalization is generally caused by an unsatisfactory fit, and there are two typical cases:

  • Underfitting: the network model performs poorly on the training set, and also performs poorly on the test set. This is usually because of insufficient training, or because the network model is too simple.

  • Overfitting: the network model performs nearly perfectly on the training set but poorly on the test set. This is usually because the network model is too complex and has learned redundant details that are not representative.

💡 Tip: Mini-batch gradient descent has both good convergence speed and good generalization ability, so it is the most commonly used training method in practice.

Tensor

Dataset

We add an initialization parameter to the dataset: batch_size (the batch size).

By setting different batch sizes, we control how the training is done:

  • Stochastic gradient descent: this is the dataset’s default (batch_size=1). For our tiny dataset, __getitem__() returns one sample each time, and __len__() returns 4;

  • Batch gradient descent: simply use all() to get all the data samples at once;

  • Mini-batch gradient descent: set batch_size to any value greater than 1. For example, with batch_size=2, __getitem__() returns two samples each time, and __len__() returns 2.

Note in particular that for a dataset with batch processing, the output data format changes from the previous 1D tensor with shape (number of features,) to a 2D tensor with shape (batch size, number of features).

Model

Once the dataset supports batch processing, the samples returned by __getitem__() are no longer 1D tensors but 2D tensors with shape (batch size, number of features). So the output of the inference function is also a 2D tensor, with shape (batch size, number of labels).

When computing the weight gradient, the gradient function also needs a formula suited to 2D tensors: instead of the multiplication p.grad * x.data, it uses the matrix multiplication p.grad.T @ x.data. When computing the bias gradient, it must also sum along axis 0 (the batch axis): np.sum(p.grad, axis=0).

With these changes, a single computation gives the correct gradient for every sample in the same batch.

Loss function (mean squared error)

The gradient function needs to divide the error term by the batch size. The purpose is to avoid adding up the error terms of several samples in a batch, which would amplify the gradient several times.

Optimizer (stochastic gradient descent)

Hyperparameters

Learning rate

Batch size

As our second hyperparameter, the batch size defines the number of samples used in each batch.

We will use mini-batch gradient descent. But by adjusting the batch size, we can also get stochastic gradient descent and batch gradient descent.

💡 Tip: In practice, the batch size is usually a power of 2 (such as 16, 32, 64, or 128). This is not a mathematical requirement. Setting it this way simply maximizes hardware efficiency.

Modeling

When creating the dataset, we need to pass the batch size as a parameter.

Training

With mini-batch gradient descent, the 4 samples in the training set need only 2 iterations.

Inference

For model inference, we use the full-batch approach.

prediction:	Tensor([[56.19176426]])

Evaluation

loss:	Tensor(11839.232164432306)

The evaluation shows that after mini-batch gradient descent reduced the number of iterations and improved efficiency, convergence has slowed down accordingly.

This is understandable. Before, we trained with one sample at a time and updated the parameters 4 times in total. Now, with a batch size of 2, the total number of parameter updates is smaller.

Summary

The three approaches compare as follows:

ApproachBatch sizeConvergence speedGeneralizationOverfitting risk
Stochastic gradient descent (SGD)One sampleSlow (large oscillations)StrongLow
Batch gradient descent (Batch GD)All samplesFast (stable single steps)
but demanding on hardware (memory and compute)
WeakHigh
Mini-batch gradient descent (Mini-batch GD)A few samplesMediumMediumMedium

Exercises

  1. By adjusting the batch size, try batch gradient descent and see how it performs.