To create a comprehensive and robust image classification evaluation pipeline adhering to the provided specifications, we can achieve this using the PyTorch framework along with necessary libraries for metric computations. We'll structure it in a way that makes the code scalable and reusable. Below is the implementation:
import torch
import torch.nn.functional as F
from typing import Union, Tuple, List, Optional
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, log_loss,
confusion_matrix, mean_absolute_error, mean_squared_error, matthews_corrcoef,
balanced_accuracy_score, jaccard_score, cohen_kappa_score, roc_curve
)
import numpy as np
def compute_metrics(
outputs: Union[np.ndarray, torch.Tensor],
labels: Union[np.ndarray, torch.Tensor],
num_classes: int,
top_k: Optional[int] = None
) -> dict:
# Convert torch Tensor to numpy array if necessary
if isinstance(outputs, torch.Tensor):
outputs = outputs.detach().cpu().numpy()
if isinstance(labels, torch.Tensor):
labels = labels.detach().cpu().numpy()
if outputs.ndim == 1 or outputs.shape[1] == 1:
# For binary classification
predictions = (outputs > 0.5).astype(int)
else:
# For multiclass classification
predictions = np.argmax(outputs, axis=1)
if top_k is not None:
top_k_preds = np.argsort(outputs, axis=1)[:, -top_k:]
metrics = {
'Accuracy': accuracy_score(labels, predictions),
'Precision': precision_score(labels, predictions, average='weighted', zero_division=0),
'Recall': recall_score(labels, predictions, average='weighted', zero_division=0),
'F1 Score': f1_score(labels, predictions, average='weighted', zero_division=0),
'Log Loss': log_loss(labels, outputs),
'Balanced Accuracy': balanced_accuracy_score(labels, predictions),
'Matthews Correlation Coefficient': matthews_corrcoef(labels, predictions),
'Jaccard Index': jaccard_score(labels, predictions, average='weighted', zero_division=0),
'Cohen’s Kappa': cohen_kappa_score(labels, predictions),
'Mean Absolute Error': mean_absolute_error(labels, predictions),
'Mean Squared Error': mean_squared_error(labels, predictions)
}
if num_classes > 2:
metrics['AUC-ROC'] = roc_auc_score(labels, outputs, multi_class='ovo', average='weighted')
else:
metrics['AUC-ROC'] = roc_auc_score(labels, outputs)
if top_k is not None:
metrics['Top-K Accuracy'] = np.mean([
label in top_k_preds[i] for i, label in enumerate(labels)
])
conf_matrix = confusion_matrix(labels, predictions)
tn, fp, fn, tp = conf_matrix.ravel()
metrics.update({
'Confusion Matrix': conf_matrix,
'Specificity': tn / (tn + fp),
'False Positive Rate (FPR)': fp / (fp + tn),
'False Negative Rate (FNR)': fn / (fn + tp),
'True Positive Rate (TPR)': tp / (tp + fn),
'False Discovery Rate (FDR)': fp / (tp + fp),
'F-beta Score': f1_score(labels, predictions, average='weighted', zero_division=0) # Customize for different beta if needed
})
return metrics
def evaluate_model(
model: torch.nn.Module,
dataloader: torch.utils.data.DataLoader,
device: torch.device,
num_classes: int,
criterion: Optional[torch.nn.Module] = None,
top_k: Optional[int] = None
) -> Tuple[float, dict]:
model.eval()
total_loss = 0.0
all_outputs = []
all_labels = []
with torch.no_grad():
for inputs, labels in dataloader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
if criterion:
loss = criterion(outputs, labels)
total_loss += loss.item()
all_outputs.append(outputs)
all_labels.append(labels)
all_outputs = torch.cat(all_outputs)
all_labels = torch.cat(all_labels)
metrics = compute_metrics(all_outputs, all_labels, num_classes, top_k)
return total_loss / len(dataloader), metrics
Key Points:
- Device Handling: We make sure to move the tensors (inputs and labels) to the appropriate device (CPU/GPU) before processing.
- Error Handling: Our implementation is designed to avoid divisions by zero by using the
zero_division=0 parameter in metrics functions from sklearn.
- Type Hints: We use Python type hints from the
typing module to enhance readability and maintainability.
- Metric Computation: We provide a comprehensive set of classification metrics.
- Generalization: The
compute_metrics function is easily extendable to add more metrics if needed.
- Model Compatibility: We abstract the evaluation into
evaluate_model which takes a PyTorch model and DataLoader.
This code provides a robust, flexible, and scalable image classification evaluation pipeline using PyTorch and Scikit-learn.