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.
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.
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.
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?