-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnist_train.py
executable file
·159 lines (108 loc) · 4.56 KB
/
mnist_train.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
154
155
156
157
158
159
#!/usr/bin/python3
if __name__ == "__main__":
import torch, tqdm
import mnist, cnn_example, deepconsensus_example
print('''
***
Training on MNIST centered in a 64x64 black image
while testing on a perturbed version of its test set,
where images are translated 20 pixels in both the x and y axes.
***
''')
# STEP 1: Get data
TRANSLATE = 20
trainData, trainLabels, testData, testLabels, NUM_CLASSES, CHANNELS, IMAGESIZE = mnist.get_mnist64_corrupt(
download = True,
mintrans = TRANSLATE,
maxtrans = TRANSLATE
)
BATCHSIZE = 100
TRAIN_VS_VALIDATION_SPLIT = 0.2
dataloader, validloader, testloader = mnist.create_trainvalid_split(
TRAIN_VS_VALIDATION_SPLIT,
trainData,
trainLabels,
testData,
testLabels,
trainbatch=BATCHSIZE,
testbatch=BATCHSIZE
)
# STEP 2: Create models
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
cnn = cnn_example.Cnn(CHANNELS, NUM_CLASSES, IMAGESIZE).to(DEVICE)
deepconsensus_cnn = deepconsensus_example.DeepConsensusCnn(CHANNELS, NUM_CLASSES, IMAGESIZE).to(DEVICE)
def count_parameters(model, name):
count = sum(map(torch.numel, model.parameters()))
print("%s model has %d (%.2f million) parameters." % (name, count, count/1e6))
count_parameters(cnn, "CNN")
count_parameters(deepconsensus_cnn, "DeepConsensus-CNN")
# STEP 3: Train models
loss_function = torch.nn.CrossEntropyLoss()
cnn_optimizer = torch.optim.Adam(cnn.parameters())
deepconsensus_cnn_optimizer = torch.optim.Adam(deepconsensus_cnn.parameters())
cnn_lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(cnn_optimizer)
deepconsensus_cnn_lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(deepconsensus_cnn_optimizer)
def train(model, X, y, optimizer=None):
yh = model(X)
loss = loss_function(yh, y)
if optimizer is not None:
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss = loss.item()
error = (yh.max(dim=1)[1] == y).float().mean()
return loss, error
def report(title, c_loss, d_loss, c_err, d_err, n):
print('''\
=== %s results ===
CNN DeepConsensus-CNN
Cross entropy loss: %.5f %.5f
Accuracy : %.5f %.5f''' % (title, c_loss/n, d_loss/n, c_err/n, d_err/n))
EPOCHS = 30
for epoch in range(1, EPOCHS+1):
cnn.train()
deepconsensus_cnn.train()
# === TRAINING ===
c_loss = d_loss = c_err = d_err = n = 0.0
for X, y in tqdm.tqdm(dataloader, desc="Epoch %d" % epoch, ncols=80):
X = X.to(DEVICE)
y = y.to(DEVICE)
cl, ce = train(cnn, X, y, cnn_optimizer)
c_loss += cl
c_err += ce
dl, de = train(deepconsensus_cnn, X, y, deepconsensus_cnn_optimizer)
d_loss += dl
d_err += de
n += 1.0
report("Training", c_loss, d_loss, c_err, d_err, n)
with torch.no_grad():
cnn.eval()
deepconsensus_cnn.eval()
# === VALIDATION ===
c_loss = d_loss = c_err = d_err = n = 0.0
for X, y in validloader:
X = X.to(DEVICE)
y = y.to(DEVICE)
cl, ce = train(cnn, X, y)
c_loss += cl
c_err += ce
dl, de = train(deepconsensus_cnn, X, y)
d_loss += dl
d_err += de
n += 1.0
cnn_lr_scheduler.step(c_err/n)
deepconsensus_cnn_lr_scheduler.step(d_err/n)
report("Validation", c_loss, d_loss, c_err, d_err, n)
# === TESTING ===
c_loss = d_loss = c_err = d_err = n = 0.0
for X, y in testloader:
X = X.to(DEVICE)
y = y.to(DEVICE)
cl, ce = train(cnn, X, y)
c_loss += cl
c_err += ce
dl, de = train(deepconsensus_cnn, X, y)
d_loss += dl
d_err += de
n += 1.0
report("Testing", c_loss, d_loss, c_err, d_err, n)