-
Notifications
You must be signed in to change notification settings - Fork 485
/
Copy pathsimple_cnn_mnist.py
169 lines (139 loc) · 5.92 KB
/
simple_cnn_mnist.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
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor
import numpy as np
import matplotlib.pyplot as plt
class CNN(nn.Module):
def __init__(self, lr, epochs, batch_size, num_classes=10):
super(CNN, self).__init__()
self.epochs = epochs
self.lr = lr
self.batch_size = batch_size
self.num_classes = num_classes
self.loss_history = []
self.acc_history = []
self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu')
self.conv1 = nn.Conv2d(1, 32, 3)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 32, 3)
self.bn2 = nn.BatchNorm2d(32)
self.conv3 = nn.Conv2d(32, 32, 3)
self.bn3 = nn.BatchNorm2d(32)
self.maxpool1 = nn.MaxPool2d(2)
self.conv4 = nn.Conv2d(32, 64, 3)
self.bn4 = nn.BatchNorm2d(64)
self.conv5 = nn.Conv2d(64, 64, 3)
self.bn5 = nn.BatchNorm2d(64)
self.conv6 = nn.Conv2d(64, 64, 3)
self.bn6 = nn.BatchNorm2d(64)
self.maxpool2 = nn.MaxPool2d(2)
input_dims = self.calc_input_dims()
self.fc1 = nn.Linear(input_dims, self.num_classes)
self.optimizer = optim.Adam(self.parameters(), lr=self.lr)
self.loss = nn.CrossEntropyLoss()
self.to(self.device)
self.get_data()
def calc_input_dims(self):
batch_data = T.zeros((1, 1, 28, 28))
batch_data = self.conv1(batch_data)
#batch_data = self.bn1(batch_data)
batch_data = self.conv2(batch_data)
#batch_data = self.bn2(batch_data)
batch_data = self.conv3(batch_data)
batch_data = self.maxpool1(batch_data)
batch_data = self.conv4(batch_data)
batch_data = self.conv5(batch_data)
batch_data = self.conv6(batch_data)
batch_data = self.maxpool2(batch_data)
return int(np.prod(batch_data.size()))
def forward(self, batch_data):
batch_data = T.tensor(batch_data).to(self.device)
batch_data = self.conv1(batch_data)
batch_data = self.bn1(batch_data)
batch_data = F.relu(batch_data)
batch_data = self.conv2(batch_data)
batch_data = self.bn2(batch_data)
batch_data = F.relu(batch_data)
batch_data = self.conv3(batch_data)
batch_data = self.bn3(batch_data)
batch_data = F.relu(batch_data)
batch_data = self.maxpool1(batch_data)
batch_data = self.conv4(batch_data)
batch_data = self.bn4(batch_data)
batch_data = F.relu(batch_data)
batch_data = self.conv5(batch_data)
batch_data = self.bn5(batch_data)
batch_data = F.relu(batch_data)
batch_data = self.conv6(batch_data)
batch_data = self.bn6(batch_data)
batch_data = F.relu(batch_data)
batch_data = self.maxpool2(batch_data)
batch_data = batch_data.view(batch_data.size()[0], -1)
classes = self.fc1(batch_data)
return classes
def get_data(self):
mnist_train_data = MNIST('mnist', train=True,
download=True, transform=ToTensor())
self.train_data_loader = T.utils.data.DataLoader(mnist_train_data,
batch_size=self.batch_size,
shuffle=True,
num_workers=8)
mnist_test_data = MNIST('mnist', train=False,
download=True, transform=ToTensor())
self.test_data_loader = T.utils.data.DataLoader(mnist_test_data,
batch_size=self.batch_size,
shuffle=True,
num_workers=8)
def _train(self):
self.train()
for i in range(self.epochs):
ep_loss = 0
ep_acc = []
for j, (input, label) in enumerate(self.train_data_loader):
self.optimizer.zero_grad()
label = label.to(self.device)
prediction = self.forward(input)
loss = self.loss(prediction, label)
prediction = F.softmax(prediction, dim=1)
classes = T.argmax(prediction, dim=1)
wrong = T.where(classes != label,
T.tensor([1.]).to(self.device),
T.tensor([0.]).to(self.device))
acc = 1 - T.sum(wrong) / self.batch_size
ep_acc.append(acc.item())
self.acc_history.append(acc.item())
ep_loss += loss.item()
loss.backward()
self.optimizer.step()
print('Finish epoch ', i, 'total loss %.3f' % ep_loss,
'accuracy %.3f' % np.mean(ep_acc))
self.loss_history.append(ep_loss)
def _test(self):
self.eval()
ep_loss = 0
ep_acc = []
for j, (input, label) in enumerate(self.test_data_loader):
label = label.to(self.device)
prediction = self.forward(input)
loss = self.loss(prediction, label)
prediction = F.softmax(prediction, dim=1)
classes = T.argmax(prediction, dim=1)
wrong = T.where(classes != label,
T.tensor([1.]).to(self.device),
T.tensor([0.]).to(self.device))
acc = 1 - T.sum(wrong) / self.batch_size
ep_acc.append(acc.item())
ep_loss += loss.item()
print('total loss %.3f' % ep_loss,
'accuracy %.3f' % np.mean(ep_acc))
if __name__ == '__main__':
network = CNN(lr=0.001, batch_size=128, epochs=25)
network._train()
plt.plot(network.loss_history)
plt.show()
plt.plot(network.acc_history)
plt.show()
network._test()