import os
from typing import List, Tuple, Dict
import torch
from torch import nn, optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
from transformers import AutoProcessor, CLIPModel
from datasets import load_dataset
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
classification_report, confusion_matrix
)
import plotly.express as px
import pandas as pd
import plotly.io as pio
from tqdm import tqdm
class CIFAR10Dataset(Dataset):
"""Custom Dataset for CIFAR-10 images."""
def __init__(self, dataset_split, labels: List[str]):
self.dataset_split = dataset_split
self.labels = labels
def __len__(self) -> int:
return len(self.dataset_split)
def __getitem__(self, idx: int) -> Dict[str, any]:
try:
image = self.dataset_split[idx]['img']
label = self.dataset_split[idx]['label']
label_text = self.labels[label]
return {
'image': image,
'label': label,
'label_text': label_text
}
except Exception as error:
print(f'Error fetching item at index {idx}: {error}')
return None
class CLIPClassifier(nn.Module):
"""Classifier Model on top of CLIP's image embeddings."""
def __init__(self, num_classes: int):
super(CLIPClassifier, self).__init__()
self.clip_model = CLIPModel.from_pretrained('openai/clip-vit-base-patch32')
# Freeze CLIP parameters
for param in self.clip_model.parameters():
param.requires_grad = False
self.classifier = nn.Linear(self.clip_model.config.projection_dim, num_classes)
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
image_features = self.clip_model.get_image_features(pixel_values=pixel_values)
logits = self.classifier(image_features)
return logits
def train(
model: nn.Module,
dataloader: DataLoader,
optimizer: optim.Optimizer,
criterion: nn.Module,
device: torch.device
) -> Tuple[float, float]:
model.train()
total_loss = 0.0
correct = 0
total = 0
for batch in tqdm(dataloader, desc='Training'):
if batch is None:
continue
try:
images = batch['image']
labels = batch['label']
# Process images
inputs = processor(images=images, return_tensors='pt').to(device)
pixel_values = inputs['pixel_values']
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(pixel_values)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
total_loss += loss.item() * labels.size(0)
_, preds = torch.max(outputs, 1)
correct += (preds == labels).sum().item()
total += labels.size(0)
except Exception as error:
print(f'Error during training batch: {error}')
continue
avg_loss = total_loss / total
accuracy = correct / total
return avg_loss, accuracy
def evaluate(
model: nn.Module,
dataloader: DataLoader,
criterion: nn.Module,
device: torch.device
) -> Tuple[float, float]:
model.eval()
total_loss = 0.0
correct = 0
total = 0
with torch.no_grad():
for batch in tqdm(dataloader, desc='Evaluation'):
if batch is None:
continue
try:
images = batch['image']
labels = batch['label']
# Process images
inputs = processor(images=images, return_tensors='pt').to(device)
pixel_values = inputs['pixel_values']
labels = labels.to(device)
outputs = model(pixel_values)
loss = criterion(outputs, labels)
total_loss += loss.item() * labels.size(0)
_, preds = torch.max(outputs, 1)
correct += (preds == labels).sum().item()
total += labels.size(0)
except Exception as error:
print(f'Error during evaluation batch: {error}')
continue
avg_loss = total_loss / total
accuracy = correct / total
return avg_loss, accuracy
def get_predictions(
model: nn.Module,
dataloader: DataLoader,
device: torch.device
) -> Tuple[List[int], List[int]]:
model.eval()
all_preds = []
all_labels = []
with torch.no_grad():
for batch in tqdm(dataloader, desc='Inference'):
if batch is None:
continue
try:
images = batch['image']
labels = batch['label']
# Process images
inputs = processor(images=images, return_tensors='pt').to(device)
pixel_values = inputs['pixel_values']
labels = labels.to(device)
outputs = model(pixel_values)
_, preds = torch.max(outputs, 1)
all_preds.extend(preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
except Exception as error:
print(f'Error during inference batch: {error}')
continue
return all_labels, all_preds
def plot_confusion_matrix(conf_matrix, labels, filename):
df_cm = pd.DataFrame(conf_matrix, index=labels, columns=labels)
fig = px.imshow(
df_cm,
text_auto=True,
labels=dict(x='Predicted', y='Actual', color='Count'),
x=labels,
y=labels,
color_continuous_scale='Blues'
)
fig.update_layout(title='Confusion Matrix')
pio.write_html(fig, file=filename, auto_open=False)
def plot_metrics(df_metrics, filename_prefix):
# Plot Loss
fig_loss = px.line(
df_metrics,
x='epoch',
y=['train_loss', 'eval_loss'],
labels={'value': 'Loss', 'variable': 'Loss Type'},
title='Training and Evaluation Loss over Epochs'
)
pio.write_html(fig_loss, file=f'{filename_prefix}_loss.html', auto_open=False)
# Plot Accuracy
fig_acc = px.line(
df_metrics,
x='epoch',
y=['train_accuracy', 'eval_accuracy'],
labels={'value': 'Accuracy', 'variable': 'Accuracy Type'},
title='Training and Evaluation Accuracy over Epochs'
)
pio.write_html(fig_acc, file=f'{filename_prefix}_accuracy.html', auto_open=False)
if __name__ == '__main__':
# Define device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
try:
# Load CLIP model and processor
processor = AutoProcessor.from_pretrained('openai/clip-vit-base-patch32')
except Exception as error:
print(f'Error loading processor: {error}')
exit(1)
try:
# Load CIFAR-10 dataset
dataset = load_dataset('cifar10')
except Exception as error:
print(f'Error loading dataset: {error}')
exit(1)
# Prepare labels
labels = dataset['train'].features['label'].names
# Create datasets and dataloaders
batch_size = 64
num_workers = 4 # Adjust based on your system
train_dataset = CIFAR10Dataset(dataset_split=dataset['train'], labels=labels)
test_dataset = CIFAR10Dataset(dataset_split=dataset['test'], labels=labels)
train_loader = DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers
)
test_loader = DataLoader(
test_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers
)
# Initialize model, criterion, optimizer
num_classes = len(labels)
model = CLIPClassifier(num_classes=num_classes).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr=1e-4)
# Training loop
num_epochs = 10
train_losses = []
train_accuracies = []
eval_losses = []
eval_accuracies = []
for epoch in range(num_epochs):
print(f'Epoch {epoch+1}/{num_epochs}')
train_loss, train_acc = train(model, train_loader, optimizer, criterion, device)
eval_loss, eval_acc = evaluate(model, test_loader, criterion, device)
train_losses.append(train_loss)
train_accuracies.append(train_acc)
eval_losses.append(eval_loss)
eval_accuracies.append(eval_acc)
print(f'Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f}')
print(f'Eval Loss: {eval_loss:.4f}, Eval Acc: {eval_acc:.4f}')
# Save model weights
weights_dir = './model_weights'
os.makedirs(weights_dir, exist_ok=True)
torch.save(model.state_dict(), os.path.join(weights_dir, 'clip_classifier.pth'))
# Generate predictions on test set
y_true, y_pred = get_predictions(model, test_loader, device)
# Compute metrics
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred, average='weighted', zero_division=0)
recall = recall_score(y_true, y_pred, average='weighted', zero_division=0)
f1 = f1_score(y_true, y_pred, average='weighted', zero_division=0)
print(f'\nFinal Test Metrics:')
print(f'Accuracy: {accuracy:.4f}')
print(f'Precision: {precision:.4f}')
print(f'Recall: {recall:.4f}')
print(f'F1 Score: {f1:.4f}')
print('\nClassification Report:')
print(classification_report(y_true, y_pred, target_names=labels, zero_division=0))
# Generate confusion matrix
conf_matrix = confusion_matrix(y_true, y_pred)
plot_confusion_matrix(conf_matrix, labels, 'confusion_matrix.html')
# Prepare metrics DataFrame
epochs = list(range(1, num_epochs + 1))
df_metrics = pd.DataFrame({
'epoch': epochs,
'train_loss': train_losses,
'train_accuracy': train_accuracies,
'eval_loss': eval_losses,
'eval_accuracy': eval_accuracies
})
plot_metrics(df_metrics, 'training_metrics')
Explanation:
- PEP-8 Compliance: The code follows PEP-8 standards with proper indentation, naming conventions, and line lengths.
- Type Hints: Functions and classes include type hints for inputs and outputs, enhancing code readability and maintainability.
- Time & Space Efficiency: The model leverages the pre-trained CLIP model, freezing its parameters to save computation and only training a classifier on top. Data loading is optimized using
DataLoader with batch processing.
- Error Handling: Try-except blocks are added to catch exceptions during data fetching, training, evaluation, and inference, providing informative error messages.
- Scalability: The use of DataLoaders, batching, and efficient data processing ensures the code can handle larger datasets.
- Robustness: The code includes checks and error handling to handle unexpected conditions gracefully.
- Plotting with Plotly: Training losses and accuracies are plotted using Plotly and saved as HTML files. The confusion matrix is also visualized and saved.
- Saving Weights: Model weights are saved in the
./model_weights directory.
Notes:
- Adjust the
num_workers parameter in DataLoader based on your system capabilities.
- Ensure all required packages are installed, including
torch, transformers, datasets, plotly, and tqdm.
- For large datasets or longer training, consider implementing checkpointing to save and resume training.
- Modify
num_epochs and batch_size based on the desired training time and system memory constraints.
Usage:
Run the script in an environment where the necessary packages are installed. The training and evaluation progress will be displayed in the console, and the plots and model weights will be saved in the specified directories.
Disclaimer: Ensure that you have the necessary hardware (GPU) to run the training efficiently. Training deep learning models can be computationally intensive.