-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
mnist.py
executable file
·53 lines (42 loc) · 1.52 KB
/
mnist.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
import dezero
import dezero.functions as F
from dezero import DataLoader
from dezero.models import MLP
max_epoch = 5
batch_size = 100
hidden_size = 1000
train_set = dezero.datasets.MNIST(train=True)
test_set = dezero.datasets.MNIST(train=False)
train_loader = DataLoader(train_set, batch_size)
test_loader = DataLoader(test_set, batch_size, shuffle=False)
model = MLP((hidden_size, hidden_size, 10), activation=F.relu)
optimizer = dezero.optimizers.Adam().setup(model)
optimizer.add_hook(dezero.optimizers.WeightDecay(1e-4)) # Weight decay
if dezero.cuda.gpu_enable:
train_loader.to_gpu()
test_loader.to_gpu()
model.to_gpu()
for epoch in range(max_epoch):
sum_loss, sum_acc = 0, 0
for x, t in train_loader:
y = model(x)
loss = F.softmax_cross_entropy(y, t)
acc = F.accuracy(y, t)
model.cleargrads()
loss.backward()
optimizer.update()
sum_loss += float(loss.data) * len(t)
sum_acc += float(acc.data) * len(t)
print('epoch: {}'.format(epoch+1))
print('train loss: {}, accuracy: {}'.format(
sum_loss / len(train_set), sum_acc / len(train_set)))
sum_loss, sum_acc = 0, 0
with dezero.no_grad():
for x, t in test_loader:
y = model(x)
loss = F.softmax_cross_entropy(y, t)
acc = F.accuracy(y, t)
sum_loss += float(loss.data) * len(t)
sum_acc += float(acc.data) * len(t)
print('test loss: {}, accuracy: {}'.format(
sum_loss / len(test_set), sum_acc / len(test_set)))