-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathopt.py
153 lines (113 loc) · 4.77 KB
/
opt.py
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
# opt.py
# CS 445/545 -- Spring 2020
# Training and validation / testing functions.
# Imports
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
#################################################
# TRAINING
#################################################
# Train the given model on the given data.
def train(model: nn.Module, data: torch.Tensor, labels: torch.Tensor, loader: torch.utils.data.dataloader.DataLoader,
optimizer: optim.Optimizer, device: torch.device, resnet: bool) -> float:
# Switch to train
model.train()
# Define criterion and initialize loss
criterion = nn.CrossEntropyLoss()
total_loss = 0.0
# Go through each batch
for i, batch in enumerate(loader):
# Get the data and labels
data_batch = data[batch[0].long()].to(device)
label_batch = labels[batch[0].long()].clone().detach().long().to(device)
# Reshape batch if using a ResNet
if resnet:
data_batch = data_batch.reshape(len(data_batch), 1, 28, 28)
# Zero the optimizer gradients
optimizer.zero_grad()
# Pass the batch through the network
output = F.softmax(model(data_batch), dim = 1)
# Calculate loss and run optimization step
loss = criterion(output, label_batch)
total_loss += loss.item()
loss.backward()
optimizer.step()
# Print progress
if i % 2500 == 0:
print("\tFinished batch {} ({:.1f}% complete).".format(i, (i / len(loader)) * 100))
# Return average loss
return total_loss / len(loader)
#################################################
# VALIDATION
#################################################
# Run validation on the given model with the given data.
def validate(model: nn.Module, data: torch.Tensor, labels: torch.Tensor, loader: torch.utils.data.dataloader.DataLoader,
device: torch.device, resnet: bool) -> float:
# Switch to eval
model.eval()
# Initialize loss and define criterion
total_loss = 0.0
criterion = nn.CrossEntropyLoss()
# Turn off gradient tracking
with torch.no_grad():
# Go through each batch
for batch in loader:
# Get the data and labels
data_batch = data[batch[0].long()].to(device)
label_batch = labels[batch[0].long()].clone().detach().long().to(device)
# Reshape batch if using a ResNet
if resnet:
data_batch = data_batch.reshape(len(data_batch), 1, 28, 28)
# Pass the batch through the network
output = F.softmax(model(data_batch), dim = 1)
# Calculate loss
loss = criterion(output, label_batch)
total_loss += loss.item()
# Return average loss
return total_loss / len(loader)
#################################################
# TESTING
#################################################
# Test the model (accuracy / confusion) on the given model with the given data.
def test(model: nn.Module, data: torch.Tensor, labels: torch.Tensor, loader: torch.utils.data.dataloader.DataLoader,
device: torch.device, num_classes: int, resnet: bool) -> (int, int, torch.Tensor, torch.Tensor):
# Switch to eval mode
model.eval()
# Initialize metrics
total = 0
correct = 0
confusion_matrix = torch.zeros((num_classes, num_classes))
softmax_matrix = torch.zeros((num_classes, num_classes))
# Turn off gradient tracking
with torch.no_grad():
# Go through each batch
for batch in loader:
# Get the data and labels
data_batch = data[batch[0].long()].to(device)
label_batch = labels[batch[0].long()].to(device)
# Reshape batch if using a ResNet
if resnet:
data_batch = data_batch.reshape(len(data_batch), 1, 28, 28)
# Pass the batch through the network and get the prediction
output = F.softmax(model(data_batch), dim = 1)
# Move to CPU for caluclations
output = output.to("cpu")
label_batch = label_batch.to("cpu")
# Iterate through each example
for i in range(len(data_batch)):
# Get the prediction and the actual label
pred = int(torch.argmax(output[i]))
label = int(label_batch[i])
# Increment accuracy counts
total += 1
if pred == label:
correct += 1
# Increment matrices
confusion_matrix[label, pred] += 1
softmax_matrix[label, :] += output[i]
# Move softmax matrix back to CPU and return metrics
return total, correct, confusion_matrix, softmax_matrix