Files
product-detection/2_product-classifier.ipynb
T
2026-05-12 11:16:56 +02:00

1.4 MiB

🛒 Product Classifier — Training Notebook

Trains a lightweight EfficientNet-B0 (ImageNet pre-trained) on shelf product crops generated by 1_generate_crop_dataset.py.


✅ Before you run

  1. Runtime → Change runtime type → GPU (T4 is free and enough for this)
  2. Upload your crops_dataset/ as a Kaggle Dataset and attach it via + Add Data
  3. Update DATA_DIR in Cell 2 — Configuration to match your dataset path
  4. Run all cells top-to-bottom

📂 Expected dataset layout

/kaggle/input/your-dataset-name/
    train/
        cola_can/   img001.jpg …
        pepsi_can/  img002.jpg …
        lays_chips/ img003.jpg …
    val/
        cola_can/   …
        …

📦 Outputs saved to /kaggle/working/runs/classify/

File Description
best.pt Best checkpoint (highest val accuracy)
last.pt Last epoch checkpoint
class_names.json {idx: class_name} mapping for inference
training_curves.png Loss & accuracy plots
In [16]:
# ── Cell 1 — Install / verify dependencies ────────────────────────────────────
# Kaggle kernels ship with torch & torchvision pre-installed.
# We only need tqdm (already present) — nothing extra to install.

import sys, subprocess

def run(cmd):
    subprocess.run(cmd, shell=True, check=True)

# Verify GPU is visible
import torch
print(f"PyTorch  : {torch.__version__}")
print(f"CUDA     : {torch.version.cuda}")
print(f"GPU      : {torch.cuda.get_device_name(0) if torch.cuda.is_available() else '⚠ NOT available — check runtime settings'}")
print(f"VRAM     : {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB" if torch.cuda.is_available() else "")
PyTorch  : 2.10.0+cu128
CUDA     : 12.8
GPU      : Tesla T4
VRAM     : 15.6 GB
In [17]:
# ── Cell 2 — Configuration  (edit this cell) ──────────────────────────────────
from pathlib import Path

# ── Paths ──────────────────────────────────────────────────────────────────────
# Point this to the root of your attached dataset (the folder that contains train/ and val/)
DATA_DIR   = Path("/kaggle/input/datasets/triztechdata/product-dataset/crops_dataset")   # ← CHANGE THIS
OUTPUT_DIR = Path("/kaggle/working/runs/classify")

# ── Model ──────────────────────────────────────────────────────────────────────
# Choices: "efficientnet_b0" | "efficientnet_b2" | "mobilenet_v3_small" | "resnet50"
MODEL_NAME      = "efficientnet_b0"
FREEZE_BACKBONE = False   # True = only train the head (faster, good for small datasets)

# ── Training hyperparameters ───────────────────────────────────────────────────
EPOCHS       = 50
BATCH_SIZE   = 64
IMG_SIZE     = 224
LR           = 1e-3
WEIGHT_DECAY = 1e-4
PATIENCE     = 10     # early-stop if val accuracy does not improve for this many epochs
NUM_WORKERS  = 2      # Kaggle kernels: keep ≤ 2 to avoid DataLoader warnings
USE_AMP      = True   # Automatic Mixed Precision — speeds up training on GPU
SEED         = 42

# ── Sanity check ───────────────────────────────────────────────────────────────
assert (DATA_DIR / "train").exists(), f"train/ not found inside {DATA_DIR}"
assert (DATA_DIR / "val").exists(),   f"val/   not found inside {DATA_DIR}"
print(f"✓ DATA_DIR   : {DATA_DIR}")
print(f"✓ OUTPUT_DIR : {OUTPUT_DIR}")
print(f"✓ Model      : {MODEL_NAME}  |  Freeze backbone: {FREEZE_BACKBONE}")
print(f"✓ Epochs     : {EPOCHS}  |  Batch: {BATCH_SIZE}  |  LR: {LR}  |  AMP: {USE_AMP}")
✓ DATA_DIR   : /kaggle/input/datasets/triztechdata/product-dataset/crops_dataset
✓ OUTPUT_DIR : /kaggle/working/runs/classify
✓ Model      : efficientnet_b0  |  Freeze backbone: False
✓ Epochs     : 50  |  Batch: 64  |  LR: 0.001  |  AMP: True
In [18]:
# ── Cell 2b — Dataset diagnostics (run before training) ────────────────
# Prints per-class image counts and flags classes with too few samples.
# A val loss stuck at ~5 almost always means imbalance or too few images.
from pathlib import Path as _Path
from collections import Counter
import math

