In [1]:
from theano.sandbox import cuda
cuda.use('gpu1')


Using gpu device 0: Tesla K80 (CNMeM is disabled, cuDNN 5103)
/home/ubuntu/anaconda2/lib/python2.7/site-packages/theano/sandbox/cuda/__init__.py:600: UserWarning: Your cuDNN version is more recent than the one Theano officially supports. If you see any problems, try updating Theano or downgrading cuDNN to version 5.
  warnings.warn(warn)
WARNING (theano.sandbox.cuda): Ignoring call to use(1), GPU number 0 is already in use.

In [1]:
%matplotlib inline
import utils; reload(utils)
from utils import *
from __future__ import division, print_function


Using Theano backend.

Setup

We're going to download the collected works of Nietzsche to use as our data for this class.


In [2]:
path = get_file('nietzsche.txt', origin="https://s3.amazonaws.com/text-datasets/nietzsche.txt")
text = open(path).read()
print('corpus length:', len(text))


corpus length: 600901

In [3]:
chars = sorted(list(set(text)))
vocab_size = len(chars)+1
print('total chars:', vocab_size)


total chars: 86

Sometimes it's useful to have a zero value in the dataset, e.g. for padding


In [4]:
chars.insert(0, "\0")

In [5]:
''.join(chars[1:])


Out[5]:
'\n !"\'(),-.0123456789:;=?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz\x86\xa4\xa6\xa9\xab\xc3'

Map from chars to indices and back again


In [6]:
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))

idx will be the data we use from now own - it simply converts all the characters to their index (based on the mapping above)


In [7]:
idx = [char_indices[c] for c in text]

In [8]:
idx[:10]


Out[8]:
[40, 42, 29, 30, 25, 27, 29, 1, 1, 1]

In [9]:
''.join(indices_char[i] for i in idx[:70])


Out[9]:
'PREFACE\n\n\nSUPPOSING that Truth is a woman--what then? Is there not gro'

3 char model

Create inputs

Create a list of every 4th character, starting at the 0th, 1st, 2nd, then 3rd characters


In [10]:
cs=3
c1_dat = [idx[i] for i in xrange(0, len(idx)-1-cs, cs)]
c2_dat = [idx[i+1] for i in xrange(0, len(idx)-1-cs, cs)]
c3_dat = [idx[i+2] for i in xrange(0, len(idx)-1-cs, cs)]
c4_dat = [idx[i+3] for i in xrange(0, len(idx)-1-cs, cs)]

In [12]:
len(idx)//3, len(c1_dat), len(c2_dat), len(c3_dat), len(c4_dat)


Out[12]:
(200300, 200299, 200299, 200299, 200299)

Our inputs


In [13]:
[indices_char[x] for xs in (c1_dat[-2:], c2_dat[-2:], c3_dat[-2:]) for x in xs]


Out[13]:
['i', 'u', 'n', 'l', 'f', 'n']

In [14]:
idx[-16:], c1_dat[-2:], c2_dat[-2:], c3_dat[-2:], c4_dat[-2:]


Out[14]:
([72, 2, 68, 59, 2, 72, 62, 67, 59, 74, 65, 67, 58, 72, 72, 10],
 [62, 74],
 [67, 65],
 [59, 67],
 [74, 58])

In [11]:
x1 = np.stack(c1_dat[:-2])
x2 = np.stack(c2_dat[:-2])
x3 = np.stack(c3_dat[:-2])

Our output


In [12]:
y = np.stack(c4_dat[:-2])

The first 4 inputs and outputs


In [17]:
x1[:4], x2[:4], x3[:4]


Out[17]:
(array([40, 30, 29,  1]), array([42, 25,  1, 43]), array([29, 27,  1, 45]))

In [18]:
y[:4]


Out[18]:
array([30, 29,  1, 40])

In [19]:
x1.shape, y.shape


Out[19]:
((200297,), (200297,))

The number of latent factors to create (i.e. the size of the embedding matrix)


In [13]:
n_fac = 42

Create inputs and embedding outputs for each of our 3 character inputs


In [21]:
def embedding_input(name, n_in, n_out):
    inp = Input(shape=(1,), dtype='int64', name=name)
    emb = Embedding(n_in, n_out, input_length=1)(inp)
    return inp, Flatten()(emb)

In [22]:
c1_in, c1 = embedding_input('c1', vocab_size, n_fac)
c2_in, c2 = embedding_input('c2', vocab_size, n_fac)
c3_in, c3 = embedding_input('c3', vocab_size, n_fac)

Create and train model

Pick a size for our hidden state


In [23]:
n_hidden = 256

This is the 'green arrow' from our diagram - the layer operation from input to hidden.


In [24]:
dense_in = Dense(n_hidden, activation='relu')

Our first hidden activation is simply this function applied to the result of the embedding of the first character.


In [25]:
c1_hidden = dense_in(c1)

This is the 'orange arrow' from our diagram - the layer operation from hidden to hidden.


In [26]:
dense_hidden = Dense(n_hidden, activation='tanh')

Our second and third hidden activations sum up the previous hidden state (after applying dense_hidden) to the new input state.


In [27]:
c2_dense = dense_in(c2)
hidden_2 = dense_hidden(c1_hidden)
c2_hidden = merge([c2_dense, hidden_2])

In [28]:
c3_dense = dense_in(c3)
hidden_3 = dense_hidden(c2_hidden)
c3_hidden = merge([c3_dense, hidden_3])

This is the 'blue arrow' from our diagram - the layer operation from hidden to output.


In [29]:
dense_out = Dense(vocab_size, activation='softmax')

The third hidden state is the input to our output layer.


In [30]:
c4_out = dense_out(c3_hidden)

In [31]:
model = Model([c1_in, c2_in, c3_in], c4_out)

In [32]:
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

In [33]:
model.optimizer.lr.set_value(0.000001)

In [34]:
model.fit([x1,x2,x3], y, batch_size=64, nb_epoch=4)


Epoch 1/4
200297/200297 [==============================] - 13s - loss: 4.4175    
Epoch 2/4
200297/200297 [==============================] - 13s - loss: 4.2861    
Epoch 3/4
200297/200297 [==============================] - 13s - loss: 4.0043    
Epoch 4/4
200297/200297 [==============================] - 13s - loss: 3.6019    
Out[34]:
<keras.callbacks.History at 0x7fe6b2ace850>

In [35]:
model.optimizer.lr.set_value(0.01)

In [36]:
model.fit([x1,x2,x3], y, batch_size=64, nb_epoch=4)


