Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/CNN/lab-10-4-mnist_nn_deep.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, 512, bias=True)
39
linear2 = torch.nn.Linear(512, 512, bias=True)
40
linear3 = torch.nn.Linear(512, 512, bias=True)
41
linear4 = torch.nn.Linear(512, 512, bias=True)
42
linear5 = torch.nn.Linear(512, 10, bias=True)
43
relu = torch.nn.ReLU()
44
45
# xavier initialization
46
torch.nn.init.xavier_uniform_(linear1.weight)
47
torch.nn.init.xavier_uniform_(linear2.weight)
48
torch.nn.init.xavier_uniform_(linear3.weight)
49
torch.nn.init.xavier_uniform_(linear4.weight)
50
torch.nn.init.xavier_uniform_(linear5.weight)
51
52
# model
53
model = torch.nn.Sequential(linear1, relu, linear2, relu, linear3).to(device)
54
55
# define cost/loss & optimizer
56
criterion = torch.nn.CrossEntropyLoss().to(device) # Softmax is internally computed.
57
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
58
59
total_batch = len(data_loader)
60
for epoch in range(training_epochs):
61
avg_cost = 0
62
63
for X, Y in data_loader:
64
# reshape input image into [batch_size by 784]
65
# label is not one-hot encoded
66
X = X.view(-1, 28 * 28).to(device)
67
Y = Y.to(device)
68
69
optimizer.zero_grad()
70
hypothesis = model(X)
71
cost = criterion(hypothesis, Y)
72
cost.backward()
73
optimizer.step()
74
75
avg_cost += cost / total_batch
76
77
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))
78
79
print('Learning finished')
80
81
# Test the model using test sets
82
with torch.no_grad():
83
X_test = mnist_test.test_data.view(-1, 28 * 28).float().to(device)
84
Y_test = mnist_test.test_labels.to(device)
85
86
prediction = model(X_test)
87
correct_prediction = torch.argmax(prediction, 1) == Y_test
88
accuracy = correct_prediction.float().mean()
89
print('Accuracy:', accuracy.item())
90
91
# Get one and predict
92
r = random.randint(0, len(mnist_test) - 1)
93
X_single_data = mnist_test.test_data[r:r + 1].view(-1, 28 * 28).float().to(device)
94
Y_single_data = mnist_test.test_labels[r:r + 1].to(device)
95
96
print('Label: ', Y_single_data.item())
97
single_prediction = model(X_single_data)
98
print('Prediction: ', torch.argmax(single_prediction, 1).item())
99