def diagnose_split(split: str):
    split_dir = DATA_DIR / split
    if not split_dir.exists():
        print(f'  {split}/ not found')
        return {}
    counts = {}
    for cls in sorted(split_dir.iterdir()):
        if cls.is_dir():
            n = sum(1 for f in cls.iterdir() if f.suffix.lower() in {'.jpg','.jpeg','.png'})
            counts[cls.name] = n
    return counts

train_c = diagnose_split('train')
val_c   = diagnose_split('val')

print(f'{"-"*60}')
print(f'  {"Class":<28} {"Train":>7} {"Val":>7}  Notes')
print(f'{"-"*60}')
all_classes = sorted(set(train_c) | set(val_c))
for cls in all_classes:
    tr = train_c.get(cls, 0)
    vl = val_c.get(cls, 0)
    notes = []
    if tr < 20:  notes.append('⚠ train<20')
    if vl < 5:   notes.append('⚠ val<5')
    if tr == 0:  notes.append('❌ missing in train!')
    if vl == 0:  notes.append('❌ missing in val!')
    print(f'  {cls:<28} {tr:>7} {vl:>7}  {" ".join(notes)}')
print(f'{"-"*60}')
print(f'  {"TOTAL":<28} {sum(train_c.values()):>7} {sum(val_c.values()):>7}')
print(f'{"-"*60}')

if train_c:
    ratio = max(train_c.values()) / max(min(train_c.values()), 1)
    print(f'\n  Imbalance ratio : {ratio:.1f}x')
    print(f'  Random-chance loss (ln {len(all_classes)}) : {math.log(len(all_classes)):.3f}')
    print(f'  If val loss ≈ {math.log(len(all_classes)):.1f} and flat -> model is guessing randomly')
    print(f'  If val loss > {math.log(len(all_classes)):.1f}         -> model is confidently wrong')
    if ratio > 5:
        print('\n  ⚠  Imbalance >5x detected — WeightedRandomSampler is already enabled in Cell 5.')
    if min(train_c.values()) < 20:
        print('\n  ⚠  Some classes have <20 training images.')
        print('     Recommended minimums: train>=50, val>=10 per class.')
        print('     Consider: --freeze_backbone True (head-only training) for small datasets.')
------------------------------------------------------------
  Class                          Train     Val  Notes
------------------------------------------------------------
  1001                             231      43  
  1001 Gold                        104      20  
  A100                              26       5  
  Aroma                             60      11  
  Aroma Espresso                   105      20  
  Aroma Familial                    80      15  
  Aroma Gold                        40       8  
  Bonal                            106      20  
  Bonal Excellence                  43       8  
  Cafe D Or Caps                    72      14  
  Canastel                          24       4  ⚠ val<5
  Caps                              36       7  
  CityOne Instant Coffee            30       6  
  Dozia                             29       6  
  El Kabir                          37       7  
  Facto                             82      15  
  Facto no                          28       5  
  Famico                           490      92  
  Famico Caps                      114      21  
  Famico Exclusive                 175      33  
  Molino                           131      25  
  Mundo                             55      10  
  Mundo Caps                        61      11  
  Nizier                            97      18  
  Nouara                            28       5  
  Oscar                             83      16  
  Primo                            173      33  
  Ricamar Thon                     128      24  
  Siglo                             30       6  
  Skor                              45       9  
------------------------------------------------------------
  TOTAL                           2743     517
------------------------------------------------------------

  Imbalance ratio : 20.4x
  Random-chance loss (ln 30) : 3.401
  If val loss ≈ 3.4 and flat -> model is guessing randomly
  If val loss > 3.4         -> model is confidently wrong

  ⚠  Imbalance >5x detected — WeightedRandomSampler is already enabled in Cell 5.
In [19]:
# ── Cell 3 — Imports ─────────────────────────────────────────────────────────
import json
import time