Epoch 1/4
200297/200297 [==============================] - 13s - loss: 3.4119    
Epoch 2/4
 61248/200297 [========>.....................] - ETA: 9s - loss: 2.9560

KeyboardInterruptTraceback (most recent call last)
<ipython-input-36-bf5c9276ab35> in <module>()
----> 1 model.fit([x1,x2,x3], y, batch_size=64, nb_epoch=4)

/home/ubuntu/anaconda2/lib/python2.7/site-packages/keras/engine/training.pyc in fit(self, x, y, batch_size, nb_epoch, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight)
   1104                               verbose=verbose, callbacks=callbacks,
   1105                               val_f=val_f, val_ins=val_ins, shuffle=shuffle,
-> 1106                               callback_metrics=callback_metrics)
   1107 
   1108     def evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None):

/home/ubuntu/anaconda2/lib/python2.7/site-packages/keras/engine/training.pyc in _fit_loop(self, f, ins, out_labels, batch_size, nb_epoch, verbose, callbacks, val_f, val_ins, shuffle, callback_metrics)
    822                 batch_logs['size'] = len(batch_ids)
    823                 callbacks.on_batch_begin(batch_index, batch_logs)
--> 824                 outs = f(ins_batch)
    825                 if type(outs) != list:
    826                     outs = [outs]

/home/ubuntu/anaconda2/lib/python2.7/site-packages/keras/backend/theano_backend.pyc in __call__(self, inputs)
    715     def __call__(self, inputs):
    716         assert type(inputs) in {list, tuple}
--> 717         return self.function(*inputs)
    718 
    719 

/home/ubuntu/anaconda2/lib/python2.7/site-packages/theano/compile/function_module.pyc in __call__(self, *args, **kwargs)
    857         t0_fn = time.time()
    858         try:
--> 859             outputs = self.fn()
    860         except Exception:
    861             if hasattr(self.fn, 'position_of_error'):

KeyboardInterrupt: 

In [37]:
model.optimizer.lr.set_value(0.000001)

In [38]:
model.fit([x1,x2,x3], y, batch_size=64, nb_epoch=4)


Epoch 1/4
200297/200297 [==============================] - 13s - loss: 2.8602    
Epoch 2/4
200297/200297 [==============================] - 13s - loss: 2.8182    
Epoch 3/4
200297/200297 [==============================] - 13s - loss: 2.7976    
Epoch 4/4
200297/200297 [==============================] - 13s - loss: 2.7861    
Out[38]:
<keras.callbacks.History at 0x7fe6a6cac750>

In [39]:
model.optimizer.lr.set_value(0.01)

In [40]:
model.fit([x1,x2,x3], y, batch_size=64, nb_epoch=4)


Epoch 1/4
200297/200297 [==============================] - 14s - loss: 2.9825    
Epoch 2/4
200297/200297 [==============================] - 13s - loss: 2.9395    
Epoch 3/4
200297/200297 [==============================] - 13s - loss: 2.9475    
Epoch 4/4
200297/200297 [==============================] - 13s - loss: 2.9542    
Out[40]:
<keras.callbacks.History at 0x7fe6a6cacc10>

Test model


In [43]:
def get_next(inp):
    idxs = [char_indices[c] for c in inp]
    arrs = [np.array(i)[np.newaxis] for i in idxs]
    p = model.predict(arrs)
    i = np.argmax(p)
    return chars[i]

In [44]:
get_next('phi')


Out[44]:
't'

In [45]:
get_next(' th')


Out[45]:
'e'

In [46]:
get_next(' an')


Out[46]:
'd'

In [124]:
model_path = "data/rnn/models/"
%mkdir -p $model_path

In [ ]:
model.save_weights(model_path+'model1.h5')

In [42]:
model.load_weights(model_path+'model1.h5')

Our first RNN!

Create inputs

This is the size of our unrolled RNN.


In [29]:
cs=8

For each of 0 through 7, create a list of every 8th character with that starting point. These will be the 8 inputs to out model.


In [30]:
c_in_dat = [[idx[i+n] for i in xrange(0, len(idx)-1-cs, cs)]
            for n in xrange(cs)]

Then create a list of the next character in each of these series. This will be the labels for our model.


In [31]:
c_out_dat = [idx[i+cs] for i in xrange(0, len(idx)-1-cs, cs)]

In [32]:
xs = [np.stack(c[:-2]) for c in c_in_dat]

In [29]:
len(xs), xs[0].shape


Out[29]:
(8, (75110,))

In [30]:
y = np.stack(c_out_dat[:-2])

So each column below is one series of 8 characters from the text.


In [31]:
[xs[n][:cs] for n in range(cs)]


Out[31]:
[array([40,  1, 33,  2, 72, 67, 73,  2]),
 array([42,  1, 38, 44,  2,  9, 61, 73]),
 array([29, 43, 31, 71, 54,  9, 58, 61]),
 array([30, 45,  2, 74,  2, 76, 67, 58]),
 array([25, 40, 73, 73, 76, 61, 24, 71]),
 array([27, 40, 61, 61, 68, 54,  2, 58]),
 array([29, 39, 54,  2, 66, 73, 33,  2]),
 array([ 1, 43, 73, 62, 54,  2, 72, 67])]

...and this is the next character after each sequence.


In [40]:
y[:cs]


Out[40]:
array([ 1, 33,  2, 72, 67, 73,  2, 68])

In [41]:
n_fac = 42

Create and train model


In [43]:
def embedding_input(name, n_in, n_out):
    inp = Input(shape=(1,), dtype='int64', name=name+'_in')
    emb = Embedding(n_in, n_out, input_length=1, name=name+'_emb')(inp)
    return inp, Flatten()(emb)

In [44]:
c_ins = [embedding_input('c'+str(n), vocab_size, n_fac) for n in range(cs)]

In [45]:
n_hidden = 256

In [46]:
dense_in = Dense(n_hidden, activation='relu')
dense_hidden = Dense(n_hidden, activation='relu', init='identity')
dense_out = Dense(vocab_size, activation='softmax')

The first character of each sequence goes through dense_in(), to create our first hidden activations.


In [47]:
hidden = dense_in(c_ins[0][1])

Then for each successive layer we combine the output of dense_in() on the next character with the output of dense_hidden() on the current hidden state, to create the new hidden state.


In [48]:
for i in range(1,cs):
    c_dense = dense_in(c_ins[i][1])
    hidden = dense_hidden(hidden)
    hidden = merge([c_dense, hidden])

Putting the final hidden state through dense_out() gives us our output.


In [49]:
c_out = dense_out(hidden)

So now we can create our model.


In [50]:
model = Model([c[0] for c in c_ins], c_out)
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

