Here is the weight update rule for mini-batch stochastic gradient descent (SGD) in linear regression, expressed in terms of the samples in a particular batch B with batch size b:
Given:
X: Data matrix of size n × d (where n is the total number of training examples and d is the number of features)
t: Target vector of size n × 1
B: Index set of a particular mini-batch with b examples (i.e., |B| = b)
w: Weight vector of size d × 1 (to be updated)
α (or learning_rate): The learning rate for SGD
Extracting the Mini-Batch Data:
X_B = X[B, :]: Mini-batch data matrix of size b × d (rows corresponding to indices in B)
t_B = t[B]: Mini-batch target vector of size b × 1 (elements corresponding to indices in B)
Predictions for the Mini-Batch:
ŷ_B = X_B @ w: Predicted values for the mini-batch (matrix multiplication), resulting in a vector of size b × 1
Error (Loss) for the Mini-Batch (Assuming Mean Squared Error, MSE):
Loss_B = (1/b) * ∑(ŷ_B - t_B)^2: Average loss over the mini-batch (scalar)
Gradient of the Loss with Respect to Weights (for the Mini-Batch):
∇Loss_B/w = (2/b) * X_B^T @ (ŷ_B - t_B): Gradient of the loss with respect to w, of size d × 1
Weight Update Rule for Mini-Batch SGD:
w ← w - α * ∇Loss_B/w
- Expanded Form:
w ← w - (2α/b) * X_B^T @ (X_B @ w - t_B)
Interpretation:
- For each mini-batch
B, compute the predictions ŷ_B using the current weights w.
- Calculate the loss for the mini-batch and its gradient with respect to
w.
- Update
w by moving in the direction of the negative gradient of the loss (scaled by the learning rate α and normalized by the batch size b). Repeat for all mini-batches.
Example Python Code (using NumPy):
import numpy as np
def mini_batch_sgd(X, t, batch_size, learning_rate, num_epochs):
num_samples, num_features = X.shape
weights = np.zeros(num_features) # Initialize weights to zero
for _ in range(num_epochs):
# Shuffle data at the start of each epoch
shuffled_indices = np.random.permutation(num_samples)
X_shuffled = X[shuffled_indices]
t_shuffled = t[shuffled_indices]
# Split data into mini-batches
for batch_idx in range(0, num_samples, batch_size):
batch_indices = shuffled_indices[batch_idx:batch_idx + batch_size]
X_batch = X_shuffled[batch_idx:batch_idx + batch_size]
t_batch = t_shuffled[batch_idx:batch_idx + batch_size]
# Compute predictions for the mini-batch
predictions = np.dot(X_batch, weights)
# Compute the gradient of the loss for the mini-batch
gradient = (2 / batch_size) * np.dot(X_batch.T, (predictions - t_batch))
# Update the weights
weights -= learning_rate * gradient
return weights
This code demonstrates how to implement mini-batch SGD for linear regression, iterating over the dataset in mini-batches, computing predictions, calculating the gradient, and updating the weights accordingly.