import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.cuda.amp import GradScaler, autocast
from torchvision import datasets, models, transforms
from torchvision.models import (
    EfficientNet_B0_Weights,
    EfficientNet_B2_Weights,
    MobileNet_V3_Small_Weights,
    ResNet50_Weights,
)
import matplotlib.pyplot as plt
import matplotlib
from tqdm.notebook import tqdm          # notebook-aware progress bars
from IPython.display import display     # for inline plot updates

matplotlib.rcParams["figure.dpi"] = 120
torch.manual_seed(SEED)
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Running on: {DEVICE}")
Running on: cuda
In [20]:
# ── Cell 4 — Dataset exploration ─────────────────────────────────────────────
import os
from collections import Counter

def count_split(split_dir: Path):
    """Return {class_name: image_count} for one split directory."""
    counts = {}
    for cls_dir in sorted(split_dir.iterdir()):
        if cls_dir.is_dir():
            n = sum(1 for f in cls_dir.iterdir() if f.suffix.lower() in
                    {".jpg", ".jpeg", ".png", ".bmp", ".webp"})
            counts[cls_dir.name] = n
    return counts

train_counts = count_split(DATA_DIR / "train")
val_counts   = count_split(DATA_DIR / "val")

print(f"Classes found : {len(train_counts)}")
print(f"Train images  : {sum(train_counts.values()):,}")
print(f"Val images    : {sum(val_counts.values()):,}")
print()

# Bar chart of class distribution
fig, axes = plt.subplots(1, 2, figsize=(14, max(4, len(train_counts) * 0.35)))
for ax, counts, title in zip(axes, [train_counts, val_counts], ["Train", "Val"]):
    classes = list(counts.keys())
    values  = list(counts.values())
    ax.barh(classes, values, color="steelblue")
    ax.set_title(f"{title} split ({sum(values):,} images)")
    ax.set_xlabel("Image count")
    for i, v in enumerate(values):
        ax.text(v + 0.5, i, str(v), va="center", fontsize=8)
plt.tight_layout()
plt.savefig(OUTPUT_DIR / "class_distribution.png", bbox_inches="tight")
plt.show()
Classes found : 30
Train images  : 2,743
Val images    : 517

In [21]:
# ── Cell 5 — Data loaders + balanced sampler ────────────────────────────────
import numpy as np
from torch.utils.data import WeightedRandomSampler

MEAN = [0.485, 0.456, 0.406]
STD  = [0.229, 0.224, 0.225]

train_tf = transforms.Compose([
    transforms.RandomResizedCrop(IMG_SIZE, scale=(0.7, 1.0)),
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.2, hue=0.05),
    transforms.RandomGrayscale(p=0.05),
    transforms.ToTensor(),
    transforms.Normalize(MEAN, STD),
])
val_tf = transforms.Compose([
    transforms.Resize(int(IMG_SIZE * 1.15)),
    transforms.CenterCrop(IMG_SIZE),
    transforms.ToTensor(),
    transforms.Normalize(MEAN, STD),
])

train_set = datasets.ImageFolder(str(DATA_DIR / 'train'), transform=train_tf)
val_set   = datasets.ImageFolder(str(DATA_DIR / 'val'),   transform=val_tf)

CLASS_NAMES = train_set.classes
NUM_CLASSES = len(CLASS_NAMES)

# ── Weighted sampler: every class gets equal expected frequency ───────────
# This prevents dominant classes from drowning out rare ones.
# If your classes are already balanced, this is a no-op in effect.
targets      = train_set.targets                          # list of int labels
class_counts = np.bincount(targets)                       # images per class
class_weights = 1.0 / class_counts                        # inverse frequency
sample_weights = class_weights[targets]                   # weight per sample

sampler = WeightedRandomSampler(
    weights     = sample_weights,
    num_samples = len(train_set),
    replacement = True,                                   # allows oversampling rare classes
)

train_loader = DataLoader(train_set, batch_size=BATCH_SIZE, sampler=sampler,
                          num_workers=NUM_WORKERS, pin_memory=True)
val_loader   = DataLoader(val_set,   batch_size=BATCH_SIZE, shuffle=False,
                          num_workers=NUM_WORKERS, pin_memory=True)

# ── Class imbalance report ──────────────────────────────────────────
print(f'Classes ({NUM_CLASSES}):')
max_count = class_counts.max()
for i, (cls, cnt) in enumerate(zip(CLASS_NAMES, class_counts)):
    bar  = '█' * int(20 * cnt / max_count)
    flag = '  ⚠ LOW' if cnt < 20 else ''
    print(f'  {cls:<28} {cnt:>5}  {bar}{flag}')
