Skip to content
E
Educatum

Stochastic Gradient Descent (SGD)

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 θ\theta using an unbiased noisy estimate of the full loss gradient computed from a randomly sampled mini-batch Bt\mathcal{B}_t (or a single sample ∣Bt∣=1|\mathcal{B}_t| = 1 in pure SGD):

θt+1=θt−ηt∇θLBt(θt)\theta_{t+1} = \theta_t - \eta_t \nabla_\theta \mathcal{L}_{\mathcal{B}_t}(\theta_t)

Unlike full-batch Gradient Descent—which scans all mm training examples before taking a single parameter step—mini-batch SGD updates parameters m/∣B∣m / |\mathcal{B}| 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 ηt\eta_t prevents persistent oscillation around the minimum.

Key Terms

  • Loss Function: Objective measuring discrepancy between model predictions and targets (e.g., MSE 1m∑i(xiTθ−yi)2\frac{1}{m}\sum_i (x_i^T\theta - y_i)^2).
  • Gradient: Vector of partial derivatives ∇θL\nabla_\theta \mathcal{L} pointing in the direction of steepest ascent.
  • Learning Rate (ηt\eta_t): Step size scaling updates in the direction of −∇θLBt-\nabla_\theta \mathcal{L}_{\mathcal{B}_t}.
  • Mini-Batch: Small randomly sampled subset Bt\mathcal{B}_t balancing gradient variance reduction and vectorization efficiency against update frequency.
  • Epoch: One full shuffled pass through all mm 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 ηt\eta_t 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}")
  • Gradient Descent Variants: Batch GD (exact gradient, O(m)O(m) 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 ηt\eta_t (such as ηt∝1/t\eta_t \propto 1/\sqrt{t} 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.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.