/
04_03_MNIST_Pytorch_CNN.py
209 lines (158 loc) · 6.18 KB
/
04_03_MNIST_Pytorch_CNN.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Hyper-parameters
input_size = 784 # 28x28
hidden_size = 256
num_classes = 10
EPOCHS = 5
batch_size = 100
learning_rate = 0.001
# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = torchvision.datasets.MNIST(root='./data',
train=False,
transform=transforms.ToTensor())
# Data loader
train_ds = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
test_ds = torch.utils.data.DataLoader(dataset=test_dataset,
batch_size=batch_size,
shuffle=False)
# plot first few images
examples = iter(test_ds)
example_data, example_targets = examples.next()
for i in range(9):
# define subplot
plt.subplot(330 + 1 + i)
# plot raw pixel data
plt.imshow(example_data[i][0], cmap=plt.get_cmap('gray'))
# if you want to invert color, you can use 'gray_r'. this can be used only for MNIST, Fashion MNIST not cifar10
# pyplot.imshow(trainX[i], cmap=pyplot.get_cmap('gray_r'))
# show the figure
plt.show()
# 3-Layers Convolution neural network with one hidden layer
class CNN_Model(nn.Module):
def __init__(self):
super(CNN_Model, self).__init__()
# Convolution 1
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=1, padding=0)
self.relu1 = nn.ReLU()
# Max pool 1
self.maxpool2d1 = nn.MaxPool2d(kernel_size=2)
# Convolution 2
self.conv2 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=0)
self.relu2 = nn.ReLU()
# Max pool 2
self.maxpool2d2 = nn.MaxPool2d(kernel_size=2)
# Convolution 3
self.conv3 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=0)
self.relu3 = nn.ReLU()
# Max pool 3
self.maxpool2d3 = nn.MaxPool2d(kernel_size=2)
# Fully connected 1 (readout)
self.d1 = nn.Linear(256 * 1 * 1, 256)
self.d2 = nn.Dropout(0.2)
self.d3 = nn.Linear(256, num_classes)
def forward(self, x):
# Convolution 1
x = self.conv1(x)
x = self.relu1(x)
# Max pool 1
x = self.maxpool2d1(x)
# Convolution 2
x = self.conv2(x)
x = self.relu2(x)
# Max pool 2
x = self.maxpool2d2(x)
# Convolution 3
x = self.conv3(x)
x = self.relu3(x)
# Max pool 3
x = self.maxpool2d3(x)
# Resize
# Original size: (100, 256, 1, 1)
# out.size(0): 100
# New out size: (100, 256*1*1)
x = x.view(x.size(0), -1)
# Linear function (readout)
x = self.d1(x)
x = self.d2(x)
out = self.d3(x)
return out
# model = CNN_Model(input_size, hidden_size, num_classes).to(device)
model = CNN_Model().to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
n_total_steps = len(train_ds)
def train_step(model, images, labels):
model.train()
# origin shape: [100, 1, 28, 28]
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
loss_val = loss.item()
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Pytorch need a manual coding for accuracy
# max returns (value ,index)
_, predicted = torch.max(outputs.data, 1)
n_samples = labels.size(0)
n_correct = (predicted == labels).sum().item()
acc = 100.0 * n_correct / n_samples
return loss_val, acc
def test_step(model, images, labels):
model.eval()
# origin shape: [100, 1, 28, 28]
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
loss_val = loss.item()
# Pytorch need a manual coding for accuracy
# max returns (value ,index)
_, predicted = torch.max(outputs.data, 1)
n_samples = labels.size(0)
n_correct = (predicted == labels).sum().item()
acc = 100.0 * n_correct / n_samples
return loss_val, acc
from tqdm import tqdm, tqdm_notebook, trange
for epoch in range(EPOCHS):
with tqdm_notebook(total=len(train_ds), desc=f"Train Epoch {epoch+1}") as pbar:
train_losses = []
train_accuracies = []
for i, (images, labels) in enumerate(train_ds):
loss_val, acc = train_step(model, images, labels)
train_losses.append(loss_val)
train_accuracies.append(acc)
pbar.update(1)
pbar.set_postfix_str(f"Loss: {loss_val:.4f} ({np.mean(train_losses):.4f}) Acc: {acc:.3f} ({np.mean(train_accuracies):.3f})")
# Test the model
# In test phase, we don't need to compute gradients (for memory efficiency)
with torch.no_grad():
with tqdm_notebook(total=len(test_ds), desc=f"Test_ Epoch {epoch+1}") as pbar:
test_losses = []
test_accuracies = []
for images, labels in test_ds:
loss_val, acc = test_step(model, images, labels)
test_losses.append(loss_val)
test_accuracies.append(acc)
pbar.update(1)
pbar.set_postfix_str(f"Loss: {loss_val:.4f} ({np.mean(test_losses):.4f}) Acc: {acc:.3f} ({np.mean(test_accuracies):.3f})")