-
Notifications
You must be signed in to change notification settings - Fork 0
/
02_MLP.py
129 lines (106 loc) · 4.52 KB
/
02_MLP.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
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
import torchvision
import torchvision.transforms as transforms
from tqdm import tqdm
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.lin1 = nn.Linear(784, 1024)
self.bn1 = nn.BatchNorm1d(1024)
self.lin2 = nn.Linear(1024, 1024)
self.bn2 = nn.BatchNorm1d(1024)
self.lin3 = nn.Linear(1024, 10)
self.bn = nn.BatchNorm1d(1024)
self.relu = nn.ReLU()
def forward(self, x):
n, c, h, w = x.shape
x = x.view(n, -1)
x = self.relu(self.lin1(x))
x = self.bn1(x)
x = self.relu(self.lin2(x))
x = self.bn2(x)
x = self.lin3(x)
return x
# alternative implementation with Sequential layer
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.classifier = nn.Sequential(nn.Linear(784, 1024),
nn.ReLU(),
nn.BatchNorm1d(1024),
nn.Linear(1024, 1024),
nn.ReLU(),
nn.BatchNorm1d(1024),
nn.Linear(1024, 10))
def forward(self, x):
n, c, h, w = x.shape
x = x.view(n, -1)
return self.classifier(x)
class Trainer(object):
def __init__(self, model, device, train_loader, test_loader, criterion,
optimizer):
self.model = model.to(device)
self.device = device
self.criterion = criterion
self.optimizer = optimizer
self.softmax = nn.Softmax(dim=1)
self.train_loader = train_loader
self.test_loader = test_loader
def train(self, epochs=10):
print('Initial accuracy: {}'.format(self.evaluate()))
for epoch in range(epochs):
self.model.train() # set the model to training mode
for images, labels in tqdm(self.train_loader,
total=len(self.train_loader)):
self.optimizer.zero_grad() # don't forget this line!
images, labels = images.to(self.device), labels.to(self.device)
output = self.softmax(self.model(images))
loss = self.criterion(output, labels)
loss.backward() # compute the derivatives of the model
optimizer.step() # update weights according to the optimizer
print('Accuracy at epoch {}: {}'.format(epoch + 1, self.evaluate()))
def evaluate(self):
self.model.eval() # set the model to eval mode
total = 0
for images, labels in tqdm(self.test_loader,
total=len(self.test_loader)):
images, labels = images.to(self.device), labels.to(self.device)
output = self.softmax(self.model(images))
predicted = torch.max(output, dim=1)[1] # argmax the output
total += (predicted == labels).sum().item()
return total / len(self.test_loader.dataset)
if __name__ == '__main__':
config = {'lr': 1e-4,
'momentum': 0.9,
'weight_decay': 0.001,
'batch_size': 8,
'epochs': 10,
'device': 'cuda:0',
'seed': 314}
# set the seeds to repeat the experiments
if 'cuda' in config['device']:
torch.cuda.manual_seed_all(config['seed'])
else:
torch.manual_seed(config['seed'])
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,),
(0.5,))])
model = MLP()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=config['lr'],
momentum=config['momentum'],
weight_decay=config['weight_decay'])
train_loader = DataLoader(
torchvision.datasets.MNIST('./mnist', download=True, train=True,
transform=transform),
batch_size=config['batch_size'], shuffle=True)
test_loader = DataLoader(
torchvision.datasets.MNIST('./mnist', download=True, train=False,
transform=transform),
batch_size=config['batch_size'], shuffle=False)
trainer = Trainer(model, config['device'], train_loader, test_loader,
criterion, optimizer)
trainer.train(epochs=config['epochs'])