File size: 4,244 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
"""Training, evaluation, and timed prediction functions shared by the project scripts."""
from copy import deepcopy
from timeit import default_timer as timer

import pandas as pd
import torch


def get_device():
    # Use an NVIDIA GPU, then an Apple GPU, then the CPU
    device = "cpu"
    if torch.cuda.is_available():
        device = "cuda"
    elif torch.backends.mps.is_available():
        device = "mps"
    return device


# Lecture 29 train and test steps
def train_step(model, data_loader, loss_fn, optimizer, device):
    model.train()
    total_loss, total_correct, total_samples = 0.0, 0, 0
    for X, y in data_loader:
        X, y = X.to(device), y.to(device)
        logits = model(X)
        loss = loss_fn(logits, y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total_loss += loss.item() * y.size(0)
        total_correct += (logits.argmax(dim=1) == y).sum().item()
        total_samples += y.size(0)
    return total_loss / total_samples, 100 * total_correct / total_samples


def test_step(model, data_loader, loss_fn, device):
    model.eval()
    total_loss, total_correct, total_samples = 0.0, 0, 0
    with torch.inference_mode():
        for X, y in data_loader:
            X, y = X.to(device), y.to(device)
            logits = model(X)
            total_loss += loss_fn(logits, y).item() * y.size(0)
            total_correct += (logits.argmax(dim=1) == y).sum().item()
            total_samples += y.size(0)
    return total_loss / total_samples, 100 * total_correct / total_samples


def train_model(model, train_loader, val_loader, loss_fn, optimizer, scheduler,
                device, max_epochs, patience, model_name):
    # Train with learning-rate scheduling and early stopping, then restore the lowest-validation-loss weights
    best_val_loss, best_epoch, epochs_without_improvement = float("inf"), 0, 0
    best_state = deepcopy(model.state_dict())
    history = []
    start = timer()
    for epoch in range(1, max_epochs + 1):
        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)
        learning_rate = optimizer.param_groups[0]["lr"]
        scheduler.step(val_loss)
        history.append({
            "epoch": epoch, "train_loss": train_loss, "train_acc": train_acc,
            "val_loss": val_loss, "val_acc": val_acc, "learning_rate": learning_rate
        })
        print(
            f"{model_name} | Epoch {epoch}/{max_epochs} | LR: {learning_rate:.1e} | "
            f"Train loss: {train_loss:.4f}, accuracy: {train_acc:.2f}% | "
            f"Val loss: {val_loss:.4f}, accuracy: {val_acc:.2f}%"
        )

        # Keep the weights with the lowest validation loss
        if val_loss < best_val_loss:
            best_val_loss, best_epoch, epochs_without_improvement = val_loss, epoch, 0
            best_state = deepcopy(model.state_dict())
        else:
            epochs_without_improvement += 1

        # Stop once validation loss has not improved for `patience` epochs
        if epochs_without_improvement >= patience:
            print(f"Early stopping after epoch {epoch}.")
            break

    training_seconds = timer() - start
    model.load_state_dict(best_state)
    print(
        f"Restored epoch {best_epoch} weights (val loss {best_val_loss:.4f}). "
        f"Training and validation took {training_seconds:.1f} seconds.\n"
    )
    return pd.DataFrame(history), best_epoch, training_seconds


def predict_labels(model, data_loader, device):
    model.eval()
    predictions = []
    with torch.inference_mode():
        for X, y in data_loader:
            predictions.append(model(X.to(device)).argmax(dim=1).cpu())
    return torch.cat(predictions)


def predict_single_image(model, image, transform, device):
    # Time one complete prediction: preprocessing, forward pass, and softmax for a single PIL image
    model.eval()
    start = timer()
    image_tensor = transform(image.convert("RGB")).unsqueeze(dim=0).to(device)
    with torch.inference_mode():
        pred_probs = torch.softmax(model(image_tensor), dim=1).squeeze(dim=0).cpu()
    seconds = timer() - start
    return pred_probs, seconds