Wayne Nixalo - 25 Jun 2017
RNN practice in Theano -- 2nd attempt
In [2]:
import os, sys
sys.path.insert(1, os.path.join('../utils'))
from utils import *
import theano
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))
In [4]:
chars = sorted(list(set(text)))
vocab_size = len(chars) + 1
print('total chars:', vocab_size)
In [5]:
chars.insert(0, '\0')
''.join(chars[1:-6])
Out[5]:
In [11]:
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))
In [12]:
idx = [char_indices[c] for c in text]
idx[:10]
Out[12]:
In [13]:
''.join(indices_char[i] for i in idx[:70])
Out[13]:
In [19]:
n_hidden, n_fac, cs, vocab_size = (256, 42, 8, 86)
In [20]:
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+cs] for i in xrange(0, len(idx) - 1 - cs, cs)]
c_out_dat = [[idx[i+n] for i in xrange(1, len(idx) - cs, cs)] for n in range(cs)]
xs = [np.stack(c[:-2]) for c in c_in_dat]
# y = np.stack(c_out_dat[:-2])
ys = [np.stack(c[:-2]) for c in c_out_dat]
In [51]:
# [xs[n][:cs] for n in range(cs)]
xs[0].shape
xs = xs.expand_dims()
Out[51]:
In [21]:
[xs[n][:cs] for n in range(cs)]
Out[21]:
In [22]:
[ys[n][:cs] for n in range(cs)]
Out[22]:
In [24]:
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[24]:
In [25]:
# THEANO RNN
In [26]:
n_input = vocab_size
n_output = vocab_size
In [27]:
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))
In [28]:
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)
In [29]:
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]
In [30]:
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]))
In [31]:
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)
In [32]:
[v_h, v_y], _ = theano.scan(step, sequences=t_inp,
outputs_info=[t_h0, None], non_sequences=w_all)
In [34]:
error = nnet.categorical_crossentropy(v_y, t_outp).sum()
g_all = T.grad(error, w_all)
In [36]:
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)
In [37]:
fn = theano.function(all_args, error, updates=upd, allow_input_downcast=True)
X = oh_x_rnn
Y = oh_y_rnn
X.shape, Y.shape
Out[37]:
In [40]:
err=0.0; l_rate=0.01
for i in xrange(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
In [41]:
f_y = theano.function([t_h0, t_inp], v_y, allow_input_downcast=True)
In [42]:
pred = np.argmax(f_y(np.zeros(n_hidden), X[6]), axis=1)
act = np.argmax(X[6], axis=1)
In [43]:
[indices_char[o] for o in act]
Out[43]:
In [44]:
[indices_char[o] for o in pred]
Out[44]:
In [ ]:
In [ ]: