In [1]:
from theano.sandbox import cuda


WARNING (theano.sandbox.cuda): The cuda backend is deprecated and will be removed in the next release (v0.10).  Please switch to the gpuarray backend. You can get more information about how to switch at this URL:
 https://github.com/Theano/Theano/wiki/Converting-to-the-new-gpu-back-end%28gpuarray%29

Using gpu device 0: Tesla K80 (CNMeM is disabled, cuDNN 5103)

In [2]:
%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 [3]:
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 [4]:
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 [5]:
chars.insert(0, "\0")

In [6]:
''.join(chars[1:-6])


Out[6]:
'\n !"\'(),-.0123456789:;=?ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz'

Map from chars to indices and back again


In [7]:
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 [8]:
idx = [char_indices[c] for c in text]

In [9]:
idx[:10]


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

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


Out[10]:
'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 [11]:
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)]

Our inputs


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

Our output


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

The first 4 inputs and outputs


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


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

In [15]:
y[:4]


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

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


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

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


In [17]:
n_fac = 42

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


In [18]:
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 [19]:
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 [20]:
n_hidden = 256

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


In [21]:
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 [22]:
c1_hidden = dense_in(c1)

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


In [23]:
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 [24]:
c2_dense = dense_in(c2)
hidden_2 = dense_hidden(c1_hidden)
c2_hidden = merge([c2_dense, hidden_2])

In [25]:
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 [26]:
dense_out = Dense(vocab_size, activation='softmax')

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


In [27]:
c4_out = dense_out(c3_hidden)

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

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

In [30]:
model.optimizer.lr=0.000001

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


Epoch 1/4
12s - loss: 4.4146
Epoch 2/4
12s - loss: 4.2851
Epoch 3/4
12s - loss: 4.0075
Epoch 4/4
12s - loss: 3.5996
Out[31]:
<keras.callbacks.History at 0x7fb43e48f750>

In [32]:
model.optimizer.lr=0.01

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


Epoch 1/4
12s - loss: 3.2944
Epoch 2/4
12s - loss: 3.1779
Epoch 3/4
12s - loss: 3.1352
Epoch 4/4
12s - loss: 3.1143
Out[33]:
<keras.callbacks.History at 0x7fb440b5cdd0>

In [34]:
model.optimizer.lr = 0.000001

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


Epoch 1/4
12s - loss: 3.1012
Epoch 2/4
12s - loss: 3.0915
Epoch 3/4
12s - loss: 3.0836
Epoch 4/4
12s - loss: 3.0765
Out[35]:
<keras.callbacks.History at 0x7fb43e48f790>

In [36]:
model.optimizer.lr = 0.01

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


Epoch 1/4
12s - loss: 3.0698
Epoch 2/4
12s - loss: 3.0633
Epoch 3/4
12s - loss: 3.0567
Epoch 4/4
12s - loss: 3.0500
Out[37]:
<keras.callbacks.History at 0x7fb440b13c10>

Test model


In [38]:
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 [39]:
get_next('phi')


Out[39]:
' '

In [40]:
get_next(' th')


Out[40]:
' '

In [41]:
get_next(' an')


Out[41]:
' '

Our first RNN!

Create inputs

This is the size of our unrolled RNN.


In [42]:
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 [43]:
c_in_dat = [[idx[i+n] for i in xrange(0, len(idx)-1-cs, cs)]
            for n in range(cs)]

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


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

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

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


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

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

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


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