In [51]:
model.fit(xs, y, batch_size=64, nb_epoch=12)


Epoch 1/12
75110/75110 [==============================] - 10s - loss: 2.5342    
Epoch 2/12
75110/75110 [==============================] - 10s - loss: 2.2569    
Epoch 3/12
75110/75110 [==============================] - 10s - loss: 2.1572    
Epoch 4/12
75110/75110 [==============================] - 10s - loss: 2.0869    
Epoch 5/12
75110/75110 [==============================] - 10s - loss: 2.0304    
Epoch 6/12
75110/75110 [==============================] - 10s - loss: 1.9837    
Epoch 7/12
75110/75110 [==============================] - 10s - loss: 1.9453    
Epoch 8/12
75110/75110 [==============================] - 9s - loss: 1.9078     
Epoch 9/12
75110/75110 [==============================] - 9s - loss: 1.8754     
Epoch 10/12
75110/75110 [==============================] - 10s - loss: 1.8459    
Epoch 11/12
75110/75110 [==============================] - 10s - loss: 1.8198    
Epoch 12/12
75110/75110 [==============================] - 10s - loss: 1.7971    
Out[51]:
<keras.callbacks.History at 0x7fc411cdf9d0>

Test model


In [52]:
def get_next(inp):
    idxs = [np.array(char_indices[c])[np.newaxis] for c in inp]
    p = model.predict(idxs)
    return chars[np.argmax(p)]

In [53]:
get_next('for thos')


Out[53]:
' '

In [54]:
get_next('part of ')


Out[54]:
't'

In [55]:
get_next('queens a')


Out[55]:
'n'

In [57]:
model.save_weights(model_path+'model2.h5')

In [59]:
model.load_weights(model_path+'model2.h5')

Our first RNN with keras!


In [17]:
n_hidden, n_fac, cs, vocab_size = (256, 42, 8, 86)

This is nearly exactly equivalent to the RNN we built ourselves in the previous section.


In [62]:
model=Sequential([
        Embedding(vocab_size, n_fac, input_length=cs),
        SimpleRNN(n_hidden, activation='relu', inner_init='identity'),
        Dense(vocab_size, activation='softmax')
    ])

In [63]:
model.summary()


____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
embedding_5 (Embedding)          (None, 8, 42)         3612        embedding_input_1[0][0]          
____________________________________________________________________________________________________
simplernn_2 (SimpleRNN)          (None, 256)           76544       embedding_5[0][0]                
____________________________________________________________________________________________________
dense_8 (Dense)                  (None, 86)            22102       simplernn_2[0][0]                
====================================================================================================
Total params: 102258
____________________________________________________________________________________________________

In [64]:
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

In [74]:
model.fit(np.concatenate(xs,axis=1), y, batch_size=64, nb_epoch=8)


Epoch 1/8
75110/75110 [==============================] - 9s - loss: 2.7972     
Epoch 2/8
75110/75110 [==============================] - 9s - loss: 2.2868     
Epoch 3/8
75110/75110 [==============================] - 9s - loss: 2.0746     
Epoch 4/8
75110/75110 [==============================] - 9s - loss: 1.9390     
Epoch 5/8
75110/75110 [==============================] - 9s - loss: 1.8342     
Epoch 6/8
75110/75110 [==============================] - 10s - loss: 1.7492    
Epoch 7/8
75110/75110 [==============================] - 9s - loss: 1.6854     
Epoch 8/8
75110/75110 [==============================] - 10s - loss: 1.6295    
Out[74]:
<keras.callbacks.History at 0x7fc3f9fd11d0>

In [75]:
def get_next_keras(inp):
    idxs = [char_indices[c] for c in inp]
    arrs = np.array(idxs)[np.newaxis,:]
    p = model.predict(arrs)[0]
    return chars[np.argmax(p)]

In [76]:
get_next_keras('this is ')


Out[76]:
't'

In [77]:
get_next_keras('part of ')


Out[77]:
't'

In [78]:
get_next_keras('queens a')


Out[78]:
'n'

In [79]:
model.save_weights(model_path+'model3.h5')

In [80]:
model.load_weights(model_path+'model3.h5')

Returning sequences

Create inputs

To use a sequence model, we can leave our input unchanged - but we have to change our output to a sequence (of course!)

Here, c_out_dat is identical to c_in_dat, but moved across 1 character.


In [33]:
#c_in_dat = [[idx[i+n] for i in xrange(0, len(idx)-1-cs, cs)]
#            for n in range(cs)]
c_out_dat = [[idx[i+n] for i in xrange(1, len(idx)-cs, cs)]
             for n in range(cs)]

In [34]:
ys = [np.stack(c[:-2]) for c in c_out_dat]

In [116]:
len(ys), ys[0].shape


Out[116]:
(8, (75110,))

Reading down each column shows one set of inputs and outputs.


In [81]:
[xs[n][:cs] for n in range(cs)]


Out[81]:
[array([40,  1, 33,  2, 72, 67, 73,  2]),
 array([42,  1, 38, 44,  2,  9, 61, 73]),
 array([29, 43, 31, 71, 54,  9, 58, 61]),
 array([30, 45,  2, 74,  2, 76, 67, 58]),
 array([25, 40, 73, 73, 76, 61, 24, 71]),
 array([27, 40, 61, 61, 68, 54,  2, 58]),
 array([29, 39, 54,  2, 66, 73, 33,  2]),
 array([ 1, 43, 73, 62, 54,  2, 72, 67])]

In [82]:
[ys[n][:cs] for n in range(cs)]


Out[82]:
[array([42,  1, 38, 44,  2,  9, 61, 73]),
 array([29, 43, 31, 71, 54,  9, 58, 61]),
 array([30, 45,  2, 74,  2, 76, 67, 58]),
 array([25, 40, 73, 73, 76, 61, 24, 71]),
 array([27, 40, 61, 61, 68, 54,  2, 58]),
 array([29, 39, 54,  2, 66, 73, 33,  2]),
 array([ 1, 43, 73, 62, 54,  2, 72, 67]),
 array([ 1, 33,  2, 72, 67, 73,  2, 68])]

Create and train model


In [83]:
dense_in = Dense(n_hidden, activation='relu')
dense_hidden = Dense(n_hidden, activation='relu', init='identity')
dense_out = Dense(vocab_size, activation='softmax', name='output')

We're going to pass a vector of all zeros as our starting point - here's our input layers for that:


In [84]:
inp1 = Input(shape=(n_fac,), name='zeros')
hidden = dense_in(inp1)

In [85]:
outs = []

