Batch size
Batch size determines how many training examples are processed in one forward and backward pass to compute a gradient update. Larger batches reduce gradient variance and maximize GPU throughput but require more memory and careful learning rate scaling, whereas smaller batches save memory and introduce gradient noise that often acts as implicit regularization for better generalization.
Study Card: Batch Size in Machine Learning
Direct Answer
Batch size is a hyperparameter controlling the number of training examples used in a single forward and backward pass before updating model weights. A larger batch size produces a lower-variance gradient estimate and exploits vectorized GPU parallelism efficiently, at the cost of higher activation memory and fewer parameter updates per epoch. A smaller batch size uses less memory and performs more updates per epoch; its noisier gradient estimates create implicit regularization that often converges to flatter minima and generalizes better, though per-step throughput is lower and learning rates must be kept smaller for stability.
Key Terms
- Epoch: One complete pass over all examples in the training dataset.
- Iteration (Step): One forward/backward pass and parameter update performed on a single mini-batch.
- Gradient: The vector of partial derivatives of the loss function with respect to the model’s parameters.
- Stochastic Gradient Descent (SGD): Optimization that updates weights from noisy sample-based gradient estimates (strictly batch size , though in practice often used for mini-batch SGD).
- Mini-batch Gradient Descent: Updating weights using the average gradient over samples (), balancing hardware vectorization and gradient noise.
Example
Consider training a classifier on images:
- Batch Size = 1 (Pure SGD): Weights update after every image ( updates per epoch). Memory usage is minimal, but gradient variance is high, producing noisy zig-zag trajectories and poor GPU utilization.
- Batch Size = 100 (Mini-Batch GD): Weights update using the average gradient of images ( updates per epoch). Hardware vectorization makes each epoch much faster while retaining enough gradient noise to aid generalization.
- Batch Size = 10,000 (Full-Batch GD): Computes the exact empirical gradient over the entire dataset, yielding one parameter update per epoch. Gradient sampling variance is zero, but memory consumption scales with and training often requires much larger step sizes or many epochs to make progress.
Code Implementation
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
# Load and preprocess MNIST subset for fast comparison
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train[:5000].astype('float32') / 255.0
y_train = y_train[:5000]
x_test = x_test[:1000].astype('float32') / 255.0
y_test = y_test[:1000]
# Always construct a fresh model inside the experiment function so weights are not reused
def build_model():
model = Sequential([
keras.Input(shape=(28, 28)),
Flatten(),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
return model
def train_with_batch_size(batch_size, epochs=8):
tf.keras.utils.set_random_seed(42)
model = build_model()
return model.fit(
x_train,
y_train,
epochs=epochs,
batch_size=batch_size,
validation_data=(x_test, y_test),
verbose=0
)
# Compare small, medium, and full-batch sizes
# (batch_size=1 pure SGD is omitted here because 5,000 sequential steps/epoch is slow in Python)
history_16 = train_with_batch_size(16)
history_128 = train_with_batch_size(128)
history_full = train_with_batch_size(len(x_train))
plt.plot(history_16.history['val_accuracy'], label='Batch size 16')
plt.plot(history_128.history['val_accuracy'], label='Batch size 128')
plt.plot(history_full.history['val_accuracy'], label=f'Full batch ({len(x_train)})')
plt.title('Validation Accuracy vs. Batch Size')
plt.ylabel('Validation Accuracy')
plt.xlabel('Epoch')
plt.legend()
plt.show()
Related Concepts
- Learning Rate Scaling: Batch size and learning rate must be tuned together. Larger batch sizes have lower gradient variance and typically allow and require larger learning rates (commonly scaled linearly with batch size for SGD or via square-root scaling for Adam, paired with learning-rate warmup), whereas smaller batch sizes have noisier gradients and require smaller learning rates to remain stable.
- Generalization Gap: Very large batches can converge to sharper minima and generalize worse if the number of updates, learning rate schedule, or explicit regularization is not adjusted accordingly.
- Gradient Accumulation: When GPU memory limits physical micro-batch size, accumulating gradients across micro-batches before stepping simulates an effective batch size of .
- Batch Normalization Sensitivity: BatchNorm computes mean and variance statistics per mini-batch; very small batch sizes () introduce noisy statistics, favoring LayerNorm or GroupNorm instead.