30 Mins

2. Loss Functions & Optimization

Loss Landscapes and Objective Functions

Loss functions define the objective for our optimization process by quantifying the distance between model predictions and ground-truth targets. For regression, Mean Squared Error (MSE) is the gold standard, providing a convex quadratic bowl that is easy to navigate via gradient-based methods. Because it penalizes larger errors exponentially due to the squaring effect, it is highly sensitive to outliers, which can skew the convergence trajectory significantly.

In classification scenarios, Cross-Entropy Loss takes precedence by minimizing the negative log-likelihood of the correct class. Unlike MSE, which assumes Gaussian noise, Cross-Entropy treats the prediction as a probability distribution over labels. By leveraging the logarithm, it applies a steep penalty when the model is confident in an incorrect classification, preventing the 'saturation' issue often encountered with Sigmoid/Softmax activation layers paired with MSE.

Operator Note: Always pair Cross-Entropy with raw logits in PyTorch, as the internal Softmax implementation is numerically stabilized to avoid overflow/underflow.
Python 3
import torch
import torch.nn as nn

# MSE Loss for regression task
preds = torch.tensor([0.9, 0.1], dtype=torch.float32, requires_grad=True)
targets = torch.tensor([1.0, 0.0], dtype=torch.float32)
mse_criterion = nn.MSELoss()
mse_loss = mse_criterion(preds, targets)

# Cross-Entropy for classification task
logits = torch.tensor([[2.0, -1.0, 0.1]], dtype=torch.float32, requires_grad=True)
labels = torch.tensor([0], dtype=torch.long)
ce_criterion = nn.CrossEntropyLoss()
ce_loss = ce_criterion(logits, labels)

print(f'MSE: {mse_loss.item()}, CE: {ce_loss.item()}')

Optimization: From SGD to Momentum

Gradient Descent is the primary engine of neural network learning, yet standard Vanilla SGD often struggles with local minima and saddle points. By calculating the gradient on a mini-batch rather than the full dataset, we introduce stochasticity that can actually help escape narrow local minima. However, the path taken is often oscillatory and slow to traverse high-curvature ravines.

Momentum optimization addresses this by accumulating a moving average of past gradients. Much like a ball rolling down a hill, the optimizer gains velocity in consistent directions while dampening oscillations in directions where gradients fluctuate rapidly. This makes the optimization process significantly more robust and speeds up convergence in deep, multi-layered architectures where vanishing gradients are a concern.

Operator Note: Momentum is particularly useful when the loss surface is elongated, as it helps the model navigate flat plateaus more effectively.
Python 3
import torch.optim as optim

model_params = [torch.randn(5, 5, requires_grad=True)]
# SGD with 0.9 momentum
optimizer = optim.SGD(model_params, lr=0.01, momentum=0.9)

# Simulated weight update
loss = (model_params[0]**2).sum()
loss.backward()
optimizer.step()
print('Optimizer updated parameters with momentum.')

Adaptive Learning Rates: The Adam Optimizer

The Adam (Adaptive Moment Estimation) optimizer is currently the industry standard for most deep learning applications. It combines the advantages of both Momentum and RMSProp by keeping track of both the first moment (mean of gradients) and the second moment (uncentered variance of gradients). This allows the optimizer to compute individual adaptive learning rates for each parameter.

By scaling the update based on the inverse of the square root of the second moment, Adam effectively normalizes the gradient updates. This ensures that parameters with sparse gradients receive larger updates, while parameters with frequent, high-magnitude gradients are smoothed out. The result is a highly efficient optimization process that is less sensitive to the initial selection of the global learning rate hyperparameter.

Operator Note: While Adam is powerful, it can sometimes converge to suboptimal solutions compared to carefully tuned SGD. Always experiment with both if your model fails to generalize.
Python 3
params = [torch.randn(10, requires_grad=True)]
# Adam optimizer initialization
adam_opt = torch.optim.Adam(params, lr=0.001, betas=(0.9, 0.999))

# Performing a step
loss = params[0].sum()
loss.backward()
adam_opt.step()
print('Adam step completed with adaptive scaling.')

Knowledge Check

Ready to test your understanding of 2. Loss Functions & Optimization?

Back