for i in range(cs):
    c_dense = dense_in(c_ins[i][1])
    hidden = dense_hidden(hidden)
    hidden = merge([c_dense, hidden], mode='sum')
    # every layer now has an output
    outs.append(dense_out(hidden))

In [86]:
model = Model([inp1]+[c[0] for c in c_ins], outs)
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

In [87]:
zeros = np.tile(np.zeros(n_fac), (len(xs[0]),1))
zeros.shape


Out[87]:
(75110, 42)

In [88]:
model.fit([zeros]+xs, ys, batch_size=64, nb_epoch=12)


Epoch 1/12
75110/75110 [==============================] - 23s - loss: 19.2041 - output_loss_1: 2.6228 - output_loss_2: 2.4623 - output_loss_3: 2.3915 - output_loss_4: 2.3520 - output_loss_5: 2.3462 - output_loss_6: 2.3339 - output_loss_7: 2.3514 - output_loss_8: 2.3440    
Epoch 2/12
75110/75110 [==============================] - 23s - loss: 17.4681 - output_loss_1: 2.4925 - output_loss_2: 2.3268 - output_loss_3: 2.1932 - output_loss_4: 2.1161 - output_loss_5: 2.0960 - output_loss_6: 2.0785 - output_loss_7: 2.0919 - output_loss_8: 2.0732    
Epoch 3/12
75110/75110 [==============================] - 24s - loss: 16.9694 - output_loss_1: 2.4863 - output_loss_2: 2.3188 - output_loss_3: 2.1474 - output_loss_4: 2.0445 - output_loss_5: 2.0100 - output_loss_6: 1.9860 - output_loss_7: 1.9986 - output_loss_8: 1.9779    
Epoch 4/12
75110/75110 [==============================] - 23s - loss: 16.6578 - output_loss_1: 2.4832 - output_loss_2: 2.3139 - output_loss_3: 2.1240 - output_loss_4: 2.0018 - output_loss_5: 1.9564 - output_loss_6: 1.9244 - output_loss_7: 1.9380 - output_loss_8: 1.9161    
Epoch 5/12
75110/75110 [==============================] - 23s - loss: 16.4354 - output_loss_1: 2.4811 - output_loss_2: 2.3109 - output_loss_3: 2.1095 - output_loss_4: 1.9712 - output_loss_5: 1.9145 - output_loss_6: 1.8824 - output_loss_7: 1.8946 - output_loss_8: 1.8711    
Epoch 6/12
75110/75110 [==============================] - 23s - loss: 16.2658 - output_loss_1: 2.4808 - output_loss_2: 2.3075 - output_loss_3: 2.0977 - output_loss_4: 1.9507 - output_loss_5: 1.8864 - output_loss_6: 1.8477 - output_loss_7: 1.8573 - output_loss_8: 1.8378    
Epoch 7/12
75110/75110 [==============================] - 23s - loss: 16.1327 - output_loss_1: 2.4784 - output_loss_2: 2.3066 - output_loss_3: 2.0917 - output_loss_4: 1.9317 - output_loss_5: 1.8623 - output_loss_6: 1.8216 - output_loss_7: 1.8315 - output_loss_8: 1.8088    
Epoch 8/12
75110/75110 [==============================] - 23s - loss: 16.0316 - output_loss_1: 2.4780 - output_loss_2: 2.3043 - output_loss_3: 2.0865 - output_loss_4: 1.9211 - output_loss_5: 1.8456 - output_loss_6: 1.7997 - output_loss_7: 1.8100 - output_loss_8: 1.7864    
Epoch 9/12
75110/75110 [==============================] - 23s - loss: 15.9440 - output_loss_1: 2.4781 - output_loss_2: 2.3046 - output_loss_3: 2.0803 - output_loss_4: 1.9098 - output_loss_5: 1.8301 - output_loss_6: 1.7827 - output_loss_7: 1.7904 - output_loss_8: 1.7680    
Epoch 10/12
75110/75110 [==============================] - 23s - loss: 15.8663 - output_loss_1: 2.4773 - output_loss_2: 2.3022 - output_loss_3: 2.0775 - output_loss_4: 1.8995 - output_loss_5: 1.8158 - output_loss_6: 1.7674 - output_loss_7: 1.7747 - output_loss_8: 1.7519    
Epoch 11/12
75110/75110 [==============================] - 23s - loss: 15.8062 - output_loss_1: 2.4764 - output_loss_2: 2.3020 - output_loss_3: 2.0748 - output_loss_4: 1.8910 - output_loss_5: 1.8060 - output_loss_6: 1.7551 - output_loss_7: 1.7623 - output_loss_8: 1.7387    
Epoch 12/12
75110/75110 [==============================] - 23s - loss: 15.7478 - output_loss_1: 2.4765 - output_loss_2: 2.2997 - output_loss_3: 2.0725 - output_loss_4: 1.8871 - output_loss_5: 1.7958 - output_loss_6: 1.7434 - output_loss_7: 1.7472 - output_loss_8: 1.7257    
Out[88]:
<keras.callbacks.History at 0x7f7a3620d790>

In [89]:
ys[0].shape


Out[89]:
(75110, 1)

Test model


In [90]:
def get_nexts(inp):
    idxs = [char_indices[c] for c in inp]
    arrs = [np.array(i)[np.newaxis] for i in idxs]
    p = model.predict([np.zeros(n_fac)[np.newaxis,:]] + arrs)
    print(list(inp))
    return [chars[np.argmax(o)] for o in p]

In [91]:
get_nexts(' this is')


[' ', 't', 'h', 'i', 's', ' ', 'i', 's']
Out[91]:
['t', 'h', 'e', 't', ' ', 'i', 'n', ' ']

In [92]:
get_nexts(' part of')


[' ', 'p', 'a', 'r', 't', ' ', 'o', 'f']
Out[92]:
['t', 'o', 'r', 't', ' ', 'o', 'f', ' ']

Sequence model with keras


In [117]:
n_hidden, n_fac, cs, vocab_size


Out[117]:
(256, 42, 8, 86)

To convert our previous keras model into a sequence model, simply add the 'return_sequences=True' parameter, and add TimeDistributed() around our dense layer.


In [94]:
model=Sequential([
        Embedding(vocab_size, n_fac, input_length=cs),
        SimpleRNN(n_hidden, activation='relu', inner_init='identity', return_sequences=True),
        TimeDistributed(Dense(vocab_size, activation='softmax'))
    ])

In [95]:
model.summary()


