Stochastic Gradient Descent (SGD)
Stochastic Gradient Descent (SGD) optimizes model parameters using noisy gradient estimates computed from a single training sample or a small mini-batch rather than the entire dataset. This lowers per-step computation from O(m) to O(batch_size), enables out-of-core streaming on massive datasets, and introduces stochastic noise that can help escape shallow saddle points or sharp local minima when paired with shuffling and learning rate decay.
Study Card: Stochastic Gradient Descent (SGD)
Direct Answer
Stochastic Gradient Descent (SGD) iteratively updates parameters using an unbiased noisy estimate of the full loss gradient computed from a randomly sampled mini-batch (or a single sample in pure SGD):
Unlike full-batch Gradient Descent—which scans all training examples before taking a single parameter step—mini-batch SGD updates parameters times per epoch, dramatically accelerating early convergence on large datasets. Because gradient estimates contain sampling variance, randomly shuffling data each epoch and decaying the learning rate prevents persistent oscillation around the minimum.
Key Terms
- Loss Function: Objective measuring discrepancy between model predictions and targets (e.g., MSE ).
- Gradient: Vector of partial derivatives pointing in the direction of steepest ascent.
- Learning Rate (): Step size scaling updates in the direction of .
- Mini-Batch: Small randomly sampled subset balancing gradient variance reduction and vectorization efficiency against update frequency.
- Epoch: One full shuffled pass through all training examples.
Example
Imagine training linear regression on 1 million house records. Full-batch Gradient Descent must evaluate and sum gradients across all 1 million homes just to perform one update. Pure SGD updates immediately after 1 randomly sampled home, while mini-batch SGD (e.g., batch_size=128) takes thousands of fast GPU-vectorized updates per epoch. Because each mini-batch is an unbiased noisy estimate of the true gradient, shuffling every epoch avoids cyclic ordering bias and decaying lets weights settle smoothly near the optimum.
Code Implementation
import numpy as np
def stochastic_gradient_descent(X, y, theta, learning_rate=0.01, n_epochs=100, batch_size=1, seed=42):
"""
Mini-batch / Stochastic Gradient Descent for Linear Regression minimizing MSE.
"""
rng = np.random.default_rng(seed)
theta = theta.astype(float).copy()
m = len(y)
for epoch in range(n_epochs):
# Shuffle samples at the start of every epoch to avoid ordering bias
perm = rng.permutation(m)
X_shuffled = X[perm]
y_shuffled = y[perm]
for start_idx in range(0, m, batch_size):
end_idx = min(start_idx + batch_size, m)
X_batch = X_shuffled[start_idx:end_idx]
y_batch = y_shuffled[start_idx:end_idx]
predictions = X_batch.dot(theta)
errors = predictions - y_batch
# Exact gradient of MSE = (1 / |B|) * sum((X_batch @ theta - y_batch)^2)
gradient = (2.0 / len(y_batch)) * X_batch.T.dot(errors)
theta = theta - learning_rate * gradient
if epoch % 10 == 0:
epoch_mse = np.mean((X.dot(theta) - y) ** 2)
print(f"Epoch: {epoch:3d}, Full MSE: {epoch_mse:.4f}")
return theta
# Sample data
X = np.array([[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]], dtype=float)
y = np.array([3, 5, 3, 7, 8, 7], dtype=float)
theta_init = np.array([0.0, 0.0])
theta_learned = stochastic_gradient_descent(X, y, theta_init, learning_rate=0.01, n_epochs=100, batch_size=2)
print(f"Learned parameters: {theta_learned}")
Related Concepts
- Gradient Descent Variants: Batch GD (exact gradient, per step), Pure SGD (
batch_size=1, highest variance), and Mini-Batch SGD (hardware-friendly trade-off used across deep learning). - Momentum & Nesterov Momentum: Accumulate exponentially weighted past gradients to accelerate progress along consistent valley directions and dampen orthogonal oscillations.
- Learning Rate Scheduling: Decaying (such as or cosine decay) ensures convergence to a minimum despite mini-batch gradient noise.
- Adaptive Optimizers (Adam, RMSprop, AdaGrad): Scale step sizes per parameter using running estimates of first and/or second gradient moments.