-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvolutional_DNN.py
More file actions
352 lines (289 loc) · 12.5 KB
/
Convolutional_DNN.py
File metadata and controls
352 lines (289 loc) · 12.5 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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# -*- coding: utf-8 -*-
"""Helhoski_Assignment_3
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1b5e0wix6CxNkA0N08cvFSChJdfgo19jI
"""
#@title imports
import torch
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
from sklearn.model_selection import KFold
import time
import torch.cuda as cuda
#@title Loading Dataset
# much of model setup and training from: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
batch_size = 40
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
#@title training
def train(model, train_loader, optimizer):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True)
data = data.to('cuda')
target = target.to('cuda')
output = model(data)
output = output.to('cuda')
criterion = nn.CrossEntropyLoss()
loss = criterion(output, target)
loss.backward()
optimizer.step()
#@title Evaluation
def evalTotalSet(model):
correct = 0
total = 0
model.eval()
model.to('cuda')
# since we're not training, we don't need to calculate the gradients for our outputs
with torch.no_grad():
for data in testloader:
images, labels = data
images = images.to('cuda')
labels = labels.to('cuda')
# calculate outputs by running images through the network
outputs = model(images)
# the class with the highest energy is what we choose as prediction
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f'Accuracy of the network on the 10000 test images: {100 * correct // total} %')
def evalCategories(model):
# prepare to count predictions for each class
correct_pred = {classname: 0 for classname in classes}
total_pred = {classname: 0 for classname in classes}
model.eval()
model.to('cuda')
# again no gradients needed
with torch.no_grad():
for data in testloader:
images, labels = data
images = images.to('cuda')
labels = labels.to('cuda')
outputs = model(images)
_, predictions = torch.max(outputs, 1)
# collect the correct predictions for each class
for label, prediction in zip(labels, predictions):
if label == prediction:
correct_pred[classes[label]] += 1
total_pred[classes[label]] += 1
# print accuracy for each class
for classname, correct_count in correct_pred.items():
accuracy = 100 * float(correct_count) / total_pred[classname]
print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %')
#@title Models
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module): # variation of LeNet from https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2,2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fcNew1 = nn.Linear(120, 100) # for hypothesis test (not in original model)
self.fc2 = nn.Linear(100, 84)
self.fcNew2 = nn.Linear(84, 32) # for hypothesis test
self.fc3 = nn.Linear(32, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x,1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fcNew1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fcNew2(x))
x = self.fc3(x)
return x
class AlexNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 96, 3)
self.conv2 = nn.Conv2d(96, 256, 4, padding=1)
self.conv3 = nn.Conv2d(256, 384, 3, padding=1)
self.conv4 = nn.Conv2d(384, 384, 2, padding=1)
self.conv5 = nn.Conv2d(384, 256, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(256*4*4, 4096)
self.fc2 = nn.Linear(4096, 4096)
self.fc3 = nn.Linear(4096, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = F.relu(self.conv3(x))
x = F.relu(self.conv4(x))
x = self.pool(F.relu(self.conv5(x)))
x = torch.flatten(x,1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
#@title Residual
class Residual(nn.Module):
def __init__(self, input_channels, num_channels, use_1x1conv=False, strides=1):
super().__init__()
self.conv1 = nn.Conv2d(input_channels, num_channels, kernel_size=3, padding=1, stride=strides)
self.conv2 = nn.Conv2d(num_channels, num_channels, kernel_size=3, padding=1)
if use_1x1conv:
self.conv3 = nn.Conv2d(input_channels, num_channels, kernel_size=1, stride=strides)
else:
self.conv3 = None
self.bn1 = nn.BatchNorm2d(num_channels)
self.bn2 = nn.BatchNorm2d(num_channels)
def forward(self, X):
Y = F.relu(self.bn1(self.conv1(X)))
Y = self.bn2(self.conv2(Y))
if self.conv3:
X = self.conv3(X)
Y += X
return F.relu(Y)
#@title ResNet-18
b1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3),
nn.BatchNorm2d(64), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
def resnet_block(input_channels, num_channels, num_residuals, first_block=False):
blk = []
for i in range(num_residuals):
if i == 0 and not first_block:
blk.append(Residual(input_channels, num_channels, use_1x1conv=True, strides=2))
else:
blk.append(Residual(num_channels, num_channels))
return blk
b2 = nn.Sequential(*resnet_block(64, 64, 2, first_block=True))
b3 = nn.Sequential(*resnet_block(64, 128, 2))
b4 = nn.Sequential(*resnet_block(128, 256, 2))
b5 = nn.Sequential(*resnet_block(256, 512, 2))
resnet18Inst = nn.Sequential(b1, b2, b3, b4, b5,
nn.AdaptiveAvgPool2d((1,1)),
nn.Flatten(), nn.Linear(512, 10))
#@title training resnet
# training all 3 models and evaluating on test set
resnet18Inst.to('cuda')
batch_size = 4
epochs = 2
optimizer = optim.SGD(resnet18Inst.parameters(), lr=0.001, momentum=0.9)
#criterion = F.nll_loss()
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True)
# method of counting parameters from: https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325
print("Model size: parameters:", sum(p.numel() for p in resnet18Inst.parameters() if p.requires_grad))
start = time.time()
for epoch in range(epochs):
train(resnet18Inst, trainloader, optimizer)
end = time.time()
print("Training time: ", end-start)
import numpy
import matplotlib.pyplot as plt
resnet18Inst = nn.Sequential(b1, b2, b3, b4, b5,
nn.AdaptiveAvgPool2d((1,1)),
nn.Flatten(), nn.Linear(512, 10))
PATH = './cifar_resNet.pth'
resnet18Inst.load_state_dict(torch.load(PATH, weights_only=True))
c_matrix = numpy.zeros((10,10), dtype=int)
evalCategories(resnet18Inst)
print(c_matrix)
#some code from: https://stackoverflow.com/questions/20998083/show-the-values-in-the-grid-using-matplotlib
plt.matshow(c_matrix)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('ResNet-18 Confusion Matrix')
plt.show()
#@title training lenet
# training all 3 models and evaluating on test set
leNetInst = LeNet()
leNetInst.to('cuda')
batch_size = 4
epochs = 2
optimizer = optim.SGD(leNetInst.parameters(), lr=0.001, momentum=0.9)
#criterion = F.nll_loss()
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True)
# method of counting parameters from: https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325
print("Model size: parameters:", sum(p.numel() for p in leNetInst.parameters() if p.requires_grad))
start = time.time()
for epoch in range(epochs):
train(leNetInst, trainloader, optimizer)
end = time.time()
print("Training time: ", end-start)
evalTotalSet(leNetInst)
evalCategories(leNetInst)
# training all 3 models and evaluating on test set
alexInst = AlexNet()
alexInst.to('cuda')
batch_size = 4
epochs = 2
optimizer = optim.SGD(alexInst.parameters(), lr=0.001, momentum=0.9)
#criterion = F.nll_loss()
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=2)
# method of counting parameters from: https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325
print("Model size: parameters:", sum(p.numel() for p in alexInst.parameters() if p.requires_grad))
start = time.time()
for epoch in range(epochs):
train(alexInst, trainloader, optimizer)
end = time.time()
print("Training time: ", end-start)
PATH = './cifar_alexNet.pth'
torch.save(alexInst.state_dict(), PATH)
#@title k-fold
def run_k_fold(folds, batch_size, epochs):
# kfold method/some code from: https://saturncloud.io/blog/how-to-use-kfold-cross-validation-with-dataloaders-in-pytorch/#step-1-importing-the-required-libraries
kf = KFold(n_splits=folds)
# Loop through each fold
for fold, (train_idx, test_idx) in enumerate(kf.split(trainset)):
print(f"Fold {fold + 1}")
print("-------")
# Define the data loaders for the current fold
train_loader = torch.utils.data.DataLoader(dataset=trainset, batch_size=batch_size, sampler=torch.utils.data.SubsetRandomSampler(train_idx),
pin_memory=True, num_workers=2)
test_loader = torch.utils.data.DataLoader(dataset=trainset, batch_size=batch_size, sampler=torch.utils.data.SubsetRandomSampler(test_idx),
pin_memory=True, num_workers=2)
# have to redefined entire model inside block so that residual blocks are reset
b1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3),
nn.BatchNorm2d(64), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
def resnet_block(input_channels, num_channels, num_residuals, first_block=False):
blk = []
for i in range(num_residuals):
if i == 0 and not first_block:
blk.append(Residual(input_channels, num_channels, use_1x1conv=True, strides=2))
else:
blk.append(Residual(num_channels, num_channels))
return blk
b2 = nn.Sequential(*resnet_block(64, 64, 2, first_block=True))
b3 = nn.Sequential(*resnet_block(64, 128, 2))
b4 = nn.Sequential(*resnet_block(128, 256, 2))
b5 = nn.Sequential(*resnet_block(256, 512, 2))
model = nn.Sequential(b1, b2, b3, b4, b5,
nn.AdaptiveAvgPool2d((1,1)),
nn.Flatten(), nn.Linear(512, 10))
model.to('cuda')
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
for epoch in range(epochs):
train(model, train_loader, optimizer)
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data = data.to('cuda')
target = target.to('cuda')
output = model(data)
criterion = nn.CrossEntropyLoss()
test_loss += criterion(output, target).item()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
accuracy = 100.0 * correct / (len(test_loader.dataset)/folds)
print(f"Test set: Average loss: {test_loss:.4f}, Accuracy: {correct}/({len(test_loader.dataset)/folds}) ({accuracy:.0f}%)")
print()