____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
embedding_5 (Embedding)          (None, 8, 42)         3612        embedding_input_2[0][0]          
____________________________________________________________________________________________________
simplernn_2 (SimpleRNN)          (None, 8, 256)        76544       embedding_5[0][0]                
____________________________________________________________________________________________________
timedistributed_2 (TimeDistribute(None, 8, 86)         22102       simplernn_2[0][0]                
====================================================================================================
Total params: 102258
____________________________________________________________________________________________________

In [96]:
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

In [118]:
xs[0].shape, ys[0].shape


Out[118]:
((75110,), (75110,))

In [119]:
x_rnn=np.stack(xs, axis=1)
y_rnn=np.atleast_3d(np.stack(ys, axis=1)) # only need to expand dims on ys if fit was not called, above

In [120]:
x_rnn.shape, y_rnn.shape


Out[120]:
((75110, 8), (75110, 8, 1))

In [121]:
model.fit(x_rnn, y_rnn, batch_size=64, nb_epoch=8)


Epoch 1/8
75110/75110 [==============================] - 13s - loss: 2.4338    
Epoch 2/8
75110/75110 [==============================] - 13s - loss: 2.0031    
Epoch 3/8
75110/75110 [==============================] - 13s - loss: 1.8850    
Epoch 4/8
75110/75110 [==============================] - 13s - loss: 1.8236    
Epoch 5/8
75110/75110 [==============================] - 13s - loss: 1.7855    
Epoch 6/8
75110/75110 [==============================] - 13s - loss: 1.7578    
Epoch 7/8
75110/75110 [==============================] - 13s - loss: 1.7383    
Epoch 8/8
75110/75110 [==============================] - 13s - loss: 1.7226    
Out[121]:
<keras.callbacks.History at 0x7f7a2c534590>

In [122]:
def get_nexts_keras(inp):
    idxs = [char_indices[c] for c in inp]
    arr = np.array(idxs)[np.newaxis,:]
    p = model.predict(arr)[0]
    print(list(inp))
    return [chars[np.argmax(o)] for o in p]

In [123]:
get_nexts_keras(' this is')


[' ', 't', 'h', 'i', 's', ' ', 'i', 's']
Out[123]:
['t', 'h', 'e', 's', ' ', 't', 'n', ' ']

In [125]:
model.save_weights(model_path+'model5.h5')

In [126]:
model.load_weights(model_path+'model5.h5')

One-hot sequence model with keras

This is the keras version of the theano model that we're about to create.


In [127]:
model=Sequential([
        SimpleRNN(n_hidden, activation='relu', inner_init='identity',
                  input_shape=(cs, vocab_size), return_sequences=True),
        TimeDistributed(Dense(vocab_size, activation='softmax'))
    ])
model.compile(loss='categorical_crossentropy', optimizer=Adam())

In [35]:
oh_ys = [to_categorical(y, vocab_size) for y in ys]
oh_y_rnn=np.stack(oh_ys, axis=1)

oh_xs = [to_categorical(x, vocab_size) for x in xs]
oh_x_rnn=np.stack(oh_xs, axis=1)

oh_x_rnn.shape, oh_y_rnn.shape


Out[35]:
((75110, 8, 86), (75110, 8, 86))

In [129]:
model.fit(oh_x_rnn, oh_y_rnn, batch_size=64, nb_epoch=8)


Epoch 1/8
75110/75110 [==============================] - 12s - loss: 2.4483    
Epoch 2/8
75110/75110 [==============================] - 12s - loss: 2.0401    
Epoch 3/8
75110/75110 [==============================] - 12s - loss: 1.9232    
Epoch 4/8
75110/75110 [==============================] - 12s - loss: 1.8578    
Epoch 5/8
75110/75110 [==============================] - 12s - loss: 1.8148    
Epoch 6/8
75110/75110 [==============================] - 12s - loss: 1.7840    
Epoch 7/8
75110/75110 [==============================] - 12s - loss: 1.7601    
Epoch 8/8
75110/75110 [==============================] - 12s - loss: 1.7412    
Out[129]:
<keras.callbacks.History at 0x7f79c488b310>

In [91]:
def get_nexts_oh(inp):
    idxs = np.array([char_indices[c] for c in inp])
    arr = to_categorical(idxs, vocab_size)
    p = model.predict(arr[np.newaxis,:])[0]
    print(list(inp))
    return [chars[np.argmax(o)] for o in p]

In [131]:
get_nexts_oh(' this is')


[' ', 't', 'h', 'i', 's', ' ', 'i', 's']
Out[131]:
['a', 'h', 'e', 'n', ' ', 'c', 's', ' ']

In [132]:
model.save_weights(model_path+'model6.h5')

In [133]:
model.load_weights(model_path+'model6.h5')

Stateful model with keras


In [134]:
bs=64

A stateful model is easy to create (just add "stateful=True") but harder to train. We had to add batchnorm and use LSTM to get reasonable results.

When using stateful in keras, you have to also add 'batch_input_shape' to the first layer, and fix the batch size there.


In [136]:
model=Sequential([
        Embedding(vocab_size, n_fac, input_length=cs, batch_input_shape=(bs,cs)),
        BatchNormalization(),
        LSTM(n_hidden, activation='relu', return_sequences=True, stateful=True),
        TimeDistributed(Dense(vocab_size, activation='softmax'))
    ])

In [137]:
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

Since we're using a fixed batch shape, we have to ensure our inputs and outputs are a even multiple of the batch size.


In [138]:
mx = len(x_rnn)//bs*bs

In [139]:
model.fit(x_rnn[:mx], y_rnn[:mx], batch_size=bs, nb_epoch=4, shuffle=False)


Epoch 1/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 2/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 3/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 4/4
75072/75072 [==============================] - 36s - loss: nan    
Out[139]:
<keras.callbacks.History at 0x7f79baa1be90>

In [140]:
model.optimizer.lr=1e-4

In [141]:
model.fit(x_rnn[:mx], y_rnn[:mx], batch_size=bs, nb_epoch=4, shuffle=False)


Epoch 1/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 2/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 3/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 4/4
75072/75072 [==============================] - 36s - loss: nan    
Out[141]:
<keras.callbacks.History at 0x7f79baa1e090>

In [142]:
model.fit(x_rnn[:mx], y_rnn[:mx], batch_size=bs, nb_epoch=4, shuffle=False)


Epoch 1/4
75072/75072 [==============================] - 36s - loss: nan    
Epoch 2/4
75072/75072 [==============================] - 37s - loss: nan    
Epoch 3/4
75072/75072 [==============================] - 37s - loss: nan    
Epoch 4/4
75072/75072 [==============================] - 38s - loss: nan    
Out[142]:
<keras.callbacks.History at 0x7f79baa1ec90>

In [143]:
model.save_weights(model_path+'model7.h5')

In [144]:
model.load_weights(model_path+'model7.h5')

Theano RNN


In [14]:
n_input = vocab_size
n_output = vocab_size

Using raw theano, we have to create our weight matrices and bias vectors ourselves - here are the functions we'll use to do so (using glorot initialization).

The return values are wrapped in shared(), which is how we tell theano that it can manage this data (copying it to and from the GPU as necessary).


In [15]:
def init_wgts(rows, cols): 
    scale = math.sqrt(2/rows)
    return shared(normal(scale=scale, size=(rows, cols)).astype(np.float32))
def init_bias(rows): 
    return shared(np.zeros(rows, dtype=np.float32))

We return the weights and biases together as a tuple. For the hidden weights, we'll use an identity initialization (as recommended by Hinton.)


In [16]:
def wgts_and_bias(n_in, n_out): 
    return init_wgts(n_in, n_out), init_bias(n_out)
def id_and_bias(n): 
    return shared(np.eye(n, dtype=np.float32)), init_bias(n)

Theano doesn't actually do any computations until we explicitly compile and evaluate the function (at which point it'll be turned into CUDA code and sent off to the GPU). So our job is to describe the computations that we'll want theano to do - the first step is to tell theano what inputs we'll be providing to our computation:


