File size: 9,886 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
"""Train the TinyVGG baseline and two EfficientNet-B0 models, then save the final model for the web app.

Usage:
    python train.py

Training histories, the learning-rate sweep, the training summary, and training curves are saved to
outputs/training/. Every model's weights are saved to checkpoints/, and the final model is also saved to models/.
"""
import json
import shutil
from copy import deepcopy
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
import torch
from torch import nn

from data_setup import (BASELINE_TEST_TRANSFORM, BASELINE_TRAIN_TRANSFORM, RANDOM_SEED,
                        TEST_TRANSFORM, TRAIN_TRANSFORM, create_dataloaders)
from engine import get_device, test_step, train_model, train_step
from model_builder import (count_parameters, create_efficientnet_b0, create_tinyvgg,
                           unfreeze_last_blocks)

PROJECT_DIR = Path(__file__).resolve().parent
CHECKPOINT_DIR = PROJECT_DIR / "checkpoints"
MODEL_DIR = PROJECT_DIR / "models"
EXAMPLE_DIR = PROJECT_DIR / "examples"
OUTPUT_DIR = PROJECT_DIR / "outputs" / "training"
FINAL_MODEL_PATH = MODEL_DIR / "flowers102_efficientnet_b0.pth"

MAX_EPOCHS = 30
PATIENCE = 5
BASELINE_LEARNING_RATE = 1e-3
SWEEP_EPOCHS = 5
SWEEP_LEARNING_RATES = [1e-4, 1e-3, 1e-2]
UNFROZEN_BLOCKS = 3


def create_scheduler(optimizer):
    # Halve the learning rate after 2 epochs without validation-loss improvement
    return torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.5, patience=2)


def sweep_learning_rates(num_classes, train_loader, val_loader, loss_fn, device):
    # Train a fresh head for five epochs at each learning rate and score it on the validation split
    rows = []
    for learning_rate in SWEEP_LEARNING_RATES:
        torch.manual_seed(RANDOM_SEED)
        model = create_efficientnet_b0(num_classes).to(device)
        optimizer = torch.optim.Adam(model.classifier.parameters(), lr=learning_rate)
        for epoch in range(SWEEP_EPOCHS):
            train_loss, train_acc = train_step(model, train_loader, loss_fn, optimizer, device)
        val_loss, val_acc = test_step(model, val_loader, loss_fn, device)
        rows.append({
            "learning_rate": learning_rate, "train_acc": train_acc,
            "val_loss": val_loss, "val_acc": val_acc
        })
        print(f"Sweep LR {learning_rate:.0e} | Val loss: {val_loss:.4f}, accuracy: {val_acc:.2f}%")
    return pd.DataFrame(rows)


def plot_training_curves(results, path):
    # Plot training and validation curves for each model and mark the restored epoch
    metric_titles = {"loss": "loss", "acc": "accuracy (%)"}
    fig, axes = plt.subplots(len(results), 2, figsize=(14, 13))
    for row, (name, result) in enumerate(results.items()):
        history = result["history"]
        for column, metric in enumerate(metric_titles):
            ax = axes[row, column]
            ax.plot(history["epoch"], history[f"train_{metric}"], label="Train")
            ax.plot(history["epoch"], history[f"val_{metric}"], label="Validation")
            ax.axvline(result["best_epoch"], color="gray", linestyle="--",
                       label=f"Restored epoch {result['best_epoch']}")
            ax.set_title(f"{name} {metric_titles[metric]}")
            ax.set_xlabel("Epoch")
            ax.legend()
    fig.tight_layout()
    fig.savefig(path, dpi=100)
    plt.close(fig)


def save_example_photos(test_data):
    # Copy one reproducible test photo per class, named after the class, for predict.py and app.py
    labels = torch.tensor(test_data._labels)
    generator = torch.Generator().manual_seed(RANDOM_SEED + 1)
    for class_index, class_name in enumerate(test_data.classes):
        class_indices = torch.where(labels == class_index)[0]
        index = class_indices[torch.randint(len(class_indices), (1,), generator=generator)].item()
        shutil.copy(test_data._image_files[index], EXAMPLE_DIR / f"{class_name.replace(' ', '_')}.jpg")


