File size: 9,853 Bytes
9351b33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate every trained model on the unseen test split and time single-image predictions.

Usage:
    python evaluate.py   (after train.py)

Metrics, the per-class report, the most frequent mistakes, timings, the model comparison, and plots are saved
to outputs/evaluation/.
"""
from copy import deepcopy
from functools import partial
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
import torch
from sklearn.metrics import classification_report, precision_recall_fscore_support
from torch.utils.data import DataLoader

from data_setup import BASELINE_TEST_TRANSFORM, BATCH_SIZE, RANDOM_SEED, TEST_TRANSFORM, load_split
from engine import get_device, predict_labels, predict_single_image
from model_builder import create_efficientnet_b0, create_tinyvgg

PROJECT_DIR = Path(__file__).resolve().parent
TRAINING_SUMMARY_PATH = PROJECT_DIR / "outputs" / "training" / "training_summary.csv"
OUTPUT_DIR = PROJECT_DIR / "outputs" / "evaluation"
TIMING_IMAGES = 50

# Rebuild each architecture without downloading pretrained weights, then load the trained checkpoint
ARCHITECTURES = {
    "TinyVGG": (create_tinyvgg, BASELINE_TEST_TRANSFORM),
    "EfficientNet-B0": (partial(create_efficientnet_b0, pretrained=False), TEST_TRANSFORM)
}


def main():
    device = get_device()
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    training_summary = pd.read_csv(TRAINING_SUMMARY_PATH, index_col="model")
    final_model_name = training_summary.index[training_summary["final_model"]][0]

    test_data = load_split("test")
    class_names = test_data.classes
    num_classes = len(class_names)
    test_targets = torch.tensor(test_data._labels)

    trained_models = {}
    for name, row in training_summary.iterrows():
        create_model, test_transform = ARCHITECTURES[row["architecture"]]
        model = create_model(num_classes)
        model.load_state_dict(torch.load(PROJECT_DIR / row["checkpoint"], map_location="cpu", weights_only=True))
        trained_models[name] = (model.to(device), test_transform)

    # Predict all test images with each model and report standard classification metrics
    model_predictions = {}
    metric_rows = []
    for name, (model, test_transform) in trained_models.items():
        test_loader = DataLoader(load_split("test", test_transform), batch_size=BATCH_SIZE, shuffle=False)
        predictions = predict_labels(model, test_loader, device)
        model_predictions[name] = predictions
        macro = precision_recall_fscore_support(test_targets, predictions, average="macro", zero_division=0)
        weighted = precision_recall_fscore_support(test_targets, predictions, average="weighted", zero_division=0)
        metric_rows.append({
            "model": name,
            "accuracy (%)": 100 * (predictions == test_targets).float().mean().item(),
            "macro precision (%)": 100 * macro[0],
            "macro recall (%)": 100 * macro[1],
            "macro F1 (%)": 100 * macro[2],
            "weighted F1 (%)": 100 * weighted[2]
        })
    test_metrics = pd.DataFrame(metric_rows).set_index("model").round(2)
    test_metrics.to_csv(OUTPUT_DIR / "test_metrics.csv")
    print(f"Test metrics ({len(test_data):,} unseen photos):")
    print(test_metrics.to_string(), "\n")

    # Build the final model's per-class report and show its ten weakest classes
    final_predictions = model_predictions[final_model_name]
    class_report = pd.DataFrame(classification_report(
        test_targets, final_predictions, labels=list(range(num_classes)),
        target_names=class_names, output_dict=True, zero_division=0
    )).T.iloc[:num_classes]
    class_report["support"] = class_report["support"].astype(int)
    class_report.round(3).to_csv(OUTPUT_DIR / "class_report.csv", index_label="class")
    print(f"{final_model_name} per-class results:")
    print(f"Classes with perfect F1: {(class_report['f1-score'] == 1).sum()} of {num_classes}")
    print(f"Classes with F1 below 0.80: {(class_report['f1-score'] < 0.8).sum()}")
    print(class_report.sort_values("f1-score").head(10).round(3).to_string(), "\n")

    # Plot the row-normalized confusion matrix, since test classes contain different numbers of images
    confusion_matrix = torch.bincount(
        test_targets * num_classes + final_predictions,
        minlength=num_classes ** 2
    ).reshape(num_classes, num_classes)
    confusion_rates = confusion_matrix / confusion_matrix.sum(dim=1, keepdim=True)
    fig, ax = plt.subplots(figsize=(11, 10))
    heatmap = ax.imshow(confusion_rates.numpy(), cmap="Blues")
    fig.colorbar(heatmap, ax=ax, label="Share of true class predicted")
    ax.set_xlabel("Predicted label")
    ax.set_ylabel("True label")
    ax.set_title(f"{final_model_name} test confusion matrix (row-normalized)")
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "confusion_matrix.png", dpi=100)
    plt.close(fig)

    # List the most frequent mistakes (true class -> predicted class)
    error_counts = confusion_matrix.clone()
    error_counts.fill_diagonal_(0)
    counts, pair_indices = error_counts.flatten().topk(8)
    class_sizes = confusion_matrix.sum(dim=1)
    top_mistakes = pd.DataFrame({
        "true class": [class_names[index // num_classes] for index in pair_indices.tolist()],
        "predicted class": [class_names[index % num_classes] for index in pair_indices.tolist()],
        "count": counts.tolist(),
        "true-class test images": [class_sizes[index // num_classes].item() for index in pair_indices.tolist()]
    })
    top_mistakes.to_csv(OUTPUT_DIR / "top_mistakes.csv", index=False)
    print(f"Correct predictions: {confusion_matrix.diag().sum().item():,}/{confusion_matrix.sum().item():,}")
    print("Most frequent mistakes:")
    print(top_mistakes.to_string(index=False), "\n")

    # Plot nine reproducible mistakes with the predicted and correct labels
    wrong_indices = torch.where(final_predictions != test_targets)[0]
    wrong_order = torch.randperm(
        len(wrong_indices), generator=torch.Generator().manual_seed(RANDOM_SEED)
    )
    fig, axes = plt.subplots(3, 3, figsize=(12, 12))
    for ax, index in zip(axes.flat, wrong_indices[wrong_order[:9]].tolist()):
        image, target = test_data[index]
        ax.imshow(image)
        ax.set_title(
            f"Pred: {class_names[final_predictions[index]]}\nTarget: {class_names[target]}",
            color="red", fontsize=10
        )
        ax.axis("off")
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "mistakes.png", dpi=80)
    plt.close(fig)

    # Time each model on the CPU with one thread, as the web app runs (fastest for single images on an M1 Pro)
    torch.set_num_threads(1)
    image_index = torch.randint(
        len(test_data), (1,), generator=torch.Generator().manual_seed(RANDOM_SEED)
    ).item()
    image, target = test_data[image_index]
    single_image_seconds = {}
    for name, (model, test_transform) in trained_models.items():
        cpu_model = deepcopy(model).to("cpu")
        # Run once untimed so the timer excludes first-call setup
        predict_single_image(cpu_model, image, test_transform, "cpu")
        pred_probs, seconds = predict_single_image(cpu_model, image, test_transform, "cpu")
        single_image_seconds[name] = seconds
        prediction = pred_probs.argmax().item()
        print(
            f"{name} | Pred: {class_names[prediction]} ({pred_probs[prediction]:.2%}) | "
            f"Target: {class_names[target]} | Prediction time: {seconds:.4f} seconds"
        )

    # Time the final model on the training device too
    final_model, _ = trained_models[final_model_name]
    predict_single_image(final_model, image, TEST_TRANSFORM, device)
    final_probs, device_seconds = predict_single_image(final_model, image, TEST_TRANSFORM, device)
    print(f"{final_model_name} on {device}: {device_seconds:.4f} seconds\n")

    fig, ax = plt.subplots(figsize=(6, 6))
    ax.imshow(image)
    ax.set_title(
        f"Pred: {class_names[final_probs.argmax()]} ({final_probs.max():.2%}) | Target: {class_names[target]}\n"
        f"CPU prediction time: {single_image_seconds[final_model_name]:.4f} seconds"
    )
    ax.axis("off")
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "single_prediction.png", dpi=80)
    plt.close(fig)

    # Repeat the CPU timer on 50 test photos to check that the single-image time is typical
    timing_indices = torch.randperm(
        len(test_data), generator=torch.Generator().manual_seed(RANDOM_SEED)
    )[:TIMING_IMAGES].tolist()
    final_cpu_model = deepcopy(final_model).to("cpu")
    timing_seconds = pd.Series([
        predict_single_image(final_cpu_model, test_data[index][0], TEST_TRANSFORM, "cpu")[1]
        for index in timing_indices
    ], name="seconds")
    timing_seconds.to_csv(OUTPUT_DIR / "cpu_timing.csv", index_label="photo")
    print(f"{final_model_name} CPU time over {TIMING_IMAGES} test photos:")
    print(timing_seconds.describe().round(4).to_string(), "\n")

    # Organize test metrics, model size, training time, and inference time in one output
    model_comparison = test_metrics.copy()
    model_comparison["validation loss"] = training_summary["val_loss"].round(4)
    model_comparison["total parameters"] = training_summary["total_parameters"]
    model_comparison["trainable parameters"] = training_summary["trainable_parameters"]
    model_comparison["restored epoch"] = training_summary["restored_epoch"]
    model_comparison["training seconds"] = training_summary["training_seconds"].round(1)
    model_comparison["CPU seconds per image"] = pd.Series(single_image_seconds).round(4)
    model_comparison.to_csv(OUTPUT_DIR / "model_comparison.csv")
    print("Model comparison:")
    print(model_comparison.astype(object).T.to_string())
    print(f"\nSaved tables and plots to {OUTPUT_DIR}")


if __name__ == "__main__":
    main()