In [38]:
t_inp = T.matrix('inp')
t_outp = T.matrix('outp')
t_h0 = T.vector('h0')
lr = T.scalar('lr')

all_args = [t_h0, t_inp, t_outp, lr]

Now we're ready to create our intial weight matrices.


In [39]:
W_h = id_and_bias(n_hidden)
W_x = wgts_and_bias(n_input, n_hidden)
W_y = wgts_and_bias(n_hidden, n_output)
w_all = list(chain.from_iterable([W_h, W_x, W_y]))

Theano handles looping by using the GPU scan operation. We have to tell theano what to do at each step through the scan - this is the function we'll use, which does a single forward pass for one character:


In [40]:
def step(x, h, W_h, b_h, W_x, b_x, W_y, b_y):
    # Calculate the hidden activations
    h = nnet.relu(T.dot(x, W_x) + b_x + T.dot(h, W_h) + b_h)
    # Calculate the output activations
    y = nnet.softmax(T.dot(h, W_y) + b_y)
    # Return both (the 'Flatten()' is to work around a theano bug)
    return h, T.flatten(y, 1)

Now we can provide everything necessary for the scan operation, so we can setup that up - we have to pass in the function to call at each step, the sequence to step through, the initial values of the outputs, and any other arguments to pass to the step function.


In [41]:
[v_h, v_y], _ = theano.scan(step, sequences=t_inp, outputs_info=[t_h0, None], non_sequences=w_all)

We can now calculate our loss function, and all of our gradients, with just a couple of lines of code!


In [42]:
error = nnet.categorical_crossentropy(v_y, t_outp).sum()
g_all = T.grad(error, w_all)

We even have to show theano how to do SGD - so we set up this dictionary of updates to complete after every forward pass, which apply to standard SGD update rule to every weight.


In [43]:
def upd_dict(wgts, grads, lr): 
    return OrderedDict({w: w-lr*g for (w,g) in zip(wgts,grads)})

upd = upd_dict(w_all, g_all, lr)

We're finally ready to compile the function!


In [44]:
fn = theano.function(all_args, error, updates=upd, allow_input_downcast=True)

In [45]:
X = oh_x_rnn
Y = oh_y_rnn
X.shape, Y.shape


Out[45]:
((75110, 8, 86), (75110, 8, 86))

To use it, we simply loop through our input data, calling the function compiled above, and printing our progress from time to time.


In [46]:
err=0.0; l_rate=0.01
for i in range(len(X)): 
    err+=fn(np.zeros(n_hidden), X[i], Y[i], l_rate)
    if i % 2000 == 1999: 
        print ("Error:{:.3f}".format(err/2000))
        err=0.0


Error:23.292
Error:20.391
Error:18.976
Error:18.785
Error:18.047
Error:17.571
Error:17.826
Error:17.200
Error:17.268
Error:16.721
Error:16.385
Error:16.371
Error:16.597
Error:16.102
Error:16.317
Error:16.483
Error:16.517
Error:16.272
Error:16.138
Error:16.138
Error:15.482
Error:15.812
Error:15.913
Error:15.802
Error:15.953
Error:15.394
Error:14.931
Error:15.434
Error:15.059
Error:15.004
Error:15.201
Error:15.180
Error:14.728
Error:14.483
Error:14.956
Error:14.943
Error:14.411

In [47]:
f_y = theano.function([t_h0, t_inp], v_y, allow_input_downcast=True)

In [48]:
pred = np.argmax(f_y(np.zeros(n_hidden), X[6]), axis=1)

In [49]:
act = np.argmax(X[6], axis=1)

In [50]:
[indices_char[o] for o in act]


Out[50]:
['t', 'h', 'e', 'n', '?', ' ', 'I', 's']

In [51]:
[indices_char[o] for o in pred]


Out[51]:
['h', 'e', ' ', ' ', ' ', 't', 's', ' ']

Pure python RNN!

Set up basic functions

Now we're going to try to repeat the above theano RNN, using just pure python (and numpy). Which means, we have to do everything ourselves, including defining the basic functions of a neural net! Below are all of the definitions, along with tests to check that they give the same answers as theano. The functions ending in _d are the derivatives of each function.


In [52]:
def sigmoid(x): return 1/(1+np.exp(-x))
def sigmoid_d(x): 
    output = sigmoid(x)
    return output * (1-output)

In [53]:
def relu(x): return np.maximum(0., x)
def relu_d(x): return (x > 0.)*1.

In [54]:
relu(np.array([3.,-3.])), relu_d(np.array([3.,-3.]))


Out[54]:
(array([ 3.,  0.]), array([ 1.,  0.]))

In [55]:
def dist(a,b): return pow(a-b,2)
def dist_d(a,b): return 2*(a-b)

In [56]:
import pdb

In [57]:
eps = 1e-7
def x_entropy(pred, actual): 
    return -np.sum(actual * np.log(np.clip(pred, eps, 1-eps)))
def x_entropy_d(pred, actual): return -actual/pred

In [58]:
def softmax(x): return np.exp(x)/np.exp(x).sum()

In [59]:
def softmax_d(x):
    sm = softmax(x)
    res = np.expand_dims(-sm,-1)*sm
    res[np.diag_indices_from(res)] = sm*(1-sm)
    return res