def main():
    device = get_device()
    print(f"PyTorch {torch.__version__} | Device: {device}")
    for directory in (CHECKPOINT_DIR, MODEL_DIR, EXAMPLE_DIR, OUTPUT_DIR):
        directory.mkdir(parents=True, exist_ok=True)

    train_loader, val_loader, test_loader = create_dataloaders(TRAIN_TRANSFORM, TEST_TRANSFORM)
    baseline_train_loader, baseline_val_loader, _ = create_dataloaders(
        BASELINE_TRAIN_TRANSFORM, BASELINE_TEST_TRANSFORM
    )
    class_names = train_loader.dataset.classes
    num_classes = len(class_names)
    loss_fn = nn.CrossEntropyLoss()
    print(f"Training batches: {len(train_loader)} | Validation batches: {len(val_loader)}\n")

    # Baseline: Lecture 29 TinyVGG trained from scratch on 64 x 64 photos
    torch.manual_seed(RANDOM_SEED)
    baseline_model = create_tinyvgg(num_classes).to(device)
    baseline_optimizer = torch.optim.Adam(baseline_model.parameters(), lr=BASELINE_LEARNING_RATE)
    baseline_history, baseline_epoch, baseline_seconds = train_model(
        baseline_model, baseline_train_loader, baseline_val_loader, loss_fn, baseline_optimizer,
        create_scheduler(baseline_optimizer), device, MAX_EPOCHS, PATIENCE, "TinyVGG baseline"
    )

    # Pick the EfficientNet-B0 head's learning rate by validation loss
    sweep_results = sweep_learning_rates(num_classes, train_loader, val_loader, loss_fn, device)
    best_learning_rate = sweep_results.loc[sweep_results["val_loss"].idxmin(), "learning_rate"]
    print(f"Selected learning rate (lowest validation loss): {best_learning_rate:.0e}\n")

    # Feature extractor: train only the new head on top of frozen ImageNet features
    torch.manual_seed(RANDOM_SEED)
    effnet_model = create_efficientnet_b0(num_classes).to(device)
    effnet_optimizer = torch.optim.Adam(effnet_model.classifier.parameters(), lr=best_learning_rate)
    effnet_history, effnet_epoch, effnet_seconds = train_model(
        effnet_model, train_loader, val_loader, loss_fn, effnet_optimizer,
        create_scheduler(effnet_optimizer), device, MAX_EPOCHS, PATIENCE,
        "EfficientNet-B0 feature extractor"
    )

    # Fine-tuned: continue from the trained head, unfreezing the last three feature blocks at a 10x lower learning rate
    finetuned_model = unfreeze_last_blocks(deepcopy(effnet_model), UNFROZEN_BLOCKS)
    torch.manual_seed(RANDOM_SEED)
    finetune_optimizer = torch.optim.Adam(
        [param for param in finetuned_model.parameters() if param.requires_grad],
        lr=best_learning_rate / 10
    )
    finetune_history, finetune_epoch, finetune_seconds = train_model(
        finetuned_model, train_loader, val_loader, loss_fn, finetune_optimizer,
        create_scheduler(finetune_optimizer), device, MAX_EPOCHS, PATIENCE,
        "EfficientNet-B0 fine-tuned"
    )

    # The fine-tuned training time includes the head training it builds on
    results = {
        "TinyVGG baseline": {
            "architecture": "TinyVGG", "model": baseline_model, "history": baseline_history,
            "best_epoch": baseline_epoch, "seconds": baseline_seconds
        },
        "EfficientNet-B0 feature extractor": {
            "architecture": "EfficientNet-B0", "model": effnet_model, "history": effnet_history,
            "best_epoch": effnet_epoch, "seconds": effnet_seconds
        },
        "EfficientNet-B0 fine-tuned": {
            "architecture": "EfficientNet-B0", "model": finetuned_model, "history": finetune_history,
            "best_epoch": finetune_epoch, "seconds": effnet_seconds + finetune_seconds
        }
    }

    # Save each model's weights and history, and summarize it at its restored epoch
    summary_rows = []
    for name, result in results.items():
        file_stem = name.lower().replace("-", "_").replace(" ", "_")
        checkpoint_path = CHECKPOINT_DIR / f"{file_stem}.pth"
        torch.save(obj=result["model"].state_dict(), f=checkpoint_path)
        result["history"].to_csv(OUTPUT_DIR / f"{file_stem}_history.csv", index=False)
        restored = result["history"].loc[result["history"]["epoch"] == result["best_epoch"]].iloc[0]
        summary_rows.append({
            "model": name, "architecture": result["architecture"],
            "restored_epoch": result["best_epoch"], "val_loss": restored["val_loss"],
            "val_acc": restored["val_acc"], "training_seconds": result["seconds"],
            "total_parameters": count_parameters(result["model"]),
            "trainable_parameters": count_parameters(result["model"], trainable_only=True),
            "checkpoint": checkpoint_path.relative_to(PROJECT_DIR).as_posix()
        })
    training_summary = pd.DataFrame(summary_rows).set_index("model")

    # Deploy the EfficientNet-B0 model with the lowest validation loss; the test set stays unseen until evaluate.py
    effnet_rows = training_summary[training_summary["architecture"] == "EfficientNet-B0"]
    final_model_name = effnet_rows["val_loss"].idxmin()
    training_summary["final_model"] = training_summary.index == final_model_name

    training_summary.to_csv(OUTPUT_DIR / "training_summary.csv")
    sweep_results.to_csv(OUTPUT_DIR / "learning_rate_sweep.csv", index=False)
    plot_training_curves(results, OUTPUT_DIR / "training_curves.png")

    # Save the final model, class names, and example test photos for predict.py and app.py
    torch.save(obj=results[final_model_name]["model"].state_dict(), f=FINAL_MODEL_PATH)
    (MODEL_DIR / "class_names.json").write_text(json.dumps(class_names, indent=2))
    save_example_photos(test_loader.dataset)

    print("Learning-rate sweep:")
    print(sweep_results.round(4).to_string(index=False), "\n")
    print("Training summary:")
    print(training_summary.round(4).to_string(), "\n")
    print(f"Final model: {final_model_name}")
    print(f"Saved {FINAL_MODEL_PATH.relative_to(PROJECT_DIR)} ({FINAL_MODEL_PATH.stat().st_size / 1e6:.1f} MB)")


if __name__ == "__main__":
    main()