print(f'  Imbalance ratio: {max_count / class_counts.min():.1f}x  '
      f'(max {max_count} / min {class_counts.min()})')

# ── Save class mapping ─────────────────────────────────────────────
class_map = {i: c for i, c in enumerate(CLASS_NAMES)}
with open(OUTPUT_DIR / 'class_names.json', 'w') as f:
    json.dump(class_map, f, indent=2)
print(f'\n✓ class_names.json saved')

# ── Sample grid ────────────────────────────────────────────────────
import torchvision
sample_imgs, _ = next(iter(train_loader))
sample_imgs = sample_imgs[:16]
inv_mean = torch.tensor(MEAN).view(3,1,1)
inv_std  = torch.tensor(STD).view(3,1,1)
grid_imgs = torch.clamp(sample_imgs * inv_std + inv_mean, 0, 1)
grid = torchvision.utils.make_grid(grid_imgs, nrow=8, padding=2)
plt.figure(figsize=(14, 4))
plt.imshow(grid.permute(1, 2, 0).numpy())
plt.title('Sample training crops (augmented)')
plt.axis('off')
plt.show()
Classes (30):
  1001                           231  █████████
  1001 Gold                      104  ████
  A100                            26  █
  Aroma                           60  ██
  Aroma Espresso                 105  ████
  Aroma Familial                  80  ███
  Aroma Gold                      40  █
  Bonal                          106  ████
  Bonal Excellence                43  █
  Cafe D Or Caps                  72  ██
  Canastel                        24  
  Caps                            36  █
  CityOne Instant Coffee          30  █
  Dozia                           29  █
  El Kabir                        37  █
  Facto                           82  ███
  Facto no                        28  █
  Famico                         490  ████████████████████
  Famico Caps                    114  ████
  Famico Exclusive               175  ███████
  Molino                         131  █████
  Mundo                           55  ██
  Mundo Caps                      61  ██
  Nizier                          97  ███
  Nouara                          28  █
  Oscar                           83  ███
  Primo                          173  ███████
  Ricamar Thon                   128  █████
  Siglo                           30  █
  Skor                            45  █
  Imbalance ratio: 20.4x  (max 490 / min 24)

✓ class_names.json saved
In [22]:
# ── Cell 6 — Model factory ───────────────────────────────────────────────────
def build_model(name: str, num_classes: int, freeze_backbone: bool) -> nn.Module:
    if name == "efficientnet_b0":
        m = models.efficientnet_b0(weights=EfficientNet_B0_Weights.IMAGENET1K_V1)
        if freeze_backbone:
            for p in m.features.parameters():
                p.requires_grad = False
        m.classifier[1] = nn.Linear(m.classifier[1].in_features, num_classes)

    elif name == "efficientnet_b2":
        m = models.efficientnet_b2(weights=EfficientNet_B2_Weights.IMAGENET1K_V1)
        if freeze_backbone:
            for p in m.features.parameters():
                p.requires_grad = False
        m.classifier[1] = nn.Linear(m.classifier[1].in_features, num_classes)

    elif name == "mobilenet_v3_small":
        m = models.mobilenet_v3_small(weights=MobileNet_V3_Small_Weights.IMAGENET1K_V1)
        if freeze_backbone:
            for p in m.features.parameters():
                p.requires_grad = False
        m.classifier[3] = nn.Linear(m.classifier[3].in_features, num_classes)

    elif name == "resnet50":
        m = models.resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)
        if freeze_backbone:
            for pname, p in m.named_parameters():
                if "fc" not in pname:
                    p.requires_grad = False
        m.fc = nn.Linear(m.fc.in_features, num_classes)

    else:
        raise ValueError(f"Unknown model: {name}")

    return m


model = build_model(MODEL_NAME, NUM_CLASSES, FREEZE_BACKBONE).to(DEVICE)

trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
total     = sum(p.numel() for p in model.parameters())
print(f"Model        : {MODEL_NAME}")
print(f"Total params : {total:,}")
print(f"Trainable    : {trainable:,}  ({trainable/total*100:.1f}%)")
Model        : efficientnet_b0
Total params : 4,045,978
Trainable    : 4,045,978  (100.0%)
In [23]:
# ── Cell 7 — Optimiser, scheduler, loss ──────────────────────────────────────
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)

