Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
deeplearningzerotoall
GitHub Repository: deeplearningzerotoall/PyTorch
Path: blob/master/CNN/lab-10-8-mnist_nn_selu(wip).py
631 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
keep_prob = 0.7
20
21
# MNIST dataset
22
mnist_train = dsets.MNIST(root='MNIST_data/',
23
train=True,
24
transform=transforms.ToTensor(),
25
download=True)
26
27
mnist_test = dsets.MNIST(root='MNIST_data/',
28
train=False,
29
transform=transforms.ToTensor(),
30
download=True)
31
32
# dataset loader
33
data_loader = torch.utils.data.DataLoader(dataset=mnist_train,
34
batch_size=batch_size,
35
shuffle=True,
36
drop_last=True)
37
38
# nn layers
39
linear1 = torch.nn.Linear(784, 512, bias=True)
40
linear2 = torch.nn.Linear(512, 512, bias=True)
41
linear3 = torch.nn.Linear(512, 512, bias=True)
42
linear4 = torch.nn.Linear(512, 512, bias=True)
43
linear5 = torch.nn.Linear(512, 10, bias=True)
44
selu = torch.nn.SELU()
45
46
# xavier initialization
47
torch.nn.init.xavier_uniform_(linear1.weight)
48
torch.nn.init.xavier_uniform_(linear2.weight)
49
torch.nn.init.xavier_uniform_(linear3.weight)
50
torch.nn.init.xavier_uniform_(linear4.weight)
51
torch.nn.init.xavier_uniform_(linear5.weight)
52
53
# model
54
model = torch.nn.Sequential(linear1, selu,
55
linear2, selu,
56
linear3, selu,
57
linear4, selu,
58
linear5).to(device)
59
60
# define cost/loss & optimizer
61
criterion = torch.nn.CrossEntropyLoss().to(device) # Softmax is internally computed.
62
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
63
64
total_batch = len(data_loader)
65
model.train() # set the model to train mode (dropout=True)
66
for epoch in range(training_epochs):
67
avg_cost = 0
68
69
for X, Y in data_loader:
70
# reshape input image into [batch_size by 784]
71
# label is not one-hot encoded
72
X = X.view(-1, 28 * 28).to(device)
73
Y = Y.to(device)
74
75
optimizer.zero_grad()
76
hypothesis = model(X)
77
cost = criterion(hypothesis, Y)
78
cost.backward()
79
optimizer.step()
80
81
avg_cost += cost / total_batch
82
83
print('Epoch:', '%04d' % (epoch + 1), 'cost =', '{:.9f}'.format(avg_cost))
84
85
print('Learning finished')
86
87
# Test model and check accuracy
88
with torch.no_grad():
89
model.eval() # set the model to evaluation mode (dropout=False)
90
91
# Test the model using test sets
92
X_test = mnist_test.test_data.view(-1, 28 * 28).float().to(device)
93
Y_test = mnist_test.test_labels.to(device)
94
95
prediction = model(X_test)
96
correct_prediction = torch.argmax(prediction, 1) == Y_test
97
accuracy = correct_prediction.float().mean()
98
print('Accuracy:', accuracy.item())
99
100
# Get one and predict
101
r = random.randint(0, len(mnist_test) - 1)
102
X_single_data = mnist_test.test_data[r:r + 1].view(-1, 28 * 28).float().to(device)
103
Y_single_data = mnist_test.test_labels[r:r + 1].to(device)
104
105
print('Label: ', Y_single_data.item())
106
single_prediction = model(X_single_data)
107
print('Prediction: ', torch.argmax(single_prediction, 1).item())
108