Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/CNN/lab-10-2-mnist_nn.py
618 views
1
# Lab 10 MNIST and softmax
2
import torch
3
import torchvision.datasets as dsets
4
import torchvision.transforms as transforms
5
import random
6
7
device = 'cuda' if torch.cuda.is_available() else 'cpu'
8
9
# for reproducibility
10
random.seed(777)
11
torch.manual_seed(777)
12
if device == 'cuda':
13
torch.cuda.manual_seed_all(777)
14
15
# parameters
16
learning_rate = 0.001
17
training_epochs = 15
18
batch_size = 100
19
20
# MNIST dataset
21
mnist_train = dsets.MNIST(root='MNIST_data/',
22
train=True,
23
transform=transforms.ToTensor(),
24
download=True)
25
26
mnist_test = dsets.MNIST(root='MNIST_data/',
27
train=False,
28
transform=transforms.ToTensor(),
29
download=True)
30
31
# dataset loader
32
data_loader = torch.utils.data.DataLoader(dataset=mnist_train,
33
batch_size=batch_size,
34
shuffle=True,
35
drop_last=True)
36
37
# nn layers
38
linear1 = torch.nn.Linear(784, 256, bias=True)
39
linear2 = torch.nn.Linear(256, 256, bias=True)
40
linear3 = torch.nn.Linear(256, 10, bias=True)
41
relu = torch.nn.ReLU()
42
43
# model
44
model = torch.nn.Sequential(linear1, relu, linear2, relu, linear3).to(device)
45
46
# define cost/loss & optimizer
47
criterion = torch.nn.CrossEntropyLoss().to(device) # Softmax is internally computed.
48
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
49
50
total_batch = len(data_loader)
51
for epoch in range(training_epochs):
52
avg_cost = 0
53
54
for X, Y in data_loader:
55
# reshape input image into [batch_size by 784]
56
# label is not one-hot encoded
57
X = X.view(-1, 28 * 28).to(device)
58
Y = Y.to(device)
59
60
optimizer.zero_grad()
61
hypothesis = model(X)
62
cost = criterion(hypothesis, Y)
63
cost.backward()
64
optimizer.step()
65
66
avg_cost += cost / total_batch
67
68
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))
69
70
print('Learning finished')
71
72
# Test the model using test sets
73
with torch.no_grad():
74
X_test = mnist_test.test_data.view(-1, 28 * 28).float().to(device)
75
Y_test = mnist_test.test_labels.to(device)
76
77
prediction = model(X_test)
78
correct_prediction = torch.argmax(prediction, 1) == Y_test
79
accuracy = correct_prediction.float().mean()
80
print('Accuracy:', accuracy.item())
81
82
# Get one and predict
83
r = random.randint(0, len(mnist_test) - 1)
84
X_single_data = mnist_test.test_data[r:r + 1].view(-1, 28 * 28).float().to(device)
85
Y_single_data = mnist_test.test_labels[r:r + 1].to(device)
86
87
print('Label: ', Y_single_data.item())
88
single_prediction = model(X_single_data)
89
print('Prediction: ', torch.argmax(single_prediction, 1).item())
90