Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/CNN/lab-11-2-mnist_deep_cnn.py
618 views
1
# Lab 11 MNIST and Deep learning CNN
2
import torch
3
import torchvision.datasets as dsets
4
import torchvision.transforms as transforms
5
import torch.nn.init
6
7
device = 'cuda' if torch.cuda.is_available() else 'cpu'
8
9
# for reproducibility
10
torch.manual_seed(777)
11
if device == 'cuda':
12
torch.cuda.manual_seed_all(777)
13
14
# parameters
15
learning_rate = 0.001
16
training_epochs = 15
17
batch_size = 100
18
19
# MNIST dataset
20
mnist_train = dsets.MNIST(root='MNIST_data/',
21
train=True,
22
transform=transforms.ToTensor(),
23
download=True)
24
25
mnist_test = dsets.MNIST(root='MNIST_data/',
26
train=False,
27
transform=transforms.ToTensor(),
28
download=True)
29
30
# dataset loader
31
data_loader = torch.utils.data.DataLoader(dataset=mnist_train,
32
batch_size=batch_size,
33
shuffle=True,
34
drop_last=True)
35
36
# CNN Model
37
class CNN(torch.nn.Module):
38
39
def __init__(self):
40
super(CNN, self).__init__()
41
self.keep_prob = 0.5
42
# L1 ImgIn shape=(?, 28, 28, 1)
43
# Conv -> (?, 28, 28, 32)
44
# Pool -> (?, 14, 14, 32)
45
self.layer1 = torch.nn.Sequential(
46
torch.nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),
47
torch.nn.ReLU(),
48
torch.nn.MaxPool2d(kernel_size=2, stride=2))
49
# L2 ImgIn shape=(?, 14, 14, 32)
50
# Conv ->(?, 14, 14, 64)
51
# Pool ->(?, 7, 7, 64)
52
self.layer2 = torch.nn.Sequential(
53
torch.nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1),
54
torch.nn.ReLU(),
55
torch.nn.MaxPool2d(kernel_size=2, stride=2))
56
# L3 ImgIn shape=(?, 7, 7, 64)
57
# Conv ->(?, 7, 7, 128)
58
# Pool ->(?, 4, 4, 128)
59
self.layer3 = torch.nn.Sequential(
60
torch.nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
61
torch.nn.ReLU(),
62
torch.nn.MaxPool2d(kernel_size=2, stride=2, padding=1))
63
64
# L4 FC 4x4x128 inputs -> 625 outputs
65
self.fc1 = torch.nn.Linear(4 * 4 * 128, 625, bias=True)
66
torch.nn.init.xavier_uniform_(self.fc1.weight)
67
self.layer4 = torch.nn.Sequential(
68
self.fc1,
69
torch.nn.ReLU(),
70
torch.nn.Dropout(p=1 - self.keep_prob))
71
# L5 Final FC 625 inputs -> 10 outputs
72
self.fc2 = torch.nn.Linear(625, 10, bias=True)
73
torch.nn.init.xavier_uniform_(self.fc2.weight)
74
75
def forward(self, x):
76
out = self.layer1(x)
77
out = self.layer2(out)
78
out = self.layer3(out)
79
out = out.view(out.size(0), -1) # Flatten them for FC
80
out = self.layer4(out)
81
out = self.fc2(out)
82
return out
83
84
85
# instantiate CNN model
86
model = CNN().to(device)
87
88
# define cost/loss & optimizer
89
criterion = torch.nn.CrossEntropyLoss().to(device) # Softmax is internally computed.
90
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
91
92
# train my model
93
total_batch = len(data_loader)
94
model.train() # set the model to train mode (dropout=True)
95
print('Learning started. It takes sometime.')
96
for epoch in range(training_epochs):
97
avg_cost = 0
98
99
for X, Y in data_loader:
100
# image is already size of (28x28), no reshape
101
# label is not one-hot encoded
102
X = X.to(device)
103
Y = Y.to(device)
104
105
optimizer.zero_grad()
106
hypothesis = model(X)
107
cost = criterion(hypothesis, Y)
108
cost.backward()
109
optimizer.step()
110
111
avg_cost += cost / total_batch
112
113
print('[Epoch: {:>4}] cost = {:>.9}'.format(epoch + 1, avg_cost))
114
115
print('Learning Finished!')
116
117
# Test model and check accuracy
118
with torch.no_grad():
119
model.eval() # set the model to evaluation mode (dropout=False)
120
121
X_test = mnist_test.test_data.view(len(mnist_test), 1, 28, 28).float().to(device)
122
Y_test = mnist_test.test_labels.to(device)
123
124
prediction = model(X_test)
125
correct_prediction = torch.argmax(prediction, 1) == Y_test
126
accuracy = correct_prediction.float().mean()
127
print('Accuracy:', accuracy.item())
128