-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_source.py
More file actions
99 lines (80 loc) · 2.56 KB
/
Copy pathtrain_source.py
File metadata and controls
99 lines (80 loc) · 2.56 KB
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
"""
EECS 445 - Introduction to Machine Learning
Winter 2024 - Project 2
Train Source CNN
Train a convolutional neural network to classify images.
Periodically output training information, and saves model checkpoints
Usage: python train_source.py
"""
import torch
import numpy as np
import random
from dataset import get_train_val_test_loaders
from model.source import Source
from train_common import *
from utils import config
import utils
import rng_control
def main():
"""Train source model on multiclass data."""
# Data loaders
tr_loader, va_loader, te_loader, _ = get_train_val_test_loaders(
task="source",
batch_size=config("source.batch_size"),
)
# Model
model = Source()
# TODO: Define loss function and optimizer. Replace "None" with the appropriate definitions.
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=0.01)
print("Number of float-valued parameters:", count_parameters(model))
# Attempts to restore the latest checkpoint if exists
print("Loading source...")
model, start_epoch, stats = restore_checkpoint(model, config("source.checkpoint"))
axes = utils.make_training_plot("Source Training")
# Evaluate the randomly initialized model
evaluate_epoch(
axes,
tr_loader,
va_loader,
te_loader,
model,
criterion,
start_epoch,
stats,
multiclass=True,
)
# initial val loss for early stopping
global_min_loss = stats[0][1]
# TODO: Define patience for early stopping. Replace "None" with the patience value.
patience = 10
curr_count_to_patience = 0
# Loop over the entire dataset multiple times
epoch = start_epoch
while curr_count_to_patience < patience:
# Train model
train_epoch(tr_loader, model, criterion, optimizer)
# Evaluate model
evaluate_epoch(
axes,
tr_loader,
va_loader,
te_loader,
model,
criterion,
epoch + 1,
stats,
multiclass=True,
)
# Save model parameters
save_checkpoint(model, epoch + 1, config("source.checkpoint"), stats)
curr_count_to_patience, global_min_loss = early_stopping(
stats, curr_count_to_patience, global_min_loss
)
epoch += 1
# Save figure and keep plot open
print("Finished Training")
utils.save_source_training_plot()
utils.hold_training_plot()
if __name__ == "__main__":
main()