-
Notifications
You must be signed in to change notification settings - Fork 1
/
CNN2_BCELoss.py
385 lines (292 loc) · 12.1 KB
/
CNN2_BCELoss.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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/env python3
# coding: utf-8
#https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu
import torch, torchvision, os, cv2
from torch.utils.data import random_split, Dataset
from torch.nn import Sigmoid, Tanh, Linear, ReLU, Sequential, Conv2d, MaxPool2d, Sigmoid, BatchNorm2d, Flatten, ConvTranspose2d
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
import CAP6610
#---CNN2_BCELosss Class with Default Training Parameters---#
class CNN2_BCELoss:
def __init__(self):
#define the neural network
self.net = Sequential(
# Defining 1st 2D convolution layer
Conv2d(3, 16, kernel_size=3, stride=1, padding=1), #200@3
BatchNorm2d(16),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining 2nd 2D convolution layer
Conv2d(16, 8, kernel_size=3, stride=1, padding=1), #100@3
BatchNorm2d(8),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining 3rd 2D convolution layer
Conv2d(8, 4, kernel_size=3, stride=1, padding=1), #50@3
BatchNorm2d(4),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining 4th 2D convolution layer
Conv2d(4, 2, kernel_size=3, stride=1, padding=1), #25@3
BatchNorm2d(2),
ReLU(inplace=True),
Flatten(),
Linear(2 * 25 * 25, 1),
Sigmoid()
)
#move neural network to the gpu
self.net = self.net.cuda()
#define default criterion
self.criterion = nn.BCELoss()
#define default optimizer
self.optimizer = optim.SGD(self.net.parameters(), lr=0.001, momentum=0.9)
#define default epochs to use for training
#self.epochs = 10000
def train(self, datas, epochs=10000):
for epoch in range(epochs): # loop over the dataset multiple times
#epoch = 0
#while True:
train_loss = 0.0
for i, data in enumerate(datas, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data[0].cuda(), data[1].cuda() #Reg
# zero the parameter gradients
self.optimizer.zero_grad()
# forward + backward + optimize
outputs = self.net(inputs)
labels = torch.reshape(labels, (-1,))
outputs = torch.reshape(outputs, (-1,))
loss = self.criterion(outputs, labels)
loss.backward()
self.optimizer.step()
# print statistics
train_loss += loss.item()
logStr = 'Train epoch: %d, Loss: %.10f' % (epoch + 1, train_loss/ (i+1))
print(logStr)
epoch += 1
print('Finished Training')
def printConfusionMatrix(self, datas):
correct = 0
total = 0
nb_classes = 2
confusion_matrix = torch.zeros(nb_classes, nb_classes)
with torch.no_grad():
for data in datas:
images, labels = data[0].cuda(), data[1].cuda()
outputs = self.net(images)
predicted = torch.round(outputs)
total += labels.size(0)
correct += (predicted == labels).sum().item()
for t, p in zip(labels.view(-1), predicted.view(-1)):
confusion_matrix[t.long(), p.long()] += 1
print('Accuracy of the network on the %s test images: %d %%' % (total,
100 * correct / total))
print(confusion_matrix)
#---END---CNN2_BCELosss Class with Training Parameters---#
#---Function for Loading Training / Test Data From File---#
def getData():
#load extracted data from files
images = np.load('LogImages.npy') #Rade the trianing data.
images = np.moveaxis(images, -1, 1) #Reshape channeL from [B, H, W, C] to [B, C, H, W]
labels = np.load('Labels.npy') #Rade the trianing data.
labels = labels.reshape(labels.shape[0],1)
# images = images.astype(np.float32)
# labels = labels.astype(np.int)
print(labels.shape)
labels2D = np.zeros((labels.shape[0],2))
for i in range(len(labels)):
lab = labels[i]
if lab == 0:
labels2D[i,0] = 1
if lab == 1:
labels2D[i,1] = 1
lengths = [round(len(images)*0.8), round(len(images)*0.2)]
print(lengths)
#perform training/testing data splits
trainImg, testImg = random_split(images, lengths ,generator=torch.random.manual_seed(42)) #Shuffle data with random seed 42 before split train and test
trainLab, testLab = random_split(labels, lengths ,generator=torch.random.manual_seed(42)) #Shuffle data with random seed 42 before split train and test
print(trainImg[0].shape)
print(trainLab[25])
#get training data
trainData = []
for i in range(len(trainImg)):
trainData.append([torch.tensor(trainImg[i], dtype=torch.float32), torch.tensor(trainLab[i],dtype=torch.float32)])
trainLoader = torch.utils.data.DataLoader(trainData, shuffle=True, batch_size=5)
#get test data
testData = []
for i in range(len(testImg)):
testData.append([torch.tensor(testImg[i], dtype=torch.float32), torch.tensor(testLab[i],dtype=torch.float32)])
testLoader = torch.utils.data.DataLoader(testData, shuffle=False, batch_size=5)
return trainLoader, testLoader
#---END---Function for Loading Training / Test Data From File---#
#function for running this file as a script
def main():
#get data from file loaded
trainLoader, testLoader = getData()
#instantate CNN2_BCELoss Neural Network with default parameters
NN = CNN2_BCELoss()
#train the network with loaded training data
NN.train(trainLoader, epochs=100)
#evaluate and print confusion matrices for data
NN.printConfusionMatrix(trainLoader)
NN.printConfusionMatrix(testLoader)
#test if user is running this file as a script
if __name__ == "__main__":
#run function defined as main
main()
#---Refactored Code for Classless Solution---#
'''
#define the neural network
net = Sequential(
# Defining 1st 2D convolution layer
Conv2d(3, 16, kernel_size=3, stride=1, padding=1), #200@3
BatchNorm2d(16),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining 2nd 2D convolution layer
Conv2d(16, 8, kernel_size=3, stride=1, padding=1), #100@3
BatchNorm2d(8),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining 3rd 2D convolution layer
Conv2d(8, 4, kernel_size=3, stride=1, padding=1), #50@3
BatchNorm2d(4),
ReLU(inplace=True),
MaxPool2d(kernel_size=2, stride=2),
# Defining 4th 2D convolution layer
Conv2d(4, 2, kernel_size=3, stride=1, padding=1), #25@3
BatchNorm2d(2),
ReLU(inplace=True),
Flatten(),
Linear(2 * 25 * 25, 1),
Sigmoid()
)
#move neural network to the gpu
net = net.cuda()
#define criterion
#criterion = nn.CrossEntropyLoss()
criterion = nn.BCELoss()
#define optimizer
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
print(net)
def train(net, criterion, optimizer, n_epoch, training):
for epoch in range(n_epoch): # loop over the dataset multiple times
#epoch = 0
#while True:
train_loss = 0.0
for i, data in enumerate(training, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data[0].cuda(), data[1].cuda() #Reg
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
labels = torch.reshape(labels, (-1,))
outputs = torch.reshape(outputs, (-1,))
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
train_loss += loss.item()
logStr = 'Train epoch: %d, Loss: %.10f' % (epoch + 1, train_loss/ (i+1))
print(logStr)
epoch += 1
print('Finished Training')
#function for evaluating and printing confusion matrix from data
def printConfusionMatrix(net, datas):
correct = 0
total = 0
nb_classes = 2
confusion_matrix = torch.zeros(nb_classes, nb_classes)
with torch.no_grad():
for data in datas:
images, labels = data[0].cuda(), data[1].cuda()
outputs = net(images)
predicted = torch.round(outputs)
total += labels.size(0)
correct += (predicted == labels).sum().item()
for t, p in zip(labels.view(-1), predicted.view(-1)):
confusion_matrix[t.long(), p.long()] += 1
print('Accuracy of the network on the %s test images: %d %%' % (total,
100 * correct / total))
print(confusion_matrix)
def main():
#get data from file loaded
trainLoader, testLoader = getData()
#train the neural net specifying criterion, optimizer, epochs, and training data
train(net, criterion, optimizer, 10000, trainLoader)
#print confusion matrix for training data
printConfusionMatrix(net, trainLoader)
#print confusion matrix for testing data
printConfusionMatrix(net, testLoader)
'''
#---END---Refactored Code for Classless Solution---#
#some old unfactored code in notes below
'''
n_epoch = 10000
for epoch in range(n_epoch): # loop over the dataset multiple times
#epoch = 0
#while True:
train_loss = 0.0
for i, data in enumerate(trainLoader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data[0].cuda(), data[1].cuda() #Reg
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
labels = torch.reshape(labels, (-1,))
outputs = torch.reshape(outputs, (-1,))
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
train_loss += loss.item()
logStr = 'Train epoch: %d, Loss: %.10f' % (epoch + 1, train_loss/ (i+1))
print(logStr)
epoch += 1
print('Finished Training')
'''
# PATH = './CNN2_SGDlr0.001_BCEL_EP10000_72%.pth'
# torch.save(net.state_dict(), PATH)
'''
correct = 0
total = 0
nb_classes = 2
confusion_matrix = torch.zeros(nb_classes, nb_classes)
with torch.no_grad():
for data in trainLoader:
images, labels = data[0].cuda(), data[1].cuda()
outputs = net(images)
predicted = torch.round(outputs)
total += labels.size(0)
correct += (predicted == labels).sum().item()
for t, p in zip(labels.view(-1), predicted.view(-1)):
confusion_matrix[t.long(), p.long()] += 1
print('Accuracy of the network on the %s test images: %d %%' % (total,
100 * correct / total))
print(confusion_matrix)
# In[48]:
'''
'''
correct = 0
total = 0
nb_classes = 2
confusion_matrix = torch.zeros(nb_classes, nb_classes)
with torch.no_grad():
for data in testLoader:
images, labels = data[0].cuda(), data[1].cuda()
outputs = net(images)
predicted = torch.round(outputs)
total += labels.size(0)
correct += (predicted == labels).sum().item()
for t, p in zip(labels.view(-1), predicted.view(-1)):
confusion_matrix[t.long(), p.long()] += 1
print('Accuracy of the network on the %s test images: %d %%' % (total,
100 * correct / total))
print(confusion_matrix)
# In[ ]:
'''