-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtorch-mlp.py
67 lines (51 loc) · 1.96 KB
/
torch-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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
import time
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
trainData = torchvision.datasets.MNIST(root='./data',
train=True,
transform=transforms.ToTensor(),
download=True)
testData = torchvision.datasets.MNIST(root='./data',
train=False,
transform=transforms.ToTensor())
trainLoader = torch.utils.data.DataLoader(dataset=trainData,
batch_size=256,
shuffle=True)
testLoader = torch.utils.data.DataLoader(dataset=testData,
batch_size=256,
shuffle=False)
model = nn.Sequential(nn.Linear(784, 400),
nn.ReLU(),
nn.Linear(400, 10),
nn.LogSoftmax(dim=1)).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
def train():
for epoch in range(1, 11):
for i, (x, y) in enumerate(trainLoader):
(x, y) = x.to(device), y.to(device)
x = x.reshape(-1, 784)
o = model(x)
loss = F.nll_loss(o, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if i % 100 == 0:
print("Epoch: {}\tLoss: {}".format(epoch, loss.item()))
tic = time.time()
train()
print(time.time()-tic, "s")
n, N = 0, 0
with torch.no_grad():
for (x, y) in testLoader:
(x, y) = x.to(device), y.to(device)
x = x.reshape(-1, 784)
o = model(x)
_, ŷ = torch.max(o, 1)
N += y.size(0)
n += torch.sum(ŷ == y).item()
print("Accuracy: {}".format(n/N))