-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdemo-rehearsal.py
323 lines (241 loc) · 7.72 KB
/
demo-rehearsal.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# coding: utf-8
## Theano Basics
# In[1]:
from __future__ import print_function
import theano
import numpy as np
from theano import tensor as T
floatX = theano.config.floatX
# In[2]:
# Convention:
# uppercase: symbolic theano element or function
# lowercase: numpy array
W = T.vector('w')
X = T.matrix('X')
Y = X.dot(W)
F = theano.function([W,X], Y)
w = np.ones(4)
x = np.ones((10,4))
y = F(w,x)
print(y)
# In[3]:
# The most underused tool in machine learning
# AUTODIFF
grad_w = T.grad(Y.sum(), W)
F_grad = theano.function([W,X], grad_w)
g = F_grad(w,x)
# this should be equal to the sum of the columns of X (do you know how to matrix calculus?)
print(g)
# In[4]:
# An easier example
B = T.scalar('E')
R = T.sqr(B)
A = T.grad(R, B)
Z = theano.function([B], A)
i = 2
l = Z(i)
print(l)
# In[5]:
# If that didn't blow your mind, well, it should have.
def sharedX(X):
return theano.shared(X.astype(floatX))
B = sharedX(np.ones(2))
R = T.sqr(B).sum()
A = T.grad(R, B)
Z = theano.function([], R, updates={B: B - .1*A})
for i in range(10):
print('cost function = {}'.format(Z()))
print('parameters = {}'.format(B.get_value()))
# Try to change range to 100 to see what happens
## Neural Nets
# In[6]:
""" Now that we now how to sum, we have enough to Deep Learn
... I should say something in the board about the Model-View-Controller way we usually
deep learn with Theano.
Model : Neural net parameters and dataset generator
View : Logging, graph updates, saving cross-validated best parameters
Controller : Update algorithm that follows gradient directions to optimize paramters
Download this dataset : http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz
"""
get_ipython().magic(u'matplotlib inline')
import cPickle
from pylab import imshow
train_set, valid_set, test_set = cPickle.load(file('mnist.pkl', 'r'))
print(len(train_set))
train_x, train_y = train_set
test_x , test_y = test_set
print(train_x.shape)
print(train_y.shape)
_ = imshow(train_x[0].reshape((28,28)), cmap='gray')
# In[7]:
def batch_iterator(x, y, batch_size):
num_batches = x.shape[0] // batch_size
for i in xrange(0,num_batches):
# TODO: use random integers instead of consecutive
# values to avoid biased gradients
first = i * batch_size
last = (i+1) * batch_size
x_batch = x[first:last].astype(floatX)
y_pre = y[first:last]
y_batch = np.zeros((batch_size, 10))
for row, col in enumerate(y_pre):
y_batch[row, col] = 1
yield (x_batch, y_batch.astype(floatX))
for x,y in batch_iterator(train_x, train_y, 10000):
print('{}, {}'.format(x.shape, y.shape))
print(y[0])
_ = imshow(x[0].reshape((28,28)), cmap='gray')
# In[13]:
# Define layers
def rectifier(input_dim, output_dim, X):
W = sharedX(np.random.normal(0, .001, size=(input_dim, output_dim)))
b = sharedX(np.zeros((output_dim,)))
Z = T.dot(X,W) + b.dimshuffle('x',0)
O = T.switch(Z>0, Z, 0)
return W,b,O
def softmax(input_dim, output_dim, X, Y):
W = sharedX(np.random.normal(0, .001, size=(input_dim, output_dim)))
b = sharedX(np.zeros((output_dim,)))
Z = T.dot(X,W) + b.dimshuffle('x',0)
O = T.nnet.softmax(Z)
cost = T.nnet.binary_crossentropy(O, Y).sum(axis=-1).mean()
return W,b,O,cost
X = T.matrix('X')
Y = T.matrix('Y')
W0, b0, O0 = rectifier(784, 100, X)
W1, b1, O1 = rectifier(100, 100, O0)
W2, b2, O2, cost = softmax(100, 10, O1, Y)
# Always write tests
F = theano.function([X,Y], [cost, O2])
x = np.zeros((100,784)).astype(floatX)
y = np.ones((100,10)).astype(floatX)
c, z = F(x,y)
assert c>0
assert z.shape == (100,10)
print(z[0])
# In[14]:
from collections import OrderedDict
params = [W0, b0, W1, b1, W2, b2]
updates = dict()
for p in params:
updates[p] = p - .01 * T.grad(cost, p)
updates = OrderedDict(updates)
trainer = theano.function([X,Y], cost, updates=updates)
# In[15]:
num_epochs = 100
for i in range(num_epochs):
print('-'*10)
print('Epoch: {}'.format(i))
for iter,b in enumerate(batch_iterator(train_x, train_y, 128)):
x = b[0]
y = b[1]
last_cost = trainer(x,y)
print('cost: {}'.format(trainer(x,y)))
# In[16]:
w0 = W0.get_value()
_ = imshow(w0[:,0].reshape((28,28)), cmap='gray')
# In[17]:
ERR = T.neq(O2.argmax(axis=-1), Y.argmax(axis=-1))
Ferr = theano.function([X,Y], ERR)
def testnet(x, y):
testerr = 0.
for b1,b2 in batch_iterator(x, y, 500):
testerr += Ferr(b1,b2)
return testerr.sum()
print('test error: {}, test acc: {}'.format(testnet(test_x, test_y),
1 - testnet(test_x, test_y) / 10000.))
## Convolutional Nets
# In[19]:
"""
We can do much better than this with more hidden neurons and dropout.
Watch Alec Radford's presentation to see how to do that
with Python/Theano: https://www.youtube.com/watch?v=S75EdAcXHKk
For now, lets move on to convnets.
"""
from theano.tensor.nnet.conv import conv2d
from theano.tensor.signal.downsample import max_pool_2d
def conv_rectifier(input_channels, output_channels, filter_dim, X):
W = sharedX(np.random.normal(0, .001, size=(output_channels,
input_channels,
filter_dim,
filter_dim)))
b = sharedX(np.zeros((output_channels,)))
Z = conv2d(X,W) + b.dimshuffle('x',0,'x','x')
DS = max_pool_2d(Z, ds=[2,2])
O = T.switch(DS>0, DS, 0)
return W,b,O
# test
X = T.tensor4('X')
W, b, O = conv_rectifier(1, 9, 5, X)
F = theano.function([X], O)
x = np.ones((5, 1, 28, 28))
print(x.shape)
o = F(x)
o.shape
# In[21]:
Y = T.matrix('Y')
W0, b0, O0 = conv_rectifier(1, 20, 5, X)
W1, b1, O1 = conv_rectifier(20, 50, 5, O0)
# test
F = theano.function([X], O1)
o = F(x)
print(o.shape)
# In[22]:
W2, b2, O2 = rectifier(50*4*4, 500, O1.flatten(2))
W3, b3, O3, cost = softmax(500, 10, O2, Y)
# Teeeeeest
x = np.ones((128,1,28,28)).astype(floatX)
y = np.ones((128,10)).astype(floatX)
F = theano.function([X, Y], [O3, cost])
z, c = F(x,y)
assert c>0
assert z.shape == (128,10)
# In[23]:
# We need to modify the batch_iterator slightly to serve formated images
def batch_iterator(x, y, batch_size):
num_batches = x.shape[0] // batch_size
for i in xrange(0,num_batches):
# TODO: use random integers instead of consecutive
# values to avoid biased gradients
first = i * batch_size
last = (i+1) * batch_size
x_batch = x[first:last].reshape((batch_size,1,28,28))
y_pre = y[first:last]
y_batch = np.zeros((batch_size, 10))
for row, col in enumerate(y_pre):
y_batch[row, col] = 1
yield (x_batch, y_batch)
for x,y in batch_iterator(train_x, train_y, 10000):
print('{}, {}'.format(x.shape, y.shape))
print(y[0])
_ = imshow(x[0].reshape((28,28)), cmap='gray')
# In[24]:
params = [W0, b0, W1, b1, W2, b2, W3, b3]
updates = dict()
for p in params:
updates[p] = p - .01 * T.grad(cost, p)
updates = OrderedDict(updates)
trainer = theano.function([X,Y], cost, updates=updates)
# In[ ]:
num_epochs = 100
for i in range(num_epochs):
print('-'*10)
print('Epoch: {}'.format(i))
for iter,b in enumerate(batch_iterator(train_x, train_y, 128)):
x = b[0]
y = b[1]
last_cost = trainer(x,y)
print('cost: {}'.format(trainer(x,y)))
# In[ ]:
w0 = W0.get_value()
_ = imshow(w0[0,0,:,:].reshape((5,5)), cmap='gray')
# In[ ]:
ERR = T.neq(O3.argmax(axis=-1), Y.argmax(axis=-1))
Ferr = theano.function([X,Y], ERR)
def testnet(x, y):
testerr = 0.
for b1,b2 in batch_iterator(x, y, 500):
testerr += Ferr(b1,b2)
return testerr.sum()
print('test error: {}, test acc: {}'.format(testnet(test_x, test_y),
1 - testnet(test_x, test_y) / 10000.))