from __future__ import annotations import argparse import json import random from pathlib import Path import numpy as np import torch from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, f1_score from torch import nn from torch.utils.data import DataLoader, TensorDataset class SmallCNN(nn.Module): def __init__(self, num_classes: int = 10) -> None: super().__init__() self.features = nn.Sequential( nn.Conv2d(1, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(32, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Dropout2d(0.08), nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Conv2d(64, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.MaxPool2d(2), nn.Dropout2d(0.12), nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d((1, 1)), ) self.classifier = nn.Sequential( nn.Flatten(), nn.Dropout(0.2), nn.Linear(128, num_classes), ) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.classifier(self.features(x)) def main() -> int: parser = argparse.ArgumentParser(description="Train a compact CNN on UFO-MNIST.") parser.add_argument("--dataset", type=Path, default=Path("data/ufo_mnist_v1/ufo_mnist_28x28.npz")) parser.add_argument("--output", type=Path, default=Path("data/ufo_mnist_v1/cnn_metrics.json")) parser.add_argument("--epochs", type=int, default=35) parser.add_argument("--batch-size", type=int, default=128) parser.add_argument("--seed", type=int, default=1337) args = parser.parse_args() random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.backends.mps.is_available(): device = torch.device("mps") elif torch.cuda.is_available(): device = torch.device("cuda") else: device = torch.device("cpu") data = np.load(args.dataset) class_names = [str(name) for name in data["class_names"]] train_x = torch.from_numpy(data["train_images"].astype(np.float32) / 255.0).unsqueeze(1) test_x = torch.from_numpy(data["test_images"].astype(np.float32) / 255.0).unsqueeze(1) train_y = torch.from_numpy(data["train_labels"].astype(np.int64)) test_y = torch.from_numpy(data["test_labels"].astype(np.int64)) generator = torch.Generator().manual_seed(args.seed) train_loader = DataLoader( TensorDataset(train_x, train_y), batch_size=args.batch_size, shuffle=True, generator=generator, ) test_loader = DataLoader(TensorDataset(test_x, test_y), batch_size=args.batch_size) model = SmallCNN(num_classes=len(class_names)).to(device) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs) loss_fn = nn.CrossEntropyLoss() history: list[dict[str, float | int]] = [] for epoch in range(1, args.epochs + 1): model.train() total_loss = 0.0 total_seen = 0 correct = 0 for batch_x, batch_y in train_loader: batch_x = batch_x.to(device) batch_y = batch_y.to(device) optimizer.zero_grad(set_to_none=True) logits = model(batch_x) loss = loss_fn(logits, batch_y) loss.backward() optimizer.step() total_loss += float(loss.detach().cpu()) * batch_x.size(0) total_seen += batch_x.size(0) correct += int((logits.argmax(dim=1) == batch_y).sum().detach().cpu()) scheduler.step() test_acc, test_loss, _, _ = evaluate(model, test_loader, loss_fn, device) row = { "epoch": epoch, "train_loss": total_loss / total_seen, "train_accuracy": correct / total_seen, "test_loss": test_loss, "test_accuracy": test_acc, } history.append(row) print( f"epoch {epoch:02d} " f"train_loss={row['train_loss']:.4f} train_acc={row['train_accuracy']:.4f} " f"test_loss={test_loss:.4f} test_acc={test_acc:.4f}" ) test_acc, test_loss, y_true, y_pred = evaluate(model, test_loader, loss_fn, device) report = classification_report(y_true, y_pred, target_names=class_names, output_dict=True, zero_division=0) metrics = { "model": "SmallCNN: 3 convolutional blocks + batch norm + dropout + AdamW", "dataset": str(args.dataset), "device": str(device), "epochs": args.epochs, "batch_size": args.batch_size, "seed": args.seed, "train_examples": int(train_x.shape[0]), "test_examples": int(test_x.shape[0]), "test_loss": float(test_loss), "accuracy": float(accuracy_score(y_true, y_pred)), "macro_f1": float(f1_score(y_true, y_pred, average="macro")), "weighted_f1": float(f1_score(y_true, y_pred, average="weighted")), "classification_report": report, "confusion_matrix": confusion_matrix(y_true, y_pred).tolist(), "class_names": class_names, "history": history, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(metrics, indent=2, sort_keys=True) + "\n", encoding="utf-8") print(f"accuracy: {metrics['accuracy']:.4f}") print(f"macro_f1: {metrics['macro_f1']:.4f}") print(f"weighted_f1: {metrics['weighted_f1']:.4f}") print(f"wrote: {args.output}") return 0 @torch.no_grad() def evaluate( model: nn.Module, loader: DataLoader, loss_fn: nn.Module, device: torch.device, ) -> tuple[float, float, list[int], list[int]]: model.eval() total_loss = 0.0 total_seen = 0 correct = 0 y_true: list[int] = [] y_pred: list[int] = [] for batch_x, batch_y in loader: batch_x = batch_x.to(device) batch_y = batch_y.to(device) logits = model(batch_x) loss = loss_fn(logits, batch_y) pred = logits.argmax(dim=1) total_loss += float(loss.detach().cpu()) * batch_x.size(0) total_seen += batch_x.size(0) correct += int((pred == batch_y).sum().detach().cpu()) y_true.extend(batch_y.detach().cpu().tolist()) y_pred.extend(pred.detach().cpu().tolist()) return correct / total_seen, total_loss / total_seen, y_true, y_pred if __name__ == "__main__": raise SystemExit(main())