optimizer = torch.optim.AdamW(
    filter(lambda p: p.requires_grad, model.parameters()),
    lr=LR,
    weight_decay=WEIGHT_DECAY,
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
scaler    = GradScaler() if (USE_AMP and DEVICE.type == "cuda") else None

print(f"Optimiser : AdamW  lr={LR}  weight_decay={WEIGHT_DECAY}")
print(f"Scheduler : CosineAnnealingLR  T_max={EPOCHS}")
print(f"AMP       : {'enabled' if scaler else 'disabled'}")
Optimiser : AdamW  lr=0.001  weight_decay=0.0001
Scheduler : CosineAnnealingLR  T_max=50
AMP       : enabled
/tmp/ipykernel_57/958891556.py:10: FutureWarning: `torch.cuda.amp.GradScaler(args...)` is deprecated. Please use `torch.amp.GradScaler('cuda', args...)` instead.
  scaler    = GradScaler() if (USE_AMP and DEVICE.type == "cuda") else None
In [24]:
# ── Cell 8 — Training helpers ────────────────────────────────────────────────
def run_epoch(model, loader, criterion, optimizer, device, scaler, train: bool):
    model.train(train)
    total_loss, correct, total = 0.0, 0, 0

    ctx = torch.enable_grad() if train else torch.no_grad()
    with ctx:
        desc = "  train" if train else "  val  "
        for imgs, labels in tqdm(loader, desc=desc, leave=False):
            imgs, labels = imgs.to(device), labels.to(device)

            with autocast(enabled=(scaler is not None)):
                logits = model(imgs)
                loss   = criterion(logits, labels)

            if train:
                optimizer.zero_grad(set_to_none=True)
                if scaler:
                    scaler.scale(loss).backward()
                    scaler.step(optimizer)
                    scaler.update()
                else:
                    loss.backward()
                    optimizer.step()

            total_loss += loss.item() * imgs.size(0)
            correct    += (logits.argmax(1) == labels).sum().item()
            total      += imgs.size(0)

    return total_loss / total, correct / total


def plot_live(history, fig, axes):
    """Redraw training curves in-place so they update each epoch."""
    epochs = range(1, len(history["train_loss"]) + 1)
    for ax in axes:
        ax.cla()

    axes[0].plot(epochs, history["train_loss"], "b-o", ms=3, label="Train")
    axes[0].plot(epochs, history["val_loss"],   "r-o", ms=3, label="Val")
    axes[0].set_title("Loss"); axes[0].set_xlabel("Epoch")
    axes[0].legend(); axes[0].grid(alpha=0.3)

    axes[1].plot(epochs, history["train_acc"], "b-o", ms=3, label="Train")
    axes[1].plot(epochs, history["val_acc"],   "r-o", ms=3, label="Val")
    axes[1].set_title("Accuracy"); axes[1].set_xlabel("Epoch")
    axes[1].set_ylim(0, 1); axes[1].legend(); axes[1].grid(alpha=0.3)

    fig.tight_layout()
    display(fig)
    plt.pause(0.01)

print("✓ Training helpers defined")
✓ Training helpers defined
In [25]:
# ── Cell 9 — Training loop ───────────────────────────────────────────────────
from IPython.display import clear_output

history = {"train_loss": [], "train_acc": [], "val_loss": [], "val_acc": []}
best_val_acc = 0.0
patience_ctr = 0

fig, axes = plt.subplots(1, 2, figsize=(12, 4))
plt.ion()    # interactive mode so curves update live

epoch_bar = tqdm(range(1, EPOCHS + 1), desc="Epochs", unit="ep")

for epoch in epoch_bar:
    t0 = time.time()

    train_loss, train_acc = run_epoch(model, train_loader, criterion,
                                      optimizer, DEVICE, scaler, train=True)
    val_loss,   val_acc   = run_epoch(model, val_loader,   criterion,
                                      None, DEVICE, None, train=False)
    scheduler.step()
    elapsed = time.time() - t0

    history["train_loss"].append(train_loss)
    history["train_acc"].append(train_acc)
    history["val_loss"].append(val_loss)
    history["val_acc"].append(val_acc)

    improved = val_acc > best_val_acc

    # ── Epoch summary line ───────────────────────────────────────────────────
    epoch_bar.set_postfix({
        "tr_loss": f"{train_loss:.4f}",
        "tr_acc":  f"{train_acc:.4f}",
        "val_acc": f"{val_acc:.4f}",
        "best":    f"{best_val_acc:.4f}",
        "⏱":      f"{elapsed:.1f}s",
    })

    # ── Save checkpoints ─────────────────────────────────────────────────────
    ckpt = {
        "epoch":       epoch,
        "model_state": model.state_dict(),
        "class_names": CLASS_NAMES,
        "val_acc":     val_acc,
        "args": {
            "model":           MODEL_NAME,
            "img_size":        IMG_SIZE,
            "freeze_backbone": FREEZE_BACKBONE,
        },
    }

    if improved:
        best_val_acc = val_acc
        patience_ctr = 0
        torch.save(ckpt, OUTPUT_DIR / "best.pt")
    else:
        patience_ctr += 1

    torch.save(ckpt, OUTPUT_DIR / "last.pt")

    # ── Live curve update ────────────────────────────────────────────────────
    clear_output(wait=True)
    plot_live(history, fig, axes)

    # ── Early stopping ───────────────────────────────────────────────────────
    if patience_ctr >= PATIENCE:
        print(f"\n⚠ Early stopping — no improvement for {PATIENCE} epochs")
        break

plt.ioff()
Out [25]:
⚠ Early stopping — no improvement for 10 epochs
<contextlib.ExitStack at 0x78029ff4f6b0>
In [26]:
# ── Cell 10 — Final training curves ─────────────────────────────────────────
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
epochs_x = range(1, len(history["train_loss"]) + 1)

ax1.plot(epochs_x, history["train_loss"], "b-o", ms=4, label="Train")
ax1.plot(epochs_x, history["val_loss"],   "r-o", ms=4, label="Val")
ax1.set_title("Loss"); ax1.set_xlabel("Epoch"); ax1.legend(); ax1.grid(alpha=0.3)

ax2.plot(epochs_x, history["train_acc"], "b-o", ms=4, label="Train")
ax2.plot(epochs_x, history["val_acc"],   "r-o", ms=4, label="Val")
ax2.set_title("Accuracy"); ax2.set_xlabel("Epoch")
ax2.set_ylim(0, 1); ax2.legend(); ax2.grid(alpha=0.3)

fig.tight_layout()
fig.savefig(OUTPUT_DIR / "training_curves.png", dpi=150)
plt.show()

print(f"\n{'═'*50}")
print(f"  Training complete!")
print(f"  Best val accuracy : {best_val_acc:.4f}")
print(f"  Epochs trained    : {len(history['train_loss'])}")
print(f"  Outputs saved to  : {OUTPUT_DIR}")
print(f"{'═'*50}")
══════════════════════════════════════════════════
  Training complete!
  Best val accuracy : 0.9749
  Epochs trained    : 17
  Outputs saved to  : /kaggle/working/runs/classify
══════════════════════════════════════════════════
In [27]:
# ── Cell 11 — Per-class validation accuracy ──────────────────────────────────
# Load best checkpoint and evaluate per class on the val set

best_ckpt = torch.load(OUTPUT_DIR / "best.pt", map_location=DEVICE)
model.load_state_dict(best_ckpt["model_state"])
model.eval()

class_correct = [0] * NUM_CLASSES
class_total   = [0] * NUM_CLASSES

with torch.no_grad():
    for imgs, labels in tqdm(val_loader, desc="Evaluating", leave=False):
        imgs, labels = imgs.to(DEVICE), labels.to(DEVICE)
        preds = model(imgs).argmax(1)
        for pred, label in zip(preds, labels):
            class_correct[label] += int(pred == label)
            class_total[label]   += 1

per_class_acc = [
    class_correct[i] / class_total[i] if class_total[i] > 0 else 0.0
    for i in range(NUM_CLASSES)
]

# Sort by accuracy
sorted_idx = sorted(range(NUM_CLASSES), key=lambda i: per_class_acc[i])
sorted_cls = [CLASS_NAMES[i] for i in sorted_idx]
sorted_acc = [per_class_acc[i] for i in sorted_idx]

fig, ax = plt.subplots(figsize=(10, max(4, NUM_CLASSES * 0.4)))
colors = ["#d9534f" if a < 0.5 else "#f0ad4e" if a < 0.8 else "#5cb85c" for a in sorted_acc]
bars = ax.barh(sorted_cls, sorted_acc, color=colors)
ax.set_xlim(0, 1)
ax.axvline(0.8, color="gray", linestyle="--", linewidth=0.8, label="80% threshold")
ax.set_xlabel("Validation accuracy")
ax.set_title("Per-class validation accuracy (best checkpoint)")
ax.legend()
for bar, acc in zip(bars, sorted_acc):
    ax.text(min(acc + 0.01, 0.96), bar.get_y() + bar.get_height()/2,
            f"{acc:.2%}", va="center", fontsize=8)
plt.tight_layout()
plt.savefig(OUTPUT_DIR / "per_class_accuracy.png", dpi=150)
plt.show()

# Print struggling classes
struggling = [(CLASS_NAMES[i], per_class_acc[i]) for i in range(NUM_CLASSES)
              if per_class_acc[i] < 0.8]
if struggling:
    print("\n⚠ Classes below 80% accuracy (may need more data or augmentation):")
    for cls, acc in sorted(struggling, key=lambda x: x[1]):
        print(f"   {cls:<30} {acc:.2%}")
else:
    print("\n✓ All classes above 80% — great training run!")
Evaluating:   0%|          | 0/9 [00:00<?, ?it/s]
⚠ Classes below 80% accuracy (may need more data or augmentation):
   Aroma Gold                     75.00%
In [28]:
# ── Cell 12 — Confusion matrix ───────────────────────────────────────────────
import numpy as np

conf_matrix = np.zeros((NUM_CLASSES, NUM_CLASSES), dtype=int)

with torch.no_grad():
    for imgs, labels in tqdm(val_loader, desc="Confusion matrix", leave=False):
        imgs = imgs.to(DEVICE)
        preds = model(imgs).argmax(1).cpu()
        for pred, label in zip(preds, labels):
            conf_matrix[label][pred] += 1

# Normalise rows to percentages
row_sums = conf_matrix.sum(axis=1, keepdims=True).clip(min=1)
conf_norm = conf_matrix / row_sums

fig_size = max(8, NUM_CLASSES * 0.6)
fig, ax = plt.subplots(figsize=(fig_size, fig_size))
im = ax.imshow(conf_norm, interpolation="nearest", cmap="Blues", vmin=0, vmax=1)
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)

