File size: 11,469 Bytes
c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 5e96bc9 c3d45c0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 |
from src.model import Classifier
from src.dataloader import ImageDataset,collate_fn
from torch.utils.data import DataLoader
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch
import random
import numpy as np
import torch.nn as nn
import time
from sklearn.metrics import (
confusion_matrix,
classification_report,
roc_curve,
auc
)
from sklearn.preprocessing import label_binarize
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
def model_evaluation(model, val_set, device,batch_size=32,num_workers=0, class_names=None):
model.eval()
all_preds = []
all_probs = []
all_labels = []
val_loader = DataLoader(
val_set,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers
)
with torch.no_grad():
for images, labels in val_loader:
if images.ndim == 4 and images.shape[-1] in (1, 3):
images = images.permute(0, 3, 1, 2)
images = images.to(device)
labels = labels.to(device)
logits = model(images)
probs = torch.softmax(logits, dim=1)
preds = torch.argmax(probs, dim=1)
all_preds.append(preds.cpu().numpy())
all_probs.append(probs.cpu().numpy())
all_labels.append(labels.cpu().numpy())
y_true = np.concatenate(all_labels)
y_pred = np.concatenate(all_preds)
y_prob = np.concatenate(all_probs)
num_classes = y_prob.shape[1]
if class_names is None:
class_names = [f"Class {i}" for i in range(num_classes)]
cm = confusion_matrix(y_true, y_pred)
cm_fig, ax = plt.subplots(figsize=(6, 6))
im = ax.imshow(cm)
ax.set_title("Confusion Matrix")
ax.set_xlabel("Predicted")
ax.set_ylabel("True")
ax.set_xticks(range(num_classes))
ax.set_yticks(range(num_classes))
ax.set_xticklabels(class_names, rotation=75)
ax.set_yticklabels(class_names)
for i in range(num_classes):
for j in range(num_classes):
ax.text(j, i, cm[i, j], ha="center", va="center")
plt.tight_layout()
report = classification_report(
y_true, y_pred,
target_names=class_names,
output_dict=True
)
cr_fig, ax = plt.subplots(figsize=(12, 8))
ax.axis("off")
table_data = []
headers = ["Class", "Precision", "Recall", "F1", "Support"]
for cls in class_names:
row = report[cls]
table_data.append([
cls,
f"{row['precision']:.3f}",
f"{row['recall']:.3f}",
f"{row['f1-score']:.3f}",
int(row['support'])
])
accuracy = report["accuracy"]
macro_avg = report["macro avg"]
weighted_avg = report["weighted avg"]
table_data.append([
"Accuracy",
f"{accuracy:.3f}",
"",
"",
""
])
table_data.append([
"Macro Avg",
f"{macro_avg['precision']:.3f}",
f"{macro_avg['recall']:.3f}",
f"{macro_avg['f1-score']:.3f}",
f"{int(macro_avg['support'])}" if 'support' in macro_avg else ""
])
table_data.append([
"Weighted Avg",
f"{weighted_avg['precision']:.3f}",
f"{weighted_avg['recall']:.3f}",
f"{weighted_avg['f1-score']:.3f}",
f"{int(weighted_avg['support'])}" if 'support' in weighted_avg else ""
])
table = ax.table(
cellText=table_data,
colLabels=headers,
loc="center"
)
table.scale(1, 2)
ax.set_title("Classification Report")
y_true_bin = label_binarize(y_true, classes=list(range(num_classes)))
roc_fig, ax = plt.subplots(figsize=(6, 6))
for i in range(num_classes):
fpr, tpr, _ = roc_curve(y_true_bin[:, i], y_prob[:, i])
roc_auc = auc(fpr, tpr)
ax.plot(fpr, tpr, label=f"{class_names[i]} (AUC={roc_auc:.3f})")
ax.plot([0, 1], [0, 1], linestyle="--")
ax.set_xlabel("False Positive Rate")
ax.set_ylabel("True Positive Rate")
ax.set_title("ROC-AUC Curve")
ax.legend()
ax.grid(True)
return cm_fig, cr_fig, roc_fig
class ModelTrainer:
def __init__(self,model : Classifier,train_set : ImageDataset,val_set : ImageDataset = None, batch_size=32,lr = 1e-3,device='cpu',return_fig=False, seed=None):
g = torch.Generator()
if seed is not None:
g.manual_seed(seed)
self.train_loader = DataLoader(
train_set,
batch_size,
shuffle=True,
collate_fn=collate_fn,
worker_init_fn=seed_worker,
generator=g
)
self.device = device
if val_set is not None:
self.val_loader = DataLoader(
val_set,
batch_size,
shuffle=False,
collate_fn=collate_fn,
worker_init_fn=seed_worker
)
else:
self.val_loader = None
self.class_names = model.classes
self.model = model
self.lr = lr
self.optim = optim.Adam(model.parameters(), lr=lr, weight_decay=1e-4)
self.optim.zero_grad()
self.criterion = nn.CrossEntropyLoss()
self.return_fig=return_fig
self.best_model_state = None
self.best_val_acc = 0.0
self.interrupt=False
def visualize_batch(self, imgs, preds, labels, class_names=None, max_samples=4):
first_image = imgs
if isinstance(imgs, list):
imgs = np.stack(imgs, axis=0)
imgs = torch.from_numpy(imgs).permute(0, 3, 1, 2).float()
imgs_np = imgs.cpu().numpy()
preds = preds.cpu().numpy()
labels = labels.cpu().numpy()
batch_size = imgs_np.shape[0]
indices = random.sample(range(batch_size), min(max_samples, batch_size))
first_image = first_image[indices[0]]
fig_pred = plt.figure(figsize=(6 * len(indices), 5))
grid = fig_pred.add_gridspec(1, len(indices))
for col, idx in enumerate(indices):
ax = fig_pred.add_subplot(grid[0, col])
ax.imshow(imgs_np[idx].transpose(1, 2, 0))
if class_names:
title = f"P: {class_names[preds[idx]]} | T: {class_names[labels[idx]]}"
else:
title = f"P: {preds[idx]} | T: {labels[idx]}"
ax.set_title(title)
ax.axis("off")
fig_pred.tight_layout()
raw_features = self.model.visualize_feature(first_image,show=False)
feature_figs = []
for f in raw_features:
if isinstance(f, plt.Figure):
feature_figs.append(f)
continue
if hasattr(f, "mode"):
f = np.array(f)
h, w = f.shape[:2]
dpi = 100
fig_w = max(4, w / dpi)
fig_h = max(4, h / dpi)
fig = plt.figure(figsize=(fig_w, fig_h), dpi=dpi)
ax = fig.add_subplot(111)
ax.imshow(f)
ax.axis("off")
feature_figs.append(fig)
all_figs = [fig_pred] + feature_figs
if not self.return_fig:
plt.show()
plt.close(fig_pred)
if self.return_fig:
return all_figs
else:
return None
def train_one_epoch(self,epoch):
self.model.train()
total_loss = 0
train_pbar = tqdm(self.train_loader, desc="Training",leave=False)
correct = 0
total = 0
for imgs, labels in train_pbar:
if self.interrupt:
break
labels = labels.to(self.device)
# Forward
outputs = self.model(imgs)
loss = self.criterion(outputs, labels)
# Backward
self.optim.zero_grad()
loss.backward()
self.optim.step()
preds = outputs.argmax(dim=1)
correct += (preds == labels).sum().item()
total += labels.size(0)
total_loss += loss.item()
train_pbar.set_postfix(acc=correct/total,loss=loss.item())
avg_loss = total_loss / len(self.train_loader)
avg_acc = correct / total
return avg_loss,avg_acc
def train(self, epochs=10, visualize_every=5):
train_losses=[]
train_accuracies=[]
val_losses=[]
val_accuracies=[]
for epoch in range(1, epochs + 1):
train_loss,train_acc = self.train_one_epoch(epoch)
if self.interrupt:
return
train_losses.append(train_loss)
train_accuracies.append(train_acc)
if self.val_loader is not None:
val_loss,val_acc,fig=self.validate(epoch, visualize=(epoch % visualize_every == 0 or epoch == 1))
if self.interrupt:
return
val_losses.append(val_loss)
val_accuracies.append(val_acc)
print(f"Epoch {epoch} Train Loss: {train_loss:.4f} | Train Acc : {train_acc:.4f} | Val Loss : {val_loss:.4f} | Val Acc : {val_acc:.4f}")
if val_acc > self.best_val_acc:
print(f"New best model found at epoch {epoch} (Val Acc: {val_acc:.4f})")
self.best_val_acc = val_acc
self.best_model_state = {k: v.clone() for k, v in self.model.state_dict().items()}
yield train_loss,train_acc,val_loss,val_acc,fig
else:
print(f"Epoch {epoch} Train Loss: {train_loss:.4f} | Train Acc : {train_acc:.4f}")
yield train_loss,train_acc,None,None,None
if self.best_model_state is not None:
self.model.load_state_dict(self.best_model_state)
print(f"Best model (Val Acc: {self.best_val_acc:.4f}) loaded into trainer.model")
yield train_losses,train_accuracies,val_losses,val_accuracies,None
def validate(self,epoch, visualize=False):
if self.val_loader is None:
return
self.model.eval()
total_loss = 0
correct = 0
total = 0
val_imgs_display = None
val_preds_display = None
val_labels_display = None
val_pbar = tqdm(self.val_loader, desc="Validation",leave=False)
fig = None
with torch.no_grad():
for imgs, labels in val_pbar:
if self.interrupt:
break
labels = labels.to(self.device)
outputs = self.model(imgs)
loss = self.criterion(outputs, labels)
total_loss += loss.item()
preds = outputs.argmax(dim=1)
correct += (preds == labels).sum().item()
total += labels.size(0)
if visualize and val_imgs_display is None:
val_imgs_display = imgs
val_preds_display = preds
val_labels_display = labels
val_pbar.set_postfix(loss=loss.item(), acc=correct / total)
avg_loss = total_loss / len(self.val_loader)
acc = correct / total
if visualize and val_imgs_display is not None:
fig = self.visualize_batch(val_imgs_display, val_preds_display, val_labels_display, self.class_names)
return avg_loss,acc,fig |