To improve the training process and reduce the loss in your dog breed classification model, we can focus on refining a few key aspects of your current implementation:
-
Model Freezing Strategy: It appears there might be a misunderstanding in the freezing logic. To effectively utilize transfer learning, it's common to freeze the initial layers of a pre-trained model and only fine-tune the deeper layers and the fully connected (fc) layers. This approach preserves the learned low-level features while allowing the model to adapt to the specific task.
-
Weight Decay: The current weight decay of 1e-2 is relatively high, which can hinder the model's ability to learn effectively. Reducing it to 1e-4 or 1e-5 often yields better performance by providing a gentler regularization.
-
Optimizer Configuration: Ensuring that different layers have appropriate learning rates can significantly impact training. Fine-tuning deeper layers with higher learning rates while keeping earlier layers' learning rates lower can help in better model adaptation.
-
Label Smoothing: Introducing label smoothing can prevent the model from becoming over-confident, which can improve generalization.
-
Gradient Clipping: While gradient clipping helps in stabilizing training, ensure that the clipping value isn't too restrictive.
Below is the revised version of your code incorporating these improvements:
import os
import pandas as pd
import numpy as np
from PIL import Image
from tqdm import tqdm
from sklearn.model_selection import StratifiedKFold
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader, Subset
from torchvision import transforms, models
from torch.cuda.amp import GradScaler, autocast
from torch.optim.lr_scheduler import OneCycleLR
from sklearn.model_selection import StratifiedKFold
# Define the DogBreedDataset class
class DogBreedDataset(Dataset):
def __init__(self, csv_file, root_dir, transform=None):
self.labels_df = pd.read_csv(csv_file)
self.root_dir = root_dir
self.transform = transform
self.breeds = self.labels_df['breed'].unique()
self.breed_to_idx = {breed: idx for idx, breed in enumerate(self.breeds)}
self.labels_df['breed'] = self.labels_df['breed'].map(self.breed_to_idx)
def __len__(self):
return len(self.labels_df)
def __getitem__(self, idx):
img_name = os.path.join(self.root_dir, self.labels_df.iloc[idx, 0] + '.jpg')
image = Image.open(img_name).convert('RGB')
breed = self.labels_df.iloc[idx, 1]
if self.transform:
image = self.transform(image)
return image, breed
def get_breed_name(self, idx):
return self.breeds[idx]
# Define the TestDataset class
class TestDataset(Dataset):
def __init__(self, root_dir, transform=None):
self.root_dir = root_dir
self.transform = transform
self.image_ids = os.listdir(root_dir)
def __len__(self):
return len(self.image_ids)
def __getitem__(self, idx):
img_name = os.path.join(self.root_dir, self.image_ids[idx])
image = Image.open(img_name).convert('RGB')
if self.transform:
image = self.transform(image)
return image, self.image_ids[idx].split('.')[0]
# Data transformations
data_transform = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.08, 1.0), ratio=(3.0/4.0, 4.0/3.0)),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.2),
transforms.RandomRotation(20),
transforms.RandomAffine(degrees=0, translate=(0.1, 0.1), scale=(0.9, 1.1)),
transforms.GaussianBlur(kernel_size=(5, 9), sigma=(0.1, 2.0)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# Validation transformations
val_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# Load the dataset
full_dataset = DogBreedDataset(csv_file='/kaggle/input/dog-breed-identification/labels.csv',
root_dir='/kaggle/input/dog-breed-identification/train',
transform=data_transform)
# Define ResNet152 model with improved freezing strategy and adjusted layers
def get_model(num_classes):
model = models.resnet152(weights=models.ResNet152_Weights.DEFAULT)
# Freeze all layers initially
for param in model.parameters():
param.requires_grad = False
# Unfreeze specific layers (e.g., layer4) and the fully connected layers
for param in model.layer4.parameters():
param.requires_grad = True
# Optionally, unfreeze layer3 for more fine-tuning
for param in model.layer3.parameters():
param.requires_grad = True
# Define a new fully connected layer with dropout and a hidden layer
num_ftrs = model.fc.in_features
model.fc = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(num_ftrs, 2048),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(2048, num_classes)
)
return model
# Training function with label smoothing
def train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, num_epochs, device, grad_clip=1.0):
scaler = GradScaler()
best_val_loss = float('inf')
patience = 5
counter = 0
for epoch in range(num_epochs):
model.train()
train_loss = 0.0
train_correct = 0
train_total = 0
pbar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs} - Training")
for inputs, labels in pbar:
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
with autocast():
outputs = model(inputs)
loss = criterion(outputs, labels)
if torch.isnan(loss):
print(f"NaN loss detected in epoch {epoch+1}. Stopping training.")
return best_val_loss
scaler.scale(loss).backward()
# Unscale the gradients before clipping
scaler.unscale_(optimizer)
# Gradient clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), grad_clip)
scaler.step(optimizer)
scaler.update()
if scheduler is not None:
scheduler.step()
train_loss += loss.item() * inputs.size(0)
_, predicted = outputs.max(1)
train_total += labels.size(0)
train_correct += predicted.eq(labels).sum().item()
# Calculate gradient norm for monitoring
total_norm = 0
for p in model.parameters():
if p.grad is not None:
param_norm = p.grad.data.norm(2)
total_norm += param_norm.item() ** 2
total_norm = total_norm ** 0.5
# Update progress bar
pbar.set_postfix({
'loss': f"{loss.item():.4f}",
'acc': f"{train_correct/train_total:.4f}",
'lr': f"{optimizer.param_groups[0]['lr']:.6f}",
'grad_norm': f"{total_norm:.4f}"
})
train_loss /= len(train_loader.dataset)
train_acc = train_correct / train_total
# Validation
val_loss, val_acc = validate_model(model, val_loader, criterion, device)
print(f'Epoch {epoch+1}/{num_epochs}:')
print(f'Train Loss: {train_loss:.4f} Acc: {train_acc:.4f}')
print(f'Val Loss: {val_loss:.4f} Acc: {val_acc:.4f}')
print(f'Learning Rate: {optimizer.param_groups[0]["lr"]:.6f}')
print(f'Gradient Norm: {total_norm:.4f}')
# Check for improvement
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save(model.state_dict(), 'best_model.pth')
print("Saved best model.")
counter = 0
else:
counter += 1
if counter >= patience:
print(f"Early stopping at epoch {epoch+1}")
break
return best_val_loss
def validate_model(model, val_loader, criterion, device):
model.eval()
val_loss = 0.0
val_correct = 0
val_total = 0
with torch.no_grad():
for inputs, labels in val_loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
val_loss += loss.item() * inputs.size(0)
_, predicted = outputs.max(1)
val_total += labels.size(0)
val_correct += predicted.eq(labels).sum().item()
val_loss /= len(val_loader.dataset)
val_acc = val_correct / val_total
return val_loss, val_acc
# Main training loop
def main():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
num_classes = len(full_dataset.breeds)
num_epochs = 50 # Reduced epochs for faster experimentation
batch_size = 32 # Increased batch size for better gradient estimation
train_size = int(0.8 * len(full_dataset))
val_size = len(full_dataset) - train_size
train_dataset, val_dataset = torch.utils.data.random_split(full_dataset, [train_size, val_size])
# Apply validation transformations to the validation dataset
val_dataset.dataset.transform = val_transform
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=8, pin_memory=True)
# Initialize the model
model = get_model(num_classes).to(device)
# Define label smoothing
class LabelSmoothingCrossEntropy(nn.Module):
def __init__(self, smoothing=0.1):
super(LabelSmoothingCrossEntropy, self).__init__()
self.smoothing = smoothing
self.confidence = 1.0 - smoothing
def forward(self, output, target):
log_probs = nn.functional.log_softmax(output, dim=-1)
targets = torch.zeros_like(log_probs).scatter_(1, target.unsqueeze(1), 1)
targets = targets * self.confidence + self.smoothing / output.size(1)
loss = (-targets * log_probs).mean(dim=-1).sum()
return loss
criterion = LabelSmoothingCrossEntropy(smoothing=0.1)
# Define the optimizer with reduced weight decay
optimizer = optim.AdamW([
{'params': model.fc.parameters(), 'lr': 5e-4},
{'params': model.layer4.parameters(), 'lr': 5e-5},
{'params': model.layer3.parameters(), 'lr': 3e-5}
], weight_decay=1e-4)
# Define the learning rate scheduler
scheduler = OneCycleLR(
optimizer,
max_lr=[5e-4, 5e-5, 3e-5], # Match the optimizer's learning rates
steps_per_epoch=len(train_loader),
epochs=num_epochs,
pct_start=0.3, # 30% warmup
div_factor=25, # 5e-4 / 25 = 2e-5 as initial LR
final_div_factor=1e4 # Final LR will be max_lr / 1e4
)
# Train the model
best_loss = train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, num_epochs, device, grad_clip=1.0)
print(f"Best Validation Loss: {best_loss:.4f}")
# Load the best model
best_model = get_model(num_classes).to(device)
best_model.load_state_dict(torch.load('best_model.pth'))
return best_model
# Testing function
def test(model, test_loader, device, class_names):
predictions = []
model.eval()
with torch.no_grad():
for inputs, image_ids in tqdm(test_loader, desc="Testing"):
inputs = inputs.to(device)
outputs = model(inputs)
probs = torch.softmax(outputs, dim=1)
probs = probs.cpu().numpy()
for image_id, prob in zip(image_ids, probs):
prediction = {'id': image_id}
for i, class_name in enumerate(class_names):
prediction[class_name] = prob[i]
predictions.append(prediction)
return predictions
if __name__ == "__main__":
best_model = main()
# Prepare test data
test_dataset = TestDataset(root_dir='/kaggle/input/dog-breed-identification/test', transform=val_transform)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=8, pin_memory=True)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Get all class names
class_names = full_dataset.breeds.tolist()
# Perform testing
predictions = test(best_model, test_loader, device, class_names)
# Create DataFrame and save as CSV
submission_df = pd.DataFrame(predictions, columns=['id'] + class_names)
submission_df.sort_values(by='id', inplace=True)
submission_df.to_csv('/kaggle/working/submission.csv', index=False)
print("Predictions saved to submission.csv")
Detailed Changes and Rationale
-
Model Freezing Strategy:
-
Original:
for param in model.parameters():
param.requires_grad = True # 冻结所有层
# 解冻 layer1, layer2, layer3, 和 layer4
for layer in [model.layer1, model.layer2, model.layer3, model.layer4]:
for param in layer.parameters():
param.requires_grad = True
The comment suggests freezing all layers, but requires_grad is set to True, which actually unfreezes them.
-
Revised:
# Freeze all layers initially
for param in model.parameters():
param.requires_grad = False
# Unfreeze specific layers (e.g., layer4) and the fully connected layers
for param in model.layer4.parameters():
param.requires_grad = True
# Optionally, unfreeze layer3 for more fine-tuning
for param in model.layer3.parameters():
param.requires_grad = True
This correctly freezes all layers initially and then selectively unfreezes layer4 and optionally layer3. This allows the model to retain pre-trained features in the frozen layers while fine-tuning the deeper layers and the classifier for your specific task.
-
Weight Decay:
-
Original:
weight_decay=1e-2
A weight decay of 1e-2 is quite high and can lead to underfitting.
-
Revised:
weight_decay=1e-4
Lowering the weight decay to 1e-4 provides a more balanced regularization, preventing the weights from growing too large without being overly restrictive.
-
Optimizer Configuration:
-
Original:
optimizer = optim.AdamW([
{'params': model.fc.parameters(), 'lr': 5e-4},
{'params': model.layer1.parameters(), 'lr': 1e-5},
{'params': model.layer2.parameters(), 'lr': 2e-5},
{'params': model.layer3.parameters(), 'lr': 3e-5},
{'params': model.layer4.parameters(), 'lr': 5e-5}
], weight_decay=1e-2)
This sets different learning rates for various layers, but with a high weight decay.
-
Revised:
optimizer = optim.AdamW([
{'params': model.fc.parameters(), 'lr': 5e-4},
{'params': model.layer4.parameters(), 'lr': 5e-5},
{'params': model.layer3.parameters(), 'lr': 3e-5}
], weight_decay=1e-4)
Additional Recommendations
-
Monitor Training Metrics: Utilize tools like TensorBoard or Weights & Biases to visualize training and validation metrics in real-time. This can provide deeper insights into the model's performance and help in making informed adjustments.
-
Advanced Augmentation: While your current data augmentations are robust, consider incorporating techniques like MixUp or CutMix, which have shown promise in improving generalization.
-
Ensemble Methods: Training multiple models with different architectures or initialization and combining their predictions can lead to better performance.
-
Hyperparameter Tuning: Experiment with different hyperparameters such as learning rates, weight decay, and batch sizes using tools like Optuna or Hyperopt for automated tuning.
Implementing these changes should help in reducing the loss and improving the overall performance of your dog breed classification model. Remember to iteratively test and validate each modification to understand its impact fully.