tick_marks = np.arange(NUM_CLASSES)
ax.set_xticks(tick_marks); ax.set_xticklabels(CLASS_NAMES, rotation=45, ha="right", fontsize=7)
ax.set_yticks(tick_marks); ax.set_yticklabels(CLASS_NAMES, fontsize=7)
ax.set_ylabel("True label"); ax.set_xlabel("Predicted label")
ax.set_title("Normalised Confusion Matrix (val set)")

# Annotate cells with percentage
thresh = 0.5
for i in range(NUM_CLASSES):
    for j in range(NUM_CLASSES):
        ax.text(j, i, f"{conf_norm[i,j]:.0%}",
                ha="center", va="center",
                color="white" if conf_norm[i,j] > thresh else "black",
                fontsize=max(5, 9 - NUM_CLASSES // 5))

plt.tight_layout()
plt.savefig(OUTPUT_DIR / "confusion_matrix.png", dpi=150)
plt.show()
Confusion matrix:   0%|          | 0/9 [00:00<?, ?it/s]
In [29]:
# ── Cell 13 — List output files ──────────────────────────────────────────────
print("Files saved to /kaggle/working/runs/classify/")
print()
for f in sorted(OUTPUT_DIR.rglob("*")):
    size = f.stat().st_size / 1e6 if f.is_file() else 0
    label = f"  {f.name:<30} {size:.2f} MB" if f.is_file() else f"  📁 {f.name}/"
    print(label)

print()
print("➜ Download best.pt + class_names.json and drop them next to 3_inference.py")
Files saved to /kaggle/working/runs/classify/

  best.pt                        16.46 MB
  class_distribution.png         0.10 MB
  class_names.json               0.00 MB
  confusion_matrix.png           0.22 MB
  last.pt                        16.46 MB
  per_class_accuracy.png         0.17 MB
  training_curves.png            0.05 MB

➜ Download best.pt + class_names.json and drop them next to 3_inference.py