In [60]:
test_preds = np.array([0.2,0.7,0.1])
test_actuals = np.array([0.,1.,0.])
nnet.categorical_crossentropy(test_preds, test_actuals).eval()


Out[60]:
array(0.35667494393873245)

In [61]:
x_entropy(test_preds, test_actuals)


Out[61]:
0.35667494393873245

In [62]:
test_inp = T.dvector()
test_out = nnet.categorical_crossentropy(test_inp, test_actuals)
test_grad = theano.function([test_inp], T.grad(test_out, test_inp))

In [63]:
test_grad(test_preds)


Out[63]:
array([-0.    , -1.4286, -0.    ])

In [64]:
x_entropy_d(test_preds, test_actuals)


Out[64]:
array([-0.    , -1.4286, -0.    ])

In [65]:
pre_pred = random(oh_x_rnn[0][0].shape)
preds = softmax(pre_pred)
actual = oh_x_rnn[0][0]

In [67]:
np.allclose(softmax_d(pre_pred).dot(x_entropy_d(preds,actual)), preds-actual)


Out[67]:
True

In [68]:
softmax(test_preds)


Out[68]:
array([ 0.2814,  0.464 ,  0.2546])

In [69]:
nnet.softmax(test_preds).eval()


Out[69]:
array([[ 0.2814,  0.464 ,  0.2546]])

In [70]:
test_out = T.flatten(nnet.softmax(test_inp))

In [71]:
test_grad = theano.function([test_inp], theano.gradient.jacobian(test_out, test_inp))

In [72]:
test_grad(test_preds)


Out[72]:
array([[ 0.2022, -0.1306, -0.0717],
       [-0.1306,  0.2487, -0.1181],
       [-0.0717, -0.1181,  0.1898]])

In [73]:
softmax_d(test_preds)


Out[73]:
array([[ 0.2022, -0.1306, -0.0717],
       [-0.1306,  0.2487, -0.1181],
       [-0.0717, -0.1181,  0.1898]])

In [74]:
act=relu
act_d=relu_d

In [75]:
loss=x_entropy
loss_d=x_entropy_d

We also have to define our own scan function. Since we're not worrying about running things in parallel, it's very simple to implement:


In [76]:
def scan(fn, start, seq):
    res = []
    prev = start
    for s in seq:
        app = fn(prev, s)
        res.append(app)
        prev = app
    return res

...for instance, scan on + is the cumulative sum.


In [77]:
scan(lambda prev,curr: prev+curr, 0, range(5))


Out[77]:
[0, 1, 3, 6, 10]

Set up training

Let's now build the functions to do the forward and backward passes of our RNN. First, define our data and shape.


In [78]:
inp = oh_x_rnn
outp = oh_y_rnn
n_input = vocab_size
n_output = vocab_size

In [79]:
inp.shape, outp.shape


Out[79]:
((75110, 8, 86), (75110, 8, 86))

Here's the function to do a single forward pass of an RNN, for a single character.


In [85]:
def one_char(prev, item):
    # Previous state
    tot_loss, pre_hidden, pre_pred, hidden, ypred = prev
    # Current inputs and output
    x, y = item
    pre_hidden = np.dot(x, w_x) + np.dot(hidden, w_h)
    hidden = act(pre_hidden)
    pre_pred = np.dot(hidden, w_y)
    ypred = softmax(pre_pred)
    return (
        # Keep track of loss so we can report it
        tot_loss + loss(ypred, y),
        # Used in backprop
        pre_hidden, pre_pred, 
        # Used in next iteration
        hidden, 
        # To provide predictions
        ypred)

We use scan to apply the above to a whole sequence of characters.


In [81]:
def get_chars(n): return zip(inp[n], outp[n])
def one_fwd(n): return scan(one_char, (0,0,0,np.zeros(n_hidden),0), get_chars(n))

Now we can define the backward step. We use a loop to go through every element of the sequence. The derivatives are applying the chain rule to each step, and accumulating the gradients across the sequence.


In [86]:
# "Columnify" a vector
def col(x): return x[:,newaxis]

def one_bkwd(args, n):
    global w_x,w_y,w_h

    i=inp[n]  # 8x86
    o=outp[n] # 8x86
    d_pre_hidden = np.zeros(n_hidden) # 256
    for p in reversed(range(len(i))):
        totloss, pre_hidden, pre_pred, hidden, ypred = args[p]
        x=i[p] # 86
        y=o[p] # 86
        d_pre_pred = softmax_d(pre_pred).dot(loss_d(ypred, y))  # 86
        d_pre_hidden = act_d(pre_hidden) * (np.dot(d_pre_pred, w_y.T) + np.dot(d_pre_hidden, w_h.T)) # 256

        # d(loss)/d(w_y) = d(loss)/d(pre_pred) * d(pre_pred)/d(w_y)
        w_y -= col(hidden) * d_pre_pred * alpha
        # d(loss)/d(w_h) = d(loss)/d(pre_hidden[p-1]) * d(pre_hidden[p-1])/d(w_h)
        if (p>0): w_h -= args[p-1][3].dot(d_pre_hidden) * alpha
        w_x -= col(x) * d_pre_hidden * alpha
    return d_pre_hidden

Now we can set up our initial weight matrices. Note that we're not using bias at all in this example, in order to keep things simpler.


In [83]:
scale=math.sqrt(2./n_input)
w_x = normal(scale=scale, size=(n_input, n_hidden))
w_y = normal(scale=scale, size=(n_hidden, n_output))
w_h = np.eye(n_hidden, dtype=np.float32)

Our loop looks much like the theano loop in the previous section, except that we have to call the backwards step ourselves.


In [87]:
overallError=0
alpha=0.0001
for n in range(10000):
    res = one_fwd(n)
    overallError+=res[-1][0]
    deriv = one_bkwd(res, n)
    if(n % 1000 == 999):
        print ("Error:{:.4f}; Gradient:{:.5f}".format(
                overallError/1000, np.linalg.norm(deriv)))
        overallError=0


Error:35.8423; Gradient:1.99904
Error:35.5631; Gradient:2.23523
Error:35.0737; Gradient:4.19969
Error:33.1817; Gradient:3.40911
Error:31.0199; Gradient:3.46317
Error:30.1018; Gradient:3.92625
Error:29.0551; Gradient:4.36537
Error:28.4263; Gradient:3.01833
Error:27.8525; Gradient:3.78146
Error:27.8353; Gradient:3.24323

Keras GRU

Identical to the last keras rnn, but a GRU!


In [88]:
model=Sequential([
        GRU(n_hidden, return_sequences=True, input_shape=(cs, vocab_size),
                  activation='relu', inner_init='identity'),
        TimeDistributed(Dense(vocab_size, activation='softmax')),
    ])
