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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.optim as optim
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
BATCH_SIZE = 64
DOWNLOAD_DATASET = False
# list all transformations
transform = transforms.Compose([
transforms.Resize((28, 28)),
transforms.ToTensor(),
])
# download and load training dataset
trainDataset = torchvision.datasets.MNIST(root='./MNIST/', train=True, download=DOWNLOAD_DATASET, transform=transform)
trainLoader = torch.utils.data.DataLoader(trainDataset, batch_size=BATCH_SIZE, shuffle=True)
# download and load testing dataset
testDataset = torchvision.datasets.MNIST(root='./MNIST/', train=False, download=DOWNLOAD_DATASET, transform=transform)
testLoader = torch.utils.data.DataLoader(testDataset, batch_size=BATCH_SIZE, shuffle=False)
# functions to show an image
def imshow(img):
# img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
# get some random training images
dataIter = iter(trainLoader)
images, labels = dataIter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# parameters
INPUT_SIZE = 28
HIDDEN_SIZE = 150
OUTPUT_SIZE = 10
TIME_STEP = 28
MAX_EPOCH = 10
class ImageRNN(nn.Module):
def __init__(self, batchSize, timeStep, inputSize, hiddenSize, outputSize):
super(ImageRNN, self).__init__()
self.hiddenSize = hiddenSize
self.batchSize = batchSize
self.timeStep = timeStep
self.inputSize = inputSize
self.outputSize = outputSize
self.RNN = nn.RNN(self.inputSize, self.hiddenSize)
self.fc = nn.Linear(self.hiddenSize, self.outputSize)
def initializeHidden(self, ):
# (num_layers, batch_size, hidden_size)
return torch.zeros(1, self.batchSize, self.hiddenSize)
def forward(self, X):
# transforms X to dimensions: timeStep x batchSize x inputSize
X = X.permute(1, 0, 2)
self.batchSize = X.size(1)
self.hidden = self.initializeHidden()
# rnnOutput => timeStep, batchSize, hiddenSize (hidden states for each time step)
# self.hidden => 1, batchSize, hiddenSize (final state from each rnnOutput)
rnnOutput, self.hidden = self.RNN(X, self.hidden)
out = self.fc(self.hidden)
return out.view(-1, self.outputSize) # batchSize x outputSize
dataIter = iter(trainLoader)
images, labels = dataIter.next()
model = ImageRNN(BATCH_SIZE, TIME_STEP, INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE)
ypred = model(images.view(-1, 28, 28))
print(ypred[0:10])
# Device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Model instance
model = ImageRNN(BATCH_SIZE, TIME_STEP, INPUT_SIZE, HIDDEN_SIZE, OUTPUT_SIZE)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
def computeAccuracy(output, target):
''' Obtain accuracy for training round '''
corrects = (torch.max(output, 1)[1].view(target.size()).data == target.data).sum()
accuracy = 100.0 * corrects / torch.numel(target)
return accuracy.item()
for epoch in range(MAX_EPOCH): # loop over the dataset multiple times
trainLoss = 0.0
trainAccuracy = 0.0
model.train()
# TRAINING ROUND
for i, data in enumerate(trainLoader):
# reset hidden states
model.hidden = model.initializeHidden()
# get the inputs
inputs, labels = data
inputs = inputs.view(-1, 28, 28)
# forward
ypred = model(inputs)
loss = criterion(ypred, labels)
# backward + optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
trainLoss += loss.detach().item()
trainAccuracy += computeAccuracy(ypred, labels)
model.eval()
print('Epoch: {:2d} | Loss: {:8.4f} | Train Accuracy: {:5.2f}'.format(epoch, trainLoss / i, trainAccuracy / i))
model.eval()
testAccuracy = 0.0
for i, (images, labels) in enumerate(testLoader, 0):
images = images.to(device)
labels = labels.to(device)
outputs = model(images.view(-1, 28, 28))
testAccuracy += computeAccuracy(outputs, labels)
print('Test Accuracy: {:6.2f}'.format(testAccuracy / len(testLoader)))
|