Out[48]:
[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 [49]:
y[:cs]


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

In [50]:
n_fac = 42

Create and train model


In [51]:
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 [52]:
c_ins = [embedding_input('c'+str(n), vocab_size, n_fac) for n in range(cs)]

In [53]:
n_hidden = 256

In [54]:
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 [55]:
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 [56]:
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 [57]:
c_out = dense_out(hidden)

So now we can create our model.


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

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


Epoch 1/12
10s - loss: 2.5388
Epoch 2/12
10s - loss: 2.2533
Epoch 3/12
10s - loss: 2.1468
Epoch 4/12
10s - loss: 2.0760
Epoch 5/12
10s - loss: 2.0197
Epoch 6/12
10s - loss: 1.9725
Epoch 7/12
10s - loss: 1.9325
Epoch 8/12
10s - loss: 1.8966
Epoch 9/12
10s - loss: 1.8619
Epoch 10/12
10s - loss: 1.8329
Epoch 11/12
10s - loss: 1.8037
Epoch 12/12
10s - loss: 1.7796
Out[59]:
<keras.callbacks.History at 0x7fb433505a50>

Test model


In [60]:
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 [61]:
get_next('for thos')


Out[61]:
'e'

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


Out[62]:
't'

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


Out[63]:
'n'

Our first RNN with keras!


In [64]:
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 [65]:
model=Sequential([
        Embedding(vocab_size, n_fac, input_length=cs),
        SimpleRNN(n_hidden, activation='relu', inner_init='identity'),
        Dense(vocab_size, activation='softmax')
    ])

In [66]:
model.summary()


____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
embedding_4 (Embedding)          (None, 8, 42)         3612        embedding_input_1[0][0]          
____________________________________________________________________________________________________
simplernn_1 (SimpleRNN)          (None, 256)           76544       embedding_4[0][0]                
____________________________________________________________________________________________________
dense_7 (Dense)                  (None, 86)            22102       simplernn_1[0][0]                
====================================================================================================
Total params: 102,258
Trainable params: 102,258
Non-trainable params: 0
____________________________________________________________________________________________________

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

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


Epoch 1/8
12s - loss: 2.8035
Epoch 2/8
12s - loss: 2.2948
Epoch 3/8
12s - loss: 2.0845
Epoch 4/8
12s - loss: 1.9439
Epoch 5/8
12s - loss: 1.8379
Epoch 6/8
12s - loss: 1.7573
Epoch 7/8
12s - loss: 1.6885
Epoch 8/8
12s - loss: 1.6349
Out[68]:
<keras.callbacks.History at 0x7fb42f58af10>

In [69]:
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 [70]:
get_next_keras('this is ')


Out[70]:
'a'

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


Out[71]:
't'

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


Out[72]:
'n'

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 [73]:
#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 [74]:
ys = [np.stack(c[:-2]) for c in c_out_dat]

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


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


Out[75]:
[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 [76]:
[ys[n][:cs] for n in range(cs)]


Out[76]:
[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 [77]:
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 [78]:
inp1 = Input(shape=(n_fac,), name='zeros')
hidden = dense_in(inp1)

In [79]:
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 [80]:
model = Model([inp1] + [c[0] for c in c_ins], outs)
model.compile(loss='sparse_categorical_crossentropy', optimizer=Adam())

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


Out[81]:
(75110, 42)

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


Epoch 1/12
22s - loss: 20.0904 - output_loss_1: 2.7094 - output_loss_2: 2.5635 - output_loss_3: 2.5122 - output_loss_4: 2.4717 - output_loss_5: 2.4649 - output_loss_6: 2.4537 - output_loss_7: 2.4681 - output_loss_8: 2.4470
Epoch 2/12
22s - loss: 17.8345 - output_loss_1: 2.5111 - output_loss_2: 2.3551 - output_loss_3: 2.2344 - output_loss_4: 2.1679 - output_loss_5: 2.1522 - output_loss_6: 2.1358 - output_loss_7: 2.1531 - output_loss_8: 2.1249
Epoch 3/12
22s - loss: 17.2056 - output_loss_1: 2.4970 - output_loss_2: 2.3299 - output_loss_3: 2.1720 - output_loss_4: 2.0777 - output_loss_5: 2.0476 - output_loss_6: 2.0256 - output_loss_7: 2.0398 - output_loss_8: 2.0160
Epoch 4/12
22s - loss: 16.8362 - output_loss_1: 2.4905 - output_loss_2: 2.3216 - output_loss_3: 2.1432 - output_loss_4: 2.0265 - output_loss_5: 1.9842 - output_loss_6: 1.9553 - output_loss_7: 1.9680 - output_loss_8: 1.9469
Epoch 5/12
22s - loss: 16.5987 - output_loss_1: 2.4864 - output_loss_2: 2.3171 - output_loss_3: 2.1270 - output_loss_4: 1.9941 - output_loss_5: 1.9426 - output_loss_6: 1.9091 - output_loss_7: 1.9226 - output_loss_8: 1.8999
Epoch 6/12
22s - loss: 16.4178 - output_loss_1: 2.4839 - output_loss_2: 2.3131 - output_loss_3: 2.1137 - output_loss_4: 1.9702 - output_loss_5: 1.9125 - output_loss_6: 1.8754 - output_loss_7: 1.8856 - output_loss_8: 1.8635
Epoch 7/12
22s - loss: 16.2815 - output_loss_1: 2.4824 - output_loss_2: 2.3104 - output_loss_3: 2.1059 - output_loss_4: 1.9520 - output_loss_5: 1.8885 - output_loss_6: 1.8473 - output_loss_7: 1.8588 - output_loss_8: 1.8362
Epoch 8/12
22s - loss: 16.1695 - output_loss_1: 2.4806 - output_loss_2: 2.3088 - output_loss_3: 2.0973 - output_loss_4: 1.9364 - output_loss_5: 1.8719 - output_loss_6: 1.8259 - output_loss_7: 1.8362 - output_loss_8: 1.8125
Epoch 9/12
22s - loss: 16.0723 - output_loss_1: 2.4797 - output_loss_2: 2.3065 - output_loss_3: 2.0909 - output_loss_4: 1.9262 - output_loss_5: 1.8545 - output_loss_6: 1.8072 - output_loss_7: 1.8170 - output_loss_8: 1.7902
Epoch 10/12
22s - loss: 15.9918 - output_loss_1: 2.4784 - output_loss_2: 2.3043 - output_loss_3: 2.0869 - output_loss_4: 1.9145 - output_loss_5: 1.8426 - output_loss_6: 1.7902 - output_loss_7: 1.8004 - output_loss_8: 1.7745
Epoch 11/12
22s - loss: 15.9244 - output_loss_1: 2.4779 - output_loss_2: 2.3029 - output_loss_3: 2.0834 - output_loss_4: 1.9073 - output_loss_5: 1.8305 - output_loss_6: 1.7770 - output_loss_7: 1.7859 - output_loss_8: 1.7595
Epoch 12/12
22s - loss: 15.8615 - output_loss_1: 2.4776 - output_loss_2: 2.3020 - output_loss_3: 2.0784 - output_loss_4: 1.9006 - output_loss_5: 1.8194 - output_loss_6: 1.7652 - output_loss_7: 1.7733 - output_loss_8: 1.7449
Out[82]:
<keras.callbacks.History at 0x7fb42a0c7050>

Test model


In [83]:
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 [84]:
get_nexts(' this is')


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

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


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

Sequence model with keras


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


Out[86]:
(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 [87]:
model=Sequential([
        Embedding(vocab_size, n_fac, input_length=cs),
        SimpleRNN(n_hidden, return_sequences=True, activation='relu', inner_init='identity'),
        TimeDistributed(Dense(vocab_size, activation='softmax')),
    ])

In [88]:
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_1 (TimeDistribut (None, 8, 86)         22102       simplernn_2[0][0]                
====================================================================================================
Total params: 102,258
Trainable params: 102,258
Non-trainable params: 0
____________________________________________________________________________________________________

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

In [90]:
xs[0].shape


Out[90]:
(75110, 1)

In [91]:
x_rnn=np.stack(xs, axis=1)
y_rnn=np.expand_dims(np.stack(ys, axis=1), -1)

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


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

In [93]:
model.fit(x_rnn[:,:,0], y_rnn[:,:,0], batch_size=64, nb_epoch=8, verbose=2)


Epoch 1/8
15s - loss: 2.4386
Epoch 2/8
15s - loss: 2.0073
Epoch 3/8
15s - loss: 1.8899
Epoch 4/8
15s - loss: 1.8286
Epoch 5/8
15s - loss: 1.7899
Epoch 6/8
15s - loss: 1.7618
Epoch 7/8
15s - loss: 1.7418
Epoch 8/8
15s - loss: 1.7254
Out[93]:
<keras.callbacks.History at 0x7fb41e550ed0>

In [94]:
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 [95]:
get_nexts_keras(' this is')


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

One-hot sequence model with keras

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


In [96]:
model=Sequential([
        SimpleRNN(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 [97]:
oh_ys = [to_categorical(o, vocab_size) for o in ys]
oh_y_rnn=np.stack(oh_ys, axis=1)

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

oh_x_rnn.shape, oh_y_rnn.shape


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

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


Epoch 1/8
13s - loss: 2.4453
Epoch 2/8
13s - loss: 2.0391
Epoch 3/8
13s - loss: 1.9234
Epoch 4/8
13s - loss: 1.8588
Epoch 5/8
13s - loss: 1.8156
Epoch 6/8
13s - loss: 1.7854
Epoch 7/8
13s - loss: 1.7621
Epoch 8/8
13s - loss: 1.7430
Out[98]:
<keras.callbacks.History at 0x7fb3ba9a8bd0>

In [99]:
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 [100]:
get_nexts_oh(' this is')


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

Stateful model with keras


In [101]:
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 [102]:
model=Sequential([
        Embedding(vocab_size, n_fac, input_length=cs, batch_input_shape=(bs,8)),
        BatchNormalization(),
        LSTM(n_hidden, return_sequences=True, stateful=True),
        TimeDistributed(Dense(vocab_size, activation='softmax')),
    ])

In [103]:
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 [104]:
mx = len(x_rnn)//bs*bs

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


Epoch 1/4
43s - loss: 2.2223
Epoch 2/4
43s - loss: 1.9721
Epoch 3/4
43s - loss: 1.8972
Epoch 4/4
43s - loss: 1.8526
Out[105]:
<keras.callbacks.History at 0x7fb3ab617690>

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

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


Epoch 1/4
43s - loss: 1.8200
Epoch 2/4
43s - loss: 1.7941
Epoch 3/4
43s - loss: 1.7724
Epoch 4/4
43s - loss: 1.7537
Out[107]:
<keras.callbacks.History at 0x7fb3ba9a8c50>

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


Epoch 1/4
43s - loss: 1.7367
Epoch 2/4
43s - loss: 1.7215
Epoch 3/4
43s - loss: 1.7076
Epoch 4/4
43s - loss: 1.6946
Out[108]:
<keras.callbacks.History at 0x7fb3ba9a8fd0>

Theano RNN


In [109]:
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 [110]:
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 [111]:
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 [112]:
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 [113]:
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 [114]:
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 [115]:
[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 [116]:
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 [117]:
def upd_dict(wgts, grads, lr): 
    return OrderedDict({w: w-g*lr for (w,g) in zip(wgts,grads)})

upd = upd_dict(w_all, g_all, lr)

We're finally ready to compile the function!


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

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


Out[119]:
((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 [120]:
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 % 1000 == 999: 
        print ("Error:{:.3f}".format(err/1000))
        err=0.0


Error:25.181
Error:21.484
Error:20.936
Error:19.936
Error:18.840
Error:19.284
Error:19.110
Error:18.500
Error:17.949
Error:18.270
Error:17.544
Error:17.656
Error:18.392
Error:17.321
Error:16.783
Error:17.770
Error:17.405
Error:17.216
Error:16.822
Error:16.728
Error:16.504
Error:16.342
Error:16.727
Error:16.130
Error:16.759
Error:16.564
Error:16.019
Error:16.206
Error:16.246
Error:16.453
Error:16.759
Error:16.386
Error:16.719
Error:16.279
Error:15.980
Error:16.678
Error:15.952
Error:16.324
Error:15.991
Error:16.384
Error:15.325
Error:15.693
Error:15.747
Error:15.979
Error:15.977
Error:15.842
Error:15.667
Error:16.105
Error:15.919
Error:16.044
Error:15.122
Error:15.587
Error:14.970
Error:14.792
Error:15.616
Error:15.334
Error:14.681
Error:15.442
Error:15.144
Error:14.981
Error:14.976
Error:15.398
Error:15.335
Error:15.062
Error:14.728
Error:14.789
Error:14.374
Error:14.737
Error:15.142
Error:14.788
Error:15.195
Error:14.711
Error:14.427
Error:14.443
Error:14.470

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

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

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

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


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

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


Out[125]:
['h', 'e', ' ', ' ', ' ', 't', 't', ' ']

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 [126]:
def sigmoid(x): return 1/(1+np.exp(-x))
def sigmoid_d(x): 
    output = sigmoid(x)
    return output*(1-output)

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

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


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

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

In [130]:
import pdb

In [131]:
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 [132]:
def softmax(x): return np.exp(x)/np.exp(x).sum()

In [133]:
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 [134]:
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[134]:
array(0.35667494393873245)

In [135]:
x_entropy(test_preds, test_actuals)


Out[135]:
0.35667494393873245

In [136]:
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 [137]:
test_grad(test_preds)


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

In [138]:
x_entropy_d(test_preds, test_actuals)


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

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

In [140]:
loss_d=x_entropy_d

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


Out[141]:
True

In [142]:
softmax(test_preds)


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

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


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

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

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

In [146]:
test_grad(test_preds)


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

In [147]:
softmax_d(test_preds)


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

In [148]:
act=relu
act_d = relu_d

In [149]:
loss=x_entropy

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 [150]:
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 [151]:
scan(lambda prev,curr: prev+curr, 0, range(5))


Out[151]:
[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 [152]:
inp = oh_x_rnn
outp = oh_y_rnn
n_input = vocab_size
n_output = vocab_size

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


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

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


In [154]:
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 [155]:
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 [156]:
# "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 = (np.dot(d_pre_hidden, w_h.T) 
                        + np.dot(d_pre_pred,w_y.T)) * act_d(pre_hidden) # 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 [157]:
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 [158]:
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.2945; Gradient:3.27527
Error:33.5225; Gradient:3.49585
Error:31.4018; Gradient:4.29564
Error:29.9376; Gradient:3.87430
Error:28.9982; Gradient:3.86819
Error:28.6904; Gradient:3.97141
Error:28.1034; Gradient:4.32484
Error:27.5712; Gradient:3.56074
Error:27.2230; Gradient:4.37731
Error:27.2548; Gradient:3.23591

Keras GRU

Identical to the last keras rnn, but a GRU!


In [159]:
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 [160]:
model.fit(oh_x_rnn, oh_y_rnn, batch_size=64, nb_epoch=8, verbose=2)


Epoch 1/8
30s - loss: 2.3750
Epoch 2/8
30s - loss: 1.9665
Epoch 3/8
30s - loss: 1.8623
Epoch 4/8
30s - loss: 1.8032
Epoch 5/8
30s - loss: 1.7633
Epoch 6/8
30s - loss: 1.7331
Epoch 7/8
30s - loss: 1.7101
Epoch 8/8
30s - loss: 1.6911
Out[160]:
<keras.callbacks.History at 0x7fb395c7b690>

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


[' ', 't', 'h', 'i', 's', ' ', 'i', 's']
Out[161]:
['t', 'h', 'e', 's', ' ', 'a', '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 [162]:
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 [163]:
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 [164]:
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 [165]:
[v_h, v_y], _ = theano.scan(step, sequences=t_inp, 
                            outputs_info=[t_h0, None], non_sequences=w_all)

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

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

In [168]:
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 % 1000 == 999: 
        l_rate *= 0.95
        print ("Error:{:.2f}".format(err/1000))
        err=0.0


Error:27.09
Error:22.60
Error:22.06
Error:21.16
Error:20.28
Error:20.62
Error:20.34
Error:19.73
Error:19.49
Error:19.77
Error:19.01
Error:19.08
Error:19.69
Error:18.88
Error:18.27
Error:19.45
Error:19.19
Error:18.88
Error:18.27
Error:18.10
Error:17.81
Error:17.83
Error:18.31
Error:17.86
Error:18.10
Error:17.94
Error:17.73
Error:17.75
Error:17.83
Error:17.98
Error:18.27
Error:17.88
Error:18.22
Error:17.75
Error:17.65
Error:18.21
Error:17.49
Error:18.05
Error:17.59
Error:17.72
Error:17.04
Error:17.43
Error:17.32
Error:17.68
Error:17.65
Error:17.73
Error:17.53
Error:18.94
Error:17.47
Error:17.73
Error:17.08
Error:17.44
Error:16.82
Error:16.98
Error:17.68
Error:17.39
Error:17.04
Error:17.44
Error:17.39
Error:17.22
Error:16.92
Error:17.36
Error:17.18
Error:17.18
Error:16.93
Error:16.93
Error:16.81
Error:16.82
Error:17.43
Error:16.83
Error:17.34
Error:16.87
Error:16.72
Error:16.63
Error:16.54

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 [169]:
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 [170]:
def gate(m, W, b): return nnet.sigmoid(T.dot(m, W) + b)

In [171]:
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 [172]:
[v_h, v_y], _ = theano.scan(step, sequences=t_inp, 
                            outputs_info=[t_h0, None], non_sequences=w_all)

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

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

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

In [176]:
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 % 1000 == 999: 
        print ("Error:{:.2f}".format(err/1000))
        err=0.0


Error:24.73
Error:22.16
Error:22.02
Error:21.29
Error:20.47
Error:21.01
Error:20.73
Error:20.18
Error:20.01
Error:20.33
Error:19.57
Error:19.70
Error:20.32
Error:19.55
Error:19.00
Error:19.98
Error:19.73
Error:19.59
Error:18.97
Error:18.85
Error:18.49
Error:18.53
Error:19.07
Error:18.47
Error:18.77
Error:18.54
Error:18.31
Error:18.36
Error:18.35
Error:18.49
Error:18.81
Error:18.36
Error:18.59
Error:18.29
Error:17.97
Error:18.55
Error:17.86
Error:18.39
Error:17.91
Error:18.05
Error:17.35
Error:17.78
Error:17.63
Error:17.98
Error:17.84
Error:17.91
Error:17.68
Error:17.91
Error:17.68
Error:17.82
Error:17.15
Error:17.38
Error:16.76
Error:16.85
Error:17.44
Error:17.25
Error:16.75
Error:17.32
Error:17.06
Error:16.93
Error:16.69
Error:17.14
Error:16.96
Error:16.75
Error:16.55
Error:16.56
Error:16.31
Error:16.47
Error:17.03
Error:16.47
Error:16.84
Error:16.36
Error:16.18
Error:16.17
Error:16.15

End