Optimizing Machine Learning with Mini-Batch Gradient Descent
Introduction
Let's recall that Stochastic Gradient Descent (SGD) is an efficient optimization algorithm known for its robust functionalities. However, when dealing with large datasets, SGD encounters particular challenges that instigate instabilities in the loss function. To overcome these limitations, we'll discuss Mini-Batch Gradient Descent (MBGD) in this session - a technique that combines the best attributes of SGD and Batch Gradient Descent. By the end of today's lesson, you'll understand the theory behind MBGD and be ready to implement it using C++.
Understanding the drawbacks of SGD
While SGD's power lies in its efficiency, especially when dealing with large datasets, it has limitations. The loss function can become unstable when the model's parameters are updated at each iteration. This instability is one of the primary challenges that MBGD aims to overcome.
Introduction to Mini-Batch Gradient Descent
MBGD offers a conceptual middle ground between SGD and Batch Gradient Descent. Like its predecessors, MBGD divides the dataset into small subsets or mini-batches. It then computes the gradient of the cost function concerning this subset and accordingly updates the model's parameters.
A distinguishing feature of MBGD is its capacity to tune the size of the mini-batches. MBGD behaves as Batch Gradient Descent if the batch size equates to the dataset size. If the batch size is 1, it acts like SGD. However, a mini-batch size between 10 and 1000 is typically selected in practice.
The Math Behind Mini-Batch Gradient Descent
We use linear regression to illustrate the math, since the implementation optimizes mean squared error (MSE).
-
Model and prediction:
- For a sample i with feature vector x_i and parameters theta, the prediction is Include an intercept by adding a 1 as the first feature if needed.
-
Mini-batch loss (size s = |B|):
Some texts use 1/(2s) to remove the 2 in the gradient; here we do not, which is why the code uses the factor 2/s.
-
Gradient on a mini-batch:
- Component-wise:
- Vector/matrix form:
This matches the code: gradients[k] += (2.0/current_batch_size) * error * X[idx][k].
-
Parameter update:
With s = 1 this reduces to SGD; with s = m (full dataset) it becomes batch gradient descent.
-
Sampling and variance: If mini-batches are sampled uniformly, the mini-batch gradient is an unbiased estimate of the full gradient; larger s lowers gradient variance but increases computation per step. Shuffling once per epoch approximates uniform sampling and ensures each example is used.
