DL Notes
Understanding gradient descent optimization algorithm - how neural networks learn by iteratively minimizing the loss function through parameter updates.
Gradient descent is the fundamental optimization algorithm used to train neural networks. It iteratively adjusts the network parameters to minimize the loss function by moving in the direction of steepest descent.
The Core Intuition
Imagine you are blindfolded on a hilly landscape and want to reach the lowest valley. Your strategy: feel the slope beneath your feet and take a step downhill. Repeat until you reach the bottom.
Mathematical Formulation
The update rule for gradient descent:
For a neural network with weight matrix W and bias b:
Types of Gradient Descent
| Variant | Batch Size | Speed | Stability | Memory |
|---|---|---|---|---|
| Batch GD | All N samples | Slow per update | Very stable | High |
| Stochastic GD | 1 sample | Fast per update | Very noisy | Low |
| Mini-batch GD | 32-256 samples | Balanced | Balanced | Moderate |
Implementation from Scratch
Gradient Descent for Linear Regression
Gradient Descent in PyTorch
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 64),
nn.ReLU(),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 1)
)
X = torch.randn(200, 10)
y = torch.randn(200, 1)
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
for epoch in range(500):
predictions = model(X)
loss = criterion(predictions, y)
optimizer.zero_grad() # Reset gradients
loss.backward() # Compute gradients
optimizer.step() # Update parameters
if epoch % 100 == 0:
print(f"Epoch {epoch}: Loss = {loss.item():.4f}")Learning Rate Effects
Challenges and Solutions
| Challenge | Description | Solution |
|---|---|---|
| Local Minima | Stuck in suboptimal point | Momentum, random restarts |
| Saddle Points | Zero gradient, not minimum | SGD noise, Adam optimizer |
| Plateaus | Very flat loss regions | Learning rate scheduling |
| Ill-conditioning | Different scales per param | Adaptive methods (Adam, RMSProp) |
| Oscillation | Bouncing in narrow valleys | Momentum, Nesterov |
Gradient Descent Variants Comparison
import torch
import torch.nn as nn
# Same model, different optimizers
model = nn.Linear(10, 1)
X = torch.randn(100, 10)
y = torch.randn(100, 1)
optimizers = {
"SGD": torch.optim.SGD(model.parameters(), lr=0.01),
"SGD+Momentum": torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9),
"Adam": torch.optim.Adam(model.parameters(), lr=0.001),
"RMSProp": torch.optim.RMSprop(model.parameters(), lr=0.01),
}
for name, opt in optimizers.items():
model_copy = nn.Linear(10, 1)
criterion = nn.MSELoss()
for epoch in range(100):
pred = model_copy(X)
loss = criterion(pred, y)
opt.zero_grad()
loss.backward()
opt.step()
print(f"{name}: Final Loss = {loss.item():.4f}")Convergence Conditions
For gradient descent to converge:
- Learning rate must be small enough (below 2/L where L is the Lipschitz constant)
- Loss function should be differentiable (or sub-differentiable)
- For convex problems: guaranteed to reach global minimum
- For non-convex (neural nets): reaches a local minimum or saddle point
Interview Questions
- Why do we subtract the gradient rather than add it?
The gradient points toward steepest ascent. Since we minimize loss, we move opposite to the gradient (steepest descent).
- What happens with a learning rate that is too large?
Updates overshoot the minimum, causing oscillation or divergence. The loss increases instead of decreasing.
- Why is mini-batch gradient descent preferred in practice?
It balances stability and speed, utilizes GPU parallelism, and the noise helps escape sharp local minima leading to better generalization.
- Can gradient descent find the global minimum for neural networks?
Neural network losses are non-convex, so no guarantee exists. However, research shows most local minima in high dimensions have loss values close to the global minimum.
- What is the relationship between batch size and learning rate?
Larger batches allow larger learning rates because gradient estimates are more accurate. The linear scaling rule suggests: if batch size doubles, learning rate can also double.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Gradient Descent.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Deep Learning topic.
Search Terms
deep-learning, deep learning, deep, learning, neural, network, fundamentals, gradient
Related Deep Learning Topics