-
Notifications
You must be signed in to change notification settings - Fork 0
/
mnist.py
90 lines (65 loc) · 2.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
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
import numpy as np
import torch
import mnistdataset
import models
imageSize = (28, 28)
inputSize = imageSize[0] * imageSize[1]
outputSize = 10
def tensorToNumpy(tensor) -> np.ndarray:
return tensor.cpu().data.numpy()
def initializeDevice(model):
shouldUseCuda = torch.cuda.is_available()
device = torch.device("cuda" if shouldUseCuda else "cpu")
model.to(device)
if shouldUseCuda:
model.cuda()
return device
def createTensor(array, device, numCols):
return torch.tensor(array, device=device, dtype=torch.float32).view(-1, numCols)
def createLabelsArray(y, numCols):
"""
input:
y -- (N,) integer labels
output:
labelArray -- (N, 10) consisting of zeros except where integer labels
assign a 1.0
"""
labelsArray = np.zeros((y.shape[0], numCols))
labelsArray[np.arange(y.shape[0]),y] = 1.0
return labelsArray
def trainModel(model, inputTensorTrain, labelTensorTrain, learningRate, numEpochs):
losses = []
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learningRate)
for epoch in range(numEpochs):
optimizer.zero_grad()
outputsTensor = model(inputTensorTrain)
loss = criterion(outputsTensor, labelTensorTrain)
lossValue = loss.cpu().data.numpy()
losses.append(lossValue)
loss.backward()
optimizer.step()
print(f"epoch {epoch:05d}, loss {loss.item():0.6f}", end="\r")
print()
return losses
def main():
modelClass, numEpochs, learningRate = models.MnistModelLinear, 10_000, 0.1
model = modelClass()
device = initializeDevice(model)
datasetDict = mnistdataset.loadDataset()
x = datasetDict["train"]["images"]
y = datasetDict["train"]["labels"]
inputTensorTrain = createTensor(x / 255, device, inputSize)
labelsArray = createLabelsArray(y, outputSize)
labelTensorTrain = createTensor(labelsArray, device, outputSize)
losses = trainModel(model, inputTensorTrain, labelTensorTrain, learningRate, numEpochs)
xtest = datasetDict["test"]["images"]
ytest = datasetDict["test"]["labels"]
labelTensorTest = createTensor(xtest / 255, device, inputSize)
with torch.no_grad():
predictedArray = model(labelTensorTest).cpu().data.numpy()
predictedLabels = np.argmax(predictedArray, axis=1)
numCorrectlyPredicted = np.sum(predictedLabels == ytest)
print(f"Error rate: {100 - 100 * numCorrectlyPredicted/predictedLabels.shape[0]:0.2f}%")
if __name__ == "__main__":
main()