model.compile(loss='categorical_crossentropy', optimizer=Adam())

In [89]:
model.fit(oh_x_rnn, oh_y_rnn, batch_size=64, nb_epoch=8)


Epoch 1/8
75110/75110 [==============================] - 128s - loss: 2.3898   
Epoch 2/8
75110/75110 [==============================] - 153s - loss: 1.9762   
Epoch 3/8
75110/75110 [==============================] - 176s - loss: 1.8642   
Epoch 4/8
75110/75110 [==============================] - 187s - loss: 1.8020   
Epoch 5/8
75110/75110 [==============================] - 187s - loss: 1.7617   
Epoch 6/8
75110/75110 [==============================] - 182s - loss: 1.7318   
Epoch 7/8
75110/75110 [==============================] - 191s - loss: 1.7091   
Epoch 8/8
75110/75110 [==============================] - 192s - loss: 1.6901   
Out[89]:
<keras.callbacks.History at 0x7f338b9dad90>

In [92]:
get_nexts_oh(' this is')


[' ', 't', 'h', 'i', 's', ' ', 'i', 's']
Out[92]:
['t', 'h', 'e', 's', ' ', 's', 's', ' ']

Theano GRU

Separate weights

The theano GRU looks just like the simple theano RNN, except for the use of the reset and update gates. Each of these gates requires its own hidden and input weights, so we add those to our weight matrices.


In [93]:
W_h = id_and_bias(n_hidden)
W_x = init_wgts(n_input, n_hidden)
W_y = wgts_and_bias(n_hidden, n_output)
rW_h = init_wgts(n_hidden, n_hidden)
rW_x = wgts_and_bias(n_input, n_hidden)
uW_h = init_wgts(n_hidden, n_hidden)
uW_x = wgts_and_bias(n_input, n_hidden)
w_all = list(chain.from_iterable([W_h, W_y, uW_x, rW_x]))
w_all.extend([W_x, uW_h, rW_h])

Here's the definition of a gate - it's just a sigmoid applied to the addition of the dot products of the input vectors.


In [94]:
def gate(x, h, W_h, W_x, b_x):
    return nnet.sigmoid(T.dot(x, W_x) + b_x + T.dot(h, W_h))

Our step is nearly identical to before, except that we multiply our hidden state by our reset gate, and we update our hidden state based on the update gate.


In [95]:
def step(x, h, W_h, b_h, W_y, b_y, uW_x, ub_x, rW_x, rb_x, W_x, uW_h, rW_h):
    reset = gate(x, h, rW_h, rW_x, rb_x)
    update = gate(x, h, uW_h, uW_x, ub_x)
    h_new = gate(x, h * reset, W_h, W_x, b_h)
    h = update*h + (1-update)*h_new
    y = nnet.softmax(T.dot(h, W_y) + b_y)
    return h, T.flatten(y, 1)

Everything from here on is identical to our simple RNN in theano.


In [96]:
[v_h, v_y], _ = theano.scan(step, sequences=t_inp, outputs_info=[t_h0, None], non_sequences=w_all)

In [97]:
error = nnet.categorical_crossentropy(v_y, t_outp).sum()
g_all = T.grad(error, w_all)

In [98]:
upd = upd_dict(w_all, g_all, lr)
fn = theano.function(all_args, error, updates=upd, allow_input_downcast=True)

In [99]:
err=0.0; l_rate=0.1
for i in range(len(X)): 
    err+=fn(np.zeros(n_hidden), X[i], Y[i], l_rate)
    if i % 3000 == 2999: 
        l_rate *= 0.95
        print ("Error:{:.2f}".format(err/3000))
        err=0.0


Error:24.01
Error:20.72
Error:19.84
Error:19.24
Error:18.89
Error:18.91
Error:17.89
Error:17.74
Error:17.62
Error:17.51
Error:17.73
Error:17.47
Error:17.27
Error:16.89
Error:16.98
Error:16.87
Error:16.78
Error:16.20
Error:16.36
Error:16.38
Error:16.25
Error:15.91
Error:15.91
Error:15.94
Error:15.55

Combined weights

We can make the previous section simpler and faster by concatenating the hidden and input matrices and inputs together. We're not going to step through this cell by cell - you'll see it's identical to the previous section except for this concatenation.


In [100]:
W = (shared(np.concatenate([np.eye(n_hidden), normal(size=(n_input, n_hidden))])
            .astype(np.float32)), init_bias(n_hidden))

rW = wgts_and_bias(n_input+n_hidden, n_hidden)
uW = wgts_and_bias(n_input+n_hidden, n_hidden)
W_y = wgts_and_bias(n_hidden, n_output)
w_all = list(chain.from_iterable([W, W_y, uW, rW]))

In [101]:
def gate(m, W, b): return nnet.sigmoid(T.dot(m, W) + b)

In [102]:
def step(x, h, W, b, W_y, b_y, uW, ub, rW, rb):
    m = T.concatenate([h, x])
    reset = gate(m, rW, rb)
    update = gate(m, uW, ub)
    m = T.concatenate([h*reset, x])
    h_new = gate(m, W, b)
    h = update*h + (1-update)*h_new
    y = nnet.softmax(T.dot(h, W_y) + b_y)
    return h, T.flatten(y, 1)

In [103]:
[v_h, v_y], _ = theano.scan(step, sequences=t_inp, outputs_info=[t_h0, None], non_sequences=w_all)

In [105]:
def upd_dict(wgts, grads, lr): 
    return OrderedDict({w: w-lr*g  for (w,g) in zip(wgts,grads)})

In [106]:
error = nnet.categorical_crossentropy(v_y, t_outp).sum()
g_all = T.grad(error, w_all)

In [107]:
upd = upd_dict(w_all, g_all, lr)
fn = theano.function(all_args, error, updates=upd, allow_input_downcast=True)

In [108]:
err=0.0; l_rate=0.01
for i in range(len(X)): 
    err+=fn(np.zeros(n_hidden), X[i], Y[i], l_rate)
    if i % 3000 == 2999: 
        print ("Error:{:.2f}".format(err/3000))
        err=0.0


Error:23.04
Error:20.95
Error:20.31
Error:19.86
Error:19.59
Error:19.75
Error:18.74
Error:18.66
Error:18.51
Error:18.36
Error:18.57
Error:18.26
Error:18.05
Error:17.71
Error:17.79
Error:17.83
Error:17.52
Error:16.97
Error:17.15
Error:17.09
Error:16.93
Error:16.61
Error:16.59
Error:16.54
Error:16.17

End