Certainly! When training a model, adjusting the learning rate based on the improvement in the loss function can be achieved by implementing a learning rate scheduler. One common strategy is to reduce the learning rate when the loss stops improving, which is often referred to as learning rate annealing or decay.
Below is a simple example of a training function with a learning rate scheduler that decreases the learning rate when the validation loss does not improve for a certain number of epochs:
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau
def train_model(model, criterion, optimizer, train_loader, val_loader, num_epochs=100, patience=10):
scheduler = ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=patience, verbose=True)
best_val_loss = float('inf')
for epoch in range(num_epochs):
model.train()
running_loss = 0.0
for data in train_loader:
inputs, targets = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
running_loss += loss.item() * inputs.size(0)
epoch_loss = running_loss / len(train_loader.dataset)
# Evaluate on the validation set
model.eval()
val_loss = 0.0
with torch.no_grad():
for data in val_loader:
inputs, targets = data
outputs = model(inputs)
loss = criterion(outputs, targets)
val_loss += loss.item() * inputs.size(0)
val_loss /= len(val_loader.dataset)
print(f'Epoch {epoch+1}/{num_epochs}, Training Loss: {epoch_loss:.4f}, Validation Loss: {val_loss:.4f}')
# Step the scheduler on validation loss
scheduler.step(val_loss)
# Check for improvement
if val_loss < best_val_loss:
best_val_loss = val_loss
# You can save your best model here
# Stop training if the learning rate gets reduced below a certain threshold
current_lr = optimizer.param_groups[0]['lr']
if current_lr < 1e-6:
print("Learning rate is too low, stopping training.")
break
print("Finished Training")
This function is for a PyTorch model but you can adapt it to TensorFlow or any other framework if needed. The ReduceLROnPlateau scheduler decreases the learning rate by a factor (factor=0.1 in this case) when the validation loss doesn't improve for a certain number (patience) of epochs.
Remember to tune the patience, factor, and mode parameters of ReduceLROnPlateau as per your requirements. The mode parameter can be 'min' if the goal is to minimize the loss, or 'max' for maximizing some accuracy metric.
Furthermore, always ensure you're using the appropriate loss function (criterion) and that the data loaders (train_loader and val_loader) are correctly yielding the training and validation data, respectively.
Feel free to customize the function as needed (e.g., adding metrics tracking, early stopping, model checkpointing, etc.).