Certainly! Below is a refactored and generalized version of your training pipeline. This version adheres to PEP-8 standards, includes comprehensive type hints, modularizes the code for better maintainability, implements robust error handling, and ensures scalability. Additionally, it organizes outputs (like plots and model weights) into designated directories.
import os
import copy
import collections
import time
from typing import Any, Dict, Tuple, Optional, List
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.utils.data import DataLoader
import torchvision
from torchvision import datasets, models, transforms
from PIL import Image
# Enable benchmark for faster training if possible
cudnn.benchmark = True
# Constants
NUM_CLASSES: int = 10
IMAGE_SIZE: int = 224
MEAN: List[float] = [0.4914, 0.4822, 0.4465]
STD: List[float] = [0.247, 0.243, 0.261]
BATCH_SIZE: int = 128
NUM_EPOCHS: int = 10
LEARNING_RATE: float = 1e-4
OUTPUT_DIR: str = "output"
MODEL_WEIGHTS_PATH: str = os.path.join(OUTPUT_DIR, "best_model.pt")
DEVICE: torch.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
CLASSES: Tuple[str, ...] = (
"plane", "car", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"
)
# Ensure output directories exist
os.makedirs(OUTPUT_DIR, exist_ok=True)
def set_seed(seed: int = 42) -> None:
"""Set the random seed for reproducibility."""
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
def get_transforms(train: bool = True) -> transforms.Compose:
"""
Get data transformations for training or validation.
Args:
train (bool): Whether to return training transformations.
Returns:
transforms.Compose: Composed transformations.
"""
if train:
return transforms.Compose([
transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
transforms.AutoAugment(policy=transforms.AutoAugmentPolicy.CIFAR10),
transforms.ToTensor(),
transforms.Normalize(MEAN, STD)
])
else:
return transforms.Compose([
transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
transforms.ToTensor(),
transforms.Normalize(MEAN, STD)
])
def load_datasets(data_dir: str = "./data") -> Tuple[datasets.CIFAR10, datasets.CIFAR10]:
"""
Load training and validation datasets.
Args:
data_dir (str): Directory to download/load data.
Returns:
Tuple[datasets.CIFAR10, datasets.CIFAR10]: Training and validation datasets.
"""
try:
train_set = datasets.CIFAR10(
root=data_dir,
train=True,
download=True,
transform=get_transforms(train=True)
)
validation_set = datasets.CIFAR10(
root=data_dir,
train=False,
download=True,
transform=get_transforms(train=False)
)
return train_set, validation_set
except Exception as e:
raise RuntimeError(f"Error loading datasets: {e}")
def plot_class_distribution(dataset: datasets.CIFAR10, dataset_name: str) -> None:
"""
Plot the distribution of classes in the dataset.
Args:
dataset (datasets.CIFAR10): The dataset to analyze.
dataset_name (str): Name of the dataset (e.g., 'Training', 'Validation').
"""
labels = [label for _, label in dataset]
counter = collections.Counter(labels)
class_counts = {dataset.classes[k]: v for k, v in counter.items()}
print(f"Class distribution for {dataset_name} dataset:")
for cls, count in class_counts.items():
print(f"{cls}: {count}")
plt.figure(figsize=(10, 6))
plt.bar(class_counts.keys(), class_counts.values(), color='skyblue')
plt.xlabel("Classes")
plt.ylabel("Number of Images")
plt.title(f"Class Distribution in {dataset_name} Dataset")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(os.path.join(OUTPUT_DIR, f"class_distribution_{dataset_name.lower()}.png"))
plt.close()
def get_data_loaders(
train_set: datasets.CIFAR10,
validation_set: datasets.CIFAR10,
batch_size: int = BATCH_SIZE
) -> Tuple[DataLoader, DataLoader]:
"""
Create DataLoader objects for training and validation datasets.
Args:
train_set (datasets.CIFAR10): Training dataset.
validation_set (datasets.CIFAR10): Validation dataset.
batch_size (int): Batch size.
Returns:
Tuple[DataLoader, DataLoader]: Training and validation DataLoaders.
"""
num_gpus = torch.cuda.device_count()
try:
train_loader = DataLoader(
train_set,
batch_size=batch_size,
shuffle=True,
num_workers=2 * num_gpus,
pin_memory=True
)
validation_loader = DataLoader(
validation_set,
batch_size=batch_size,
shuffle=False,
num_workers=2 * num_gpus,
pin_memory=True
)
return train_loader, validation_loader
except Exception as e:
raise RuntimeError(f"Error creating data loaders: {e}")
def imshow(
tensor: torch.Tensor,
title: Optional[List[str]] = None,
filename: Optional[str] = None
) -> None:
"""
Display a tensor as an image grid.
Args:
tensor (torch.Tensor): Image tensor.
title (Optional[List[str]]): Titles for each image.
filename (Optional[str]): If provided, save the image grid to this file.
"""
image = torchvision.utils.make_grid(tensor).permute(1, 2, 0).numpy()
image = STD * image + MEAN
image = np.clip(image, 0, 1)
plt.figure(figsize=(10, 10))
plt.imshow(image)
if title:
plt.title(", ".join(title))
plt.axis("off")
if filename:
plt.savefig(os.path.join(OUTPUT_DIR, filename))
else:
plt.show()
plt.close()
def display_sample_images(
loader: DataLoader,
classes: Tuple[str, ...],
filename: Optional[str] = None
) -> None:
"""
Display a batch of sample images from the DataLoader.
Args:
loader (DataLoader): DataLoader to fetch images from.
classes (Tuple[str, ...]): Class names.
filename (Optional[str]): If provided, save the image grid to this file.
"""
try:
inputs, labels = next(iter(loader))
imshow(
inputs[:5],
title=[classes[label] for label in labels[:5]],
filename=filename
)
except Exception as e:
print(f"Error displaying sample images: {e}")
def get_model(num_classes: int = NUM_CLASSES) -> nn.Module:
"""
Initialize the VGG19 model, adjust the classifier, and freeze feature layers.
Args:
num_classes (int): Number of output classes.
Returns:
nn.Module: Modified VGG19 model.
"""
try:
model = models.vgg19(weights=models.VGG19_Weights.IMAGENET1K_V1)
# Modify the classifier
model.classifier[6] = nn.Linear(in_features=4096, out_features=num_classes)
# Freeze convolutional layers
for param in model.features.parameters():
param.requires_grad = False
return model
except Exception as e:
raise RuntimeError(f"Error initializing the model: {e}")
def get_lr(optimizer: optim.Optimizer) -> float:
"""
Get the current learning rate from the optimizer.
Args:
optimizer (optim.Optimizer): Optimizer instance.
Returns:
float: Current learning rate.
"""
return optimizer.param_groups[0]["lr"]
def compute_accuracy(output: torch.Tensor, target: torch.Tensor) -> int:
"""
Compute the number of correct predictions.
Args:
output (torch.Tensor): Model outputs.
target (torch.Tensor): Ground truth labels.
Returns:
int: Number of correct predictions.
"""
preds = output.argmax(dim=1, keepdim=True)
corrects = preds.eq(target.view_as(preds)).sum().item()
return corrects
def train_eval_batch(
loss_func: nn.Module,
model: nn.Module,
inputs: torch.Tensor,
targets: torch.Tensor,
optimizer: Optional[optim.Optimizer] = None
) -> Tuple[float, int]:
"""
Perform a single batch training or evaluation step.
Args:
loss_func (nn.Module): Loss function.
model (nn.Module): Model.
inputs (torch.Tensor): Input data.
targets (torch.Tensor): Ground truth labels.
optimizer (Optional[optim.Optimizer]): Optimizer for training.
Returns:
Tuple[float, int]: Loss value and number of correct predictions.
"""
try:
outputs = model(inputs)
loss = loss_func(outputs, targets)
corrects = compute_accuracy(outputs, targets)
if optimizer:
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss.item(), corrects
except Exception as e:
raise RuntimeError(f"Error in training/evaluation batch: {e}")
def train_validate(
model: nn.Module,
train_loader: DataLoader,
val_loader: DataLoader,
loss_func: nn.Module,
optimizer: optim.Optimizer,
scheduler: optim.lr_scheduler._LRScheduler,
epochs: int = NUM_EPOCHS,
device: torch.device = DEVICE
) -> Tuple[nn.Module, Dict[str, List[float]], Dict[str, List[float]]]:
"""
Train and validate the model.
Args:
model (nn.Module): The model to train.
train_loader (DataLoader): Training DataLoader.
val_loader (DataLoader): Validation DataLoader.
loss_func (nn.Module): Loss function.
optimizer (optim.Optimizer): Optimizer.
scheduler (optim.lr_scheduler._LRScheduler): Learning rate scheduler.
epochs (int): Number of epochs.
device (torch.device): Device to train on.
Returns:
Tuple[nn.Module, Dict[str, List[float]], Dict[str, List[float]]]:
Trained model, loss history, and metric history.
"""
loss_history = {"train": [], "val": []}
metric_history = {"train": [], "val": []}
best_loss = float("inf")
best_model_wts = copy.deepcopy(model.state_dict())
for epoch in range(1, epochs + 1):
print(f"Epoch {epoch}/{epochs}")
print("-" * 10)
# Training phase
model.train()
running_loss = 0.0
running_corrects = 0
for inputs, labels in train_loader:
inputs = inputs.to(device)
labels = labels.to(device)
loss, corrects = train_eval_batch(
loss_func, model, inputs, labels, optimizer
)
running_loss += loss
running_corrects += corrects
epoch_loss = running_loss / len(train_loader.dataset)
epoch_acc = running_corrects / len(train_loader.dataset)
loss_history["train"].append(epoch_loss)
metric_history["train"].append(epoch_acc)
print(f"Train Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}")
# Validation phase
model.eval()
val_loss = 0.0
val_corrects = 0
with torch.no_grad():
for inputs, labels in val_loader:
inputs = inputs.to(device)
labels = labels.to(device)
loss, corrects = train_eval_batch(
loss_func, model, inputs, labels, optimizer=None
)
val_loss += loss
val_corrects += corrects
epoch_val_loss = val_loss / len(val_loader.dataset)
epoch_val_acc = val_corrects / len(val_loader.dataset)
loss_history["val"].append(epoch_val_loss)
metric_history["val"].append(epoch_val_acc)
print(f"Validation Loss: {epoch_val_loss:.4f} Acc: {epoch_val_acc:.4f}")
# Step the scheduler
scheduler.step()
# Deep copy the model if it has the best loss so far
if epoch_val_loss < best_loss:
best_loss = epoch_val_loss
best_model_wts = copy.deepcopy(model.state_dict())
torch.save(best_model_wts, MODEL_WEIGHTS_PATH)
print("Best model weights updated.")
print()
# Load best model weights
model.load_state_dict(best_model_wts)
return model, loss_history, metric_history
def plot_training_history(
loss_history: Dict[str, List[float]],
metric_history: Dict[str, List[float]],
epochs: int = NUM_EPOCHS
) -> None:
"""
Plot the training and validation loss and accuracy.
Args:
loss_history (Dict[str, List[float]]): Loss history.
metric_history (Dict[str, List[float]]): Metric history.
epochs (int): Number of epochs.
"""
try:
fig = make_subplots(
rows=1,
cols=2,
subplot_titles=["Training & Validation Loss", "Training & Validation Accuracy"]
)
# Plot Loss
for phase, color in zip(["train", "val"], ["#F1C40F", "#2ECC71"]):
fig.add_trace(
go.Scatter(
x=list(range(1, epochs + 1)),
y=loss_history[phase],
mode="lines+markers",
name=f"{phase.capitalize()} Loss",
line=dict(color=color)
),
row=1,
col=1
)
# Plot Accuracy
for phase, color in zip(["train", "val"], ["#E74C3C", "#3498DB"]):
fig.add_trace(
go.Scatter(
x=list(range(1, epochs + 1)),
y=metric_history[phase],
mode="lines+markers",
name=f"{phase.capitalize()} Accuracy",
line=dict(color=color)
),
row=1,
col=2
)
fig.update_layout(
height=600,
width=1200,
title_text="Training History",
template="plotly_white"
)
fig.write_image(os.path.join(OUTPUT_DIR, "training_history.png"))
fig.show()
except Exception as e:
print(f"Error plotting training history: {e}")
def visualize_predictions(
model: nn.Module,
img_path: str,
device: torch.device = DEVICE
) -> None:
"""
Visualize model predictions on a single image.
Args:
model (nn.Module): Trained model.
img_path (str): Path to the input image.
device (torch.device): Device to perform computation on.
"""
try:
model.eval()
img = Image.open(img_path).convert("RGB")
transform = get_transforms(train=False)
img_tensor = transform(img).unsqueeze(0).to(device)
with torch.no_grad():
outputs = model(img_tensor)
_, preds = torch.max(outputs, 1)
pred_class = CLASSES[preds.item()]
# Display the image
plt.figure(figsize=(6, 6))
img_display = img_tensor.cpu().squeeze().permute(1, 2, 0).numpy()
img_display = STD * img_display + MEAN
img_display = np.clip(img_display, 0, 1)
plt.imshow(img_display)
plt.title(f"Predicted: {pred_class}")
plt.axis("off")
plt.savefig(os.path.join(OUTPUT_DIR, "prediction_visualization.png"))
plt.show()
plt.close()
except Exception as e:
print(f"Error visualizing predictions: {e}")
finally:
model.train()
def save_model_weights(model: nn.Module, path: str) -> None:
"""
Save the model weights to a specified path.
Args:
model (nn.Module): The model to save.
path (str): File path to save the weights.
"""
try:
torch.save(model.state_dict(), path)
print(f"Model weights saved to {path}")
except Exception as e:
print(f"Error saving model weights: {e}")
def load_model_weights(model: nn.Module, path: str) -> nn.Module:
"""
Load model weights from a specified path.
Args:
model (nn.Module): The model to load weights into.
path (str): File path from where to load the weights.
Returns:
nn.Module: Model with loaded weights.
"""
try:
model.load_state_dict(torch.load(path, map_location=DEVICE))
model.to(DEVICE)
print(f"Model weights loaded from {path}")
return model
except Exception as e:
raise RuntimeError(f"Error loading model weights: {e}")
def main() -> None:
"""Main function to orchestrate the training pipeline."""
set_seed()
# Load datasets
try:
train_set, validation_set = load_datasets()
except RuntimeError as e:
print(e)
return
print(f"Training dataset size: {len(train_set)}")
print(f"Validation dataset size: {len(validation_set)}")
# Plot class distributions
plot_class_distribution(train_set, "Training")
plot_class_distribution(validation_set, "Validation")
# Create data loaders
try:
train_loader, val_loader = get_data_loaders(train_set, validation_set)
except RuntimeError as e:
print(e)
return
# Display sample images
display_sample_images(train_loader, CLASSES, filename="sample_training_images.png")
display_sample_images(val_loader, CLASSES, filename="sample_validation_images.png")
# Initialize the model
try:
model = get_model(num_classes=NUM_CLASSES)
except RuntimeError as e:
print(e)
return
model = model.to(DEVICE)
# Define loss function, optimizer, and scheduler
loss_func = nn.CrossEntropyLoss(reduction="sum")
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
scheduler = CosineAnnealingLR(optimizer, T_max=5, eta_min=1e-6)
# Train and validate the model
try:
model, loss_history, metric_history = train_validate(
model,
train_loader,
val_loader,
loss_func,
optimizer,
scheduler,
epochs=NUM_EPOCHS,
device=DEVICE
)
except RuntimeError as e:
print(e)
return
# Plot training history
plot_training_history(loss_history, metric_history, epochs=NUM_EPOCHS)
# Save the best model weights
save_model_weights(model, MODEL_WEIGHTS_PATH)
# Visualize predictions on a sample image
sample_image_path = "/path/to/your/image.jpg" # Replace with your image path
if os.path.exists(sample_image_path):
visualize_predictions(model, sample_image_path)
else:
print(f"Sample image not found at {sample_image_path}")
print("Training pipeline completed successfully.")
if __name__ == "__main__":
main()
Key Enhancements and Features
-
PEP-8 Compliance and Readability
- The code is structured with clear spacing, indentation, and line lengths as per PEP-8 guidelines.
- Function and variable names are descriptive and follow the snake_case convention.
-
Type Hints
- Comprehensive type hints are added for function arguments and return types to enhance code clarity and facilitate easier maintenance.
-
Modular Design
- The code is broken down into modular functions each handling specific tasks such as data loading, model initialization, training, evaluation, visualization, and saving/loading model weights.
- This modularity ensures that each component can be tested and maintained independently.
-
Error Handling
- Each critical operation is wrapped in try-except blocks to catch and handle exceptions gracefully, providing meaningful error messages.
- This ensures that unexpected errors do not cause the entire pipeline to fail silently.
-
Scalability and Efficiency
- Utilizes
DataLoader with appropriate num_workers based on the number of available GPUs to ensure efficient data loading.
- Freezes the convolutional layers of the pre-trained VGG19 model to reduce memory usage and speed up training.
- Enables
cudnn.benchmark for optimized performance on GPU.
-
Generalization
- The pipeline is designed to be easily adaptable to different datasets and models by modifying constants and parameters.
- Paths for data and outputs are configurable, and the code ensures that output directories are created if they do not exist.
-
Visualization and Output Management
- Plots for class distribution, training history, and sample images are saved to the
output directory.
- The best model weights are saved separately, and there is functionality to visualize predictions on custom images.
-
Maintainability
- Clear function docstrings explain the purpose, arguments, and returns of each function.
- The
main function orchestrates the entire pipeline, making the flow of execution easy to follow.
Instructions to Run the Pipeline
-
Dependencies: Ensure that the following Python packages are installed:
torch
torchvision
numpy
matplotlib
plotly
Pillow
You can install them using pip:
pip install torch torchvision numpy matplotlib plotly Pillow
-
Image Path for Visualization: Update the sample_image_path variable in the main function with the path to an image you want to use for prediction visualization.
-
Execution: Run the script using Python:
python training_pipeline.py
Replace training_pipeline.py with the filename you saved the script as.
-
Outputs:
- All plots and the best model weights will be saved in the
output directory.
- Sample images from training and validation datasets will be saved as
sample_training_images.png and sample_validation_images.png.
- The training history plot will be saved as
training_history.png.
- The prediction visualization will be saved as
prediction_visualization.png if a valid image path is provided.
This refactored pipeline is robust, efficient, and easy to maintain or extend for more complex tasks or different datasets. It provides a solid foundation for building and experimenting with deep learning models in a structured manner.