from pathlib import Path
import io
import json
import zipfile
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
from torchvision.models import (vgg16, VGG16_Weights,
mobilenet_v2, MobileNet_V2_Weights,
resnet18, ResNet18_Weights)
SEED = 42
np.random.seed(SEED % (2**32))
torch.manual_seed(SEED)
torch.set_num_threads(min(6, torch.get_num_threads()))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path('work/results') if Path('work').exists() else Path('results')
OUT.mkdir(parents=True, exist_ok=True)
torch.hub.set_dir(str((OUT / 'torch_cache').resolve()))
def show_inline():
plt.show()
ZIP = Path('work/tiny-imagenet-200.zip') if Path('work').exists() else Path('tiny-imagenet-200.zip')
if not ZIP.exists():
from urllib.request import urlretrieve
urlretrieve('http://cs231n.stanford.edu/tiny-imagenet-200.zip', ZIP)
with zipfile.ZipFile(ZIP) as z:
wnids = z.read('tiny-imagenet-200/wnids.txt').decode().splitlines()
selected = wnids[:3] # fixed three classes, 200 images each
words = dict(line.split('\t', 1) for line in z.read('tiny-imagenet-200/words.txt').decode().splitlines())
labels = [words[w].split(',')[0] for w in selected]
arrays, targets = [], []
for class_index, wnid in enumerate(selected):
paths = sorted(p for p in z.namelist() if p.startswith(f'tiny-imagenet-200/train/{wnid}/images/') and p.endswith('.JPEG'))[:200]
if len(paths) != 200:
raise ValueError(f'Expected 200 images for {wnid}, found {len(paths)}')
for path in paths:
with Image.open(io.BytesIO(z.read(path))) as image:
arrays.append(np.asarray(image.convert('RGB').resize((64, 64)), dtype=np.uint8))
targets.append(class_index)
images = np.stack(arrays)
targets = np.asarray(targets)
assert images.shape == (600, 64, 64, 3)
# 70/15/15 stratified split: 140/30/30 per class.
split_rng = np.random.default_rng(SEED)
train_ids, val_ids, test_ids = [], [], []
for cls in range(3):
ids = split_rng.permutation(np.where(targets == cls)[0])
train_ids.extend(ids[:140]); val_ids.extend(ids[140:170]); test_ids.extend(ids[170:200])
train_ids = np.array(train_ids); val_ids = np.array(val_ids); test_ids = np.array(test_ids)
pixels = torch.from_numpy(images.copy()).permute(0, 3, 1, 2).float() / 255
y = torch.from_numpy(targets).long()
mean = torch.tensor([0.485, 0.456, 0.406])[None, :, None, None]
std = torch.tensor([0.229, 0.224, 0.225])[None, :, None, None]
pixels_imagenet = (pixels - mean) / std
print('Selected classes:', list(zip(selected, labels)))
print('Dataset shape:', images.shape, 'Split:', len(train_ids), len(val_ids), len(test_ids))
def make_loader(x, ids, shuffle=False, batch_size=32):
return DataLoader(TensorDataset(x[ids], y[ids]), batch_size=batch_size, shuffle=shuffle)
def train_model(model, train_loader, val_loader, epochs=12, patience=3, lr=1e-3):
model.to(DEVICE)
optimizer = torch.optim.Adam((p for p in model.parameters() if p.requires_grad), lr=lr)
loss_fn = nn.CrossEntropyLoss()
history = {'train_loss': [], 'val_loss': []}
best_loss, stale, best_state = float('inf'), 0, None
for epoch in range(epochs):
model.train(); running = count = 0
for xb, yb in train_loader:
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
optimizer.zero_grad()
loss = loss_fn(model(xb), yb)
loss.backward(); optimizer.step()
running += loss.item() * len(xb); count += len(xb)
history['train_loss'].append(running / count)
model.eval(); running = count = 0
with torch.no_grad():
for xb, yb in val_loader:
xb, yb = xb.to(DEVICE), yb.to(DEVICE)
running += loss_fn(model(xb), yb).item() * len(xb); count += len(xb)
val_loss = running / count
history['val_loss'].append(val_loss)
print(f'Epoch {epoch+1}: train loss={history["train_loss"][-1]:.4f}, val loss={val_loss:.4f}', flush=True)
if val_loss < best_loss - 1e-4:
best_loss, stale = val_loss, 0
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
else:
stale += 1
if stale >= patience:
print('Early stopping')
break
model.load_state_dict(best_state)
return model, history
def evaluate(model, loader):
model.eval(); predicted = []; actual = []
with torch.no_grad():
for xb, yb in loader:
predicted.extend(model(xb.to(DEVICE)).argmax(1).cpu().tolist())
actual.extend(yb.tolist())
p, r, f, _ = precision_recall_fscore_support(actual, predicted, average='macro', zero_division=0)
return {'accuracy': round(accuracy_score(actual, predicted), 4),
'precision': round(p, 4), 'recall': round(r, 4), 'f1': round(f, 4)}
class CustomCNN(nn.Module):
def __init__(self):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
nn.AdaptiveAvgPool2d((1, 1)))
self.classifier = nn.Sequential(nn.Flatten(), nn.Dropout(.3), nn.Linear(64, 3))
def forward(self, x):
return self.classifier(self.features(x))
custom, history = train_model(CustomCNN(), make_loader(pixels, train_ids, True),
make_loader(pixels, val_ids), epochs=12, patience=3)
results = {'Custom CNN': evaluate(custom, make_loader(pixels, test_ids))}
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(np.arange(1, len(history['train_loss']) + 1), history['train_loss'], marker='o', label='Training')
ax.plot(np.arange(1, len(history['val_loss']) + 1), history['val_loss'], marker='o', label='Validation')
ax.set(xlabel='Epoch', ylabel='Cross-entropy loss', title='Custom CNN learning curves')
ax.legend(); ax.grid(alpha=.25)
fig.tight_layout(); fig.savefig(OUT / 'assignment_11_loss_curves.png', dpi=150); show_inline(); plt.close(fig)
print('Custom CNN test metrics:', results['Custom CNN'])
def transfer_backbone(name):
if name == 'VGG16':
model = vgg16(weights=VGG16_Weights.DEFAULT)
model.avgpool = nn.AdaptiveAvgPool2d((1, 1))
dimension = 512
elif name == 'MobileNetV2':
model = mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT)
dimension = 1280
elif name == 'ResNet18':
model = resnet18(weights=ResNet18_Weights.DEFAULT)
dimension = 512
return model.to(DEVICE).eval(), dimension
def frozen_features(model, name, x, batch_size=32):
chunks = []
resnet_body = nn.Sequential(*list(model.children())[:-1]) if name == 'ResNet18' else None
with torch.no_grad():
for batch in x.split(batch_size):
batch = batch.to(DEVICE)
if name == 'VGG16':
feature = model.avgpool(model.features(batch)).flatten(1)
elif name == 'MobileNetV2':
feature = nn.functional.adaptive_avg_pool2d(model.features(batch), 1).flatten(1)
else:
feature = resnet_body(batch).flatten(1)
chunks.append(feature.cpu())
return torch.cat(chunks)
for name in ('VGG16', 'MobileNetV2', 'ResNet18'):
print('Training', name, flush=True)
backbone, dimension = transfer_backbone(name)
features = frozen_features(backbone, name, pixels_imagenet)
del backbone
if torch.cuda.is_available():
torch.cuda.empty_cache()
head, model_history = train_model(nn.Linear(dimension, 3),
make_loader(features, train_ids, True), make_loader(features, val_ids),
epochs=30, patience=4, lr=1e-3)
results[name] = evaluate(head, make_loader(features, test_ids))
print(name, 'test metrics:', results[name], flush=True)
del head, features
fig, ax = plt.subplots(figsize=(8, 4))
names = list(results)
for j, metric in enumerate(('accuracy', 'precision', 'recall', 'f1')):
ax.bar(np.arange(len(names)) + (j - 1.5) * .18, [results[n][metric] for n in names],
width=.18, label=metric.title())
ax.set_xticks(np.arange(len(names)), names)
ax.set(ylim=(0, 1), ylabel='Score', title='Test set comparison, 90 images')
ax.legend(ncol=4, loc='upper center', fontsize=8)
fig.tight_layout(); fig.savefig(OUT / 'assignment_11_comparison.png', dpi=150); show_inline(); plt.close(fig)
(OUT / 'metrics_11.json').write_text(json.dumps({'selected_wnids': selected, 'class_names': labels,
'split': {'train': 420, 'validation': 90, 'test': 90},
'custom_history': history, 'results': results}, indent=2))
print('Final comparison:', results)