-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlenet_original.py
160 lines (133 loc) · 4.6 KB
/
lenet_original.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
import torch
import torch.nn as nn
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import transforms
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
'''
Step 1:
'''
# MNIST dataset
train_dataset = datasets.MNIST(root='./mnist_data/',
train=True,
transform=transforms.ToTensor(),
download=True)
test_dataset = datasets.MNIST(root='./mnist_data/',
train=False,
transform=transforms.ToTensor())
'''
Step 2: LeNet5
'''
# Modern LeNet uses this layer for C3
class C3_layer_full(nn.Module):
def __init__(self):
super(C3_layer_full, self).__init__()
self.conv_layer = nn.Conv2d(6, 16, kernel_size=5)
def forward(self, x):
return self.conv_layer(x)
# Original LeNet uses this layer for C3
class C3_layer(nn.Module):
def __init__(self):
super(C3_layer, self).__init__()
self.ch_in_3 = [[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[0, 4, 5],
[0, 1, 5]] # filter with 3 subset of input channels
self.ch_in_4 = [[0, 1, 2, 3],
[1, 2, 3, 4],
[2, 3, 4, 5],
[0, 3, 4, 5],
[0, 1, 4, 5],
[0, 1, 2, 5],
[0, 1, 3, 4],
[1, 2, 4, 5],
[0, 2, 3, 5]] # filter with 4 subset of input channels
# put implementation here
pass
def forward(self, x):
# put implementation here
pass
class LeNet(nn.Module) :
def __init__(self) :
super(LeNet, self).__init__()
#padding=2 makes 28x28 image into 32x32
self.C1_layer = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=5, padding=2),
nn.Tanh()
)
self.P2_layer = nn.Sequential(
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Tanh()
)
self.C3_layer = nn.Sequential(
#C3_layer_full(),
C3_layer(),
nn.Tanh()
)
self.P4_layer = nn.Sequential(
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Tanh()
)
self.C5_layer = nn.Sequential(
nn.Linear(5*5*16, 120),
nn.Tanh()
)
self.F6_layer = nn.Sequential(
nn.Linear(120, 84),
nn.Tanh()
)
self.F7_layer = nn.Linear(84, 10)
self.tanh = nn.Tanh()
def forward(self, x) :
output = self.C1_layer(x)
output = self.P2_layer(output)
output = self.C3_layer(output)
output = self.P4_layer(output)
output = output.view(-1,5*5*16)
output = self.C5_layer(output)
output = self.F6_layer(output)
output = self.F7_layer(output)
return output
'''
Step 3
'''
model = LeNet().to(device)
loss_function = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-1)
# print total number of trainable parameters
param_ct = sum([p.numel() for p in model.parameters()])
print(f"Total number of trainable parameters: {param_ct}")
'''
Step 4
'''
train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=100, shuffle=True)
import time
start = time.time()
for epoch in range(10) :
print("{}th epoch starting.".format(epoch))
for images, labels in train_loader :
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
train_loss = loss_function(model(images), labels)
train_loss.backward()
optimizer.step()
end = time.time()
print("Time ellapsed in training is: {}".format(end - start))
'''
Step 5
'''
test_loss, correct, total = 0, 0, 0
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=100, shuffle=False)
for images, labels in test_loader :
images, labels = images.to(device), labels.to(device)
output = model(images)
test_loss += loss_function(output, labels).item()
pred = output.max(1, keepdim=True)[1]
correct += pred.eq(labels.view_as(pred)).sum().item()
total += labels.size(0)
print('[Test set] Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
test_loss /total, correct, total,
100. * correct / total))