forked from lazyprogrammer/machine_learning_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpytorch_example.py
149 lines (103 loc) · 3.53 KB
/
pytorch_example.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
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# https://deeplearningcourses.com/c/data-science-deep-learning-in-theano-tensorflow
# https://www.udemy.com/data-science-deep-learning-in-theano-tensorflow
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
# Linux and Mac instructions:
# http://pytorch.org/#pip-install-pytorch
# Windows instructions (just one line):
# conda install -c peterjc123 pytorch
# Note: is helpful to look at keras_example.py first
import numpy as np
import matplotlib.pyplot as plt
from util import get_normalized_data
import torch
from torch.autograd import Variable
from torch import optim
# get the data, same as Theano + Tensorflow examples
# no need to split now, the fit() function will do it
X, Y = get_normalized_data()
# get shapes
_, D = X.shape
K = len(set(Y))
# split the data
Xtrain = X[:-1000,]
Ytrain = Y[:-1000]
Xtest = X[-1000:,]
Ytest = Y[-1000:]
# Note: no need to convert Y to indicator matrix
# the model will be a sequence of layers
model = torch.nn.Sequential()
# ANN with layers [784] -> [500] -> [300] -> [10]
model.add_module("dense1", torch.nn.Linear(D, 500))
model.add_module("relu1", torch.nn.ReLU())
model.add_module("dense2", torch.nn.Linear(500, 300))
model.add_module("relu2", torch.nn.ReLU())
model.add_module("dense3", torch.nn.Linear(300, K))
# Note: no final softmax!
# just like Tensorflow, it's included in cross-entropy function
# define a loss function
# other loss functions can be found here:
# http://pytorch.org/docs/master/nn.html#loss-functions
loss = torch.nn.CrossEntropyLoss(size_average=True)
# define an optimizer
# other optimizers can be found here:
# http://pytorch.org/docs/master/optim.html
optimizer = optim.Adam(model.parameters())
# define the training procedure
# i.e. one step of gradient descent
# there are lots of steps
# so we encapsulate it in a function
# Note: inputs and labels are torch tensors
def train(model, loss, optimizer, inputs, labels):
inputs = Variable(inputs, requires_grad=False)
labels = Variable(labels, requires_grad=False)
# Reset gradient
optimizer.zero_grad()
# Forward
logits = model.forward(inputs)
output = loss.forward(logits, labels)
# Backward
output.backward()
# Update parameters
optimizer.step()
# what's the difference between backward() and step()?
return output.data[0]
# define the prediction procedure
# also encapsulate these steps
# Note: inputs is a torch tensor
def predict(model, inputs):
inputs = Variable(inputs, requires_grad=False)
logits = model.forward(inputs)
return logits.data.numpy().argmax(axis=1)
### prepare for training loop ###
# convert the data arrays into torch tensors
Xtrain = torch.from_numpy(Xtrain).float()
Ytrain = torch.from_numpy(Ytrain).long()
Xtest = torch.from_numpy(Xtest).float()
epochs = 15
batch_size = 32
n_batches = Xtrain.size()[0] // batch_size
costs = []
test_accuracies = []
for i in range(epochs):
cost = 0.
for j in range(n_batches):
Xbatch = Xtrain[j*batch_size:(j+1)*batch_size]
Ybatch = Ytrain[j*batch_size:(j+1)*batch_size]
cost += train(model, loss, optimizer, Xbatch, Ybatch)
Ypred = predict(model, Xtest)
acc = np.mean(Ytest == Ypred)
print("Epoch: %d, cost: %f, acc: %.2f" % (i, cost / n_batches, acc))
# for plotting
costs.append(cost / n_batches)
test_accuracies.append(acc)
# EXERCISE: plot test cost + training accuracy too
# plot the results
plt.plot(costs)
plt.title('Training cost')
plt.show()
plt.plot(test_accuracies)
plt.title('Test accuracies')
plt.show()