Anna KaRNNa

In this notebook, I'll build a character-wise RNN trained on Anna Karenina, one of my all-time favorite books. It'll be able to generate new text based on the text from the book.

This network is based off of Andrej Karpathy's post on RNNs and implementation in Torch. Also, some information here at r2rt and from Sherjil Ozair on GitHub. Below is the general architecture of the character-wise RNN.


In [1]:
import time
from collections import namedtuple

import numpy as np
import tensorflow as tf

First we'll load the text file and convert it into integers for our network to use.


In [2]:
with open('anna.txt', 'r') as f:
    text=f.read()
vocab = set(text)
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(vocab))
chars = np.array([vocab_to_int[c] for c in text], dtype=np.int32)

In [3]:
text[:100]


Out[3]:
'Chapter 1\n\n\nHappy families are all alike; every unhappy family is unhappy in its own\nway.\n\nEverythin'

In [4]:
chars[:100]


Out[4]:
array([57, 66, 81, 82, 23,  9, 73, 29, 54, 49, 49, 49, 78, 81, 82, 82, 63,
       29, 58, 81, 17, 50, 20, 50,  9, 53, 29, 81, 73,  9, 29, 81, 20, 20,
       29, 81, 20, 50, 76,  9, 35, 29,  9, 52,  9, 73, 63, 29,  2, 19, 66,
       81, 82, 82, 63, 29, 58, 81, 17, 50, 20, 63, 29, 50, 53, 29,  2, 19,
       66, 81, 82, 82, 63, 29, 50, 19, 29, 50, 23, 53, 29, 39, 24, 19, 49,
       24, 81, 63,  3, 49, 49, 55, 52,  9, 73, 63, 23, 66, 50, 19], dtype=int32)

Now I need to split up the data into batches, and into training and validation sets. I should be making a test set here, but I'm not going to worry about that. My test will be if the network can generate new text.

Here I'll make both input and target arrays. The targets are the same as the inputs, except shifted one character over. I'll also drop the last bit of data so that I'll only have completely full batches.

The idea here is to make a 2D matrix where the number of rows is equal to the number of batches. Each row will be one long concatenated string from the character data. We'll split this data into a training set and validation set using the split_frac keyword. This will keep 90% of the batches in the training set, the other 10% in the validation set.


In [5]:
def split_data(chars, batch_size, num_steps, split_frac=0.9):
    """ 
    Split character data into training and validation sets, inputs and targets for each set.
    
    Arguments
    ---------
    chars: character array
    batch_size: Size of examples in each of batch
    num_steps: Number of sequence steps to keep in the input and pass to the network
    split_frac: Fraction of batches to keep in the training set
    
    
    Returns train_x, train_y, val_x, val_y
    """
    
    slice_size = batch_size * num_steps
    n_batches = int(len(chars) / slice_size)
    
    # Drop the last few characters to make only full batches
    x = chars[: n_batches*slice_size]
    y = chars[1: n_batches*slice_size + 1]
    
    # Split the data into batch_size slices, then stack them into a 2D matrix 
    x = np.stack(np.split(x, batch_size))
    y = np.stack(np.split(y, batch_size))
    
    # Now x and y are arrays with dimensions batch_size x n_batches*num_steps
    
    # Split into training and validation sets, keep the virst split_frac batches for training
    split_idx = int(n_batches*split_frac)
    train_x, train_y= x[:, :split_idx*num_steps], y[:, :split_idx*num_steps]
    val_x, val_y = x[:, split_idx*num_steps:], y[:, split_idx*num_steps:]
    
    return train_x, train_y, val_x, val_y

In [6]:
train_x, train_y, val_x, val_y = split_data(chars, 10, 200)

In [7]:
train_x.shape


Out[7]:
(10, 178400)

In [8]:
train_x[:,:10]


Out[8]:
array([[57, 66, 81, 82, 23,  9, 73, 29, 54, 49],
       [ 4, 19, 36, 29, 66,  9, 29, 17, 39, 52],
       [29, 68, 81, 23, 68, 66, 50, 19, 40, 29],
       [39, 23, 66,  9, 73, 29, 24, 39,  2, 20],
       [29, 23, 66,  9, 29, 20, 81, 19, 36, 25],
       [29, 30, 66, 73, 39,  2, 40, 66, 29, 20],
       [23, 29, 23, 39, 49, 36, 39,  3, 49, 49],
       [39, 29, 66,  9, 73, 53,  9, 20, 58, 12],
       [66, 81, 23, 29, 50, 53, 29, 23, 66,  9],
       [ 9, 73, 53,  9, 20, 58, 29, 81, 19, 36]], dtype=int32)

I'll write another function to grab batches out of the arrays made by split data. Here each batch will be a sliding window on these arrays with size batch_size X num_steps. For example, if we want our network to train on a sequence of 100 characters, num_steps = 100. For the next batch, we'll shift this window the next sequence of num_steps characters. In this way we can feed batches to the network and the cell states will continue through on each batch.


In [9]:
def get_batch(arrs, num_steps):
    batch_size, slice_size = arrs[0].shape
    
    n_batches = int(slice_size/num_steps)
    for b in range(n_batches):
        yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs]

In [10]:
def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2,
              learning_rate=0.001, grad_clip=5, sampling=False):
        
    if sampling == True:
        batch_size, num_steps = 1, 1

    tf.reset_default_graph()
    
    # Declare placeholders we'll feed into the graph
    with tf.name_scope('inputs'):
        inputs = tf.placeholder(tf.int32, [batch_size, num_steps], name='inputs')
        x_one_hot = tf.one_hot(inputs, num_classes, name='x_one_hot')
    
    with tf.name_scope('targets'):
        targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets')
        y_one_hot = tf.one_hot(targets, num_classes, name='y_one_hot')
        y_reshaped = tf.reshape(y_one_hot, [-1, num_classes])
    
    keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    
    # Build the RNN layers
    with tf.name_scope("RNN_cells"):
        lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size)
        drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
        cell = tf.contrib.rnn.MultiRNNCell([drop] * num_layers)
    
    with tf.name_scope("RNN_init_state"):
        initial_state = cell.zero_state(batch_size, tf.float32)

    # Run the data through the RNN layers
    with tf.name_scope("RNN_forward"):
        outputs, state = tf.nn.dynamic_rnn(cell, x_one_hot, initial_state=initial_state)
    
    final_state = state
    
    # Reshape output so it's a bunch of rows, one row for each cell output
    with tf.name_scope('sequence_reshape'):
        seq_output = tf.concat(outputs, axis=1,name='seq_output')
        output = tf.reshape(seq_output, [-1, lstm_size], name='graph_output')
    
    # Now connect the RNN outputs to a softmax layer and calculate the cost
    with tf.name_scope('logits'):
        softmax_w = tf.Variable(tf.truncated_normal((lstm_size, num_classes), stddev=0.1),
                               name='softmax_w')
        softmax_b = tf.Variable(tf.zeros(num_classes), name='softmax_b')
        logits = tf.matmul(output, softmax_w) + softmax_b
        tf.summary.histogram('softmax_w', softmax_w)
        tf.summary.histogram('softmax_b', softmax_b)

    with tf.name_scope('predictions'):
        preds = tf.nn.softmax(logits, name='predictions')
        tf.summary.histogram('predictions', preds)
    
    with tf.name_scope('cost'):
        loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped, name='loss')
        cost = tf.reduce_mean(loss, name='cost')
        tf.summary.scalar('cost', cost)

    # Optimizer for training, using gradient clipping to control exploding gradients
    with tf.name_scope('train'):
        tvars = tf.trainable_variables()
        grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), grad_clip)
        train_op = tf.train.AdamOptimizer(learning_rate)
        optimizer = train_op.apply_gradients(zip(grads, tvars))
    
    merged = tf.summary.merge_all()
    
    # Export the nodes 
    export_nodes = ['inputs', 'targets', 'initial_state', 'final_state',
                    'keep_prob', 'cost', 'preds', 'optimizer', 'merged']
    Graph = namedtuple('Graph', export_nodes)
    local_dict = locals()
    graph = Graph(*[local_dict[each] for each in export_nodes])
    
    return graph

Hyperparameters

Here I'm defining the hyperparameters for the network. The two you probably haven't seen before are lstm_size and num_layers. These set the number of hidden units in the LSTM layers and the number of LSTM layers, respectively. Of course, making these bigger will improve the network's performance but you'll have to watch out for overfitting. If your validation loss is much larger than the training loss, you're probably overfitting. Decrease the size of the network or decrease the dropout keep probability.


In [11]:
batch_size = 100
num_steps = 100
lstm_size = 512
num_layers = 2
learning_rate = 0.001

Training

Time for training which is is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by save_every_n) I calculate the validation loss and save a checkpoint.


In [13]:
!mkdir -p checkpoints/anna

In [12]:
epochs = 1
save_every_n = 100
train_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps)

model = build_rnn(len(vocab), 
                  batch_size=batch_size,
                  num_steps=num_steps,
                  learning_rate=learning_rate,
                  lstm_size=lstm_size,
                  num_layers=num_layers)

saver = tf.train.Saver(max_to_keep=100)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter('./logs/2/train', sess.graph)
    test_writer = tf.summary.FileWriter('./logs/2/test')
    
    # Use the line below to load a checkpoint and resume training
    #saver.restore(sess, 'checkpoints/anna20.ckpt')
    
    n_batches = int(train_x.shape[1]/num_steps)
    iterations = n_batches * epochs
    for e in range(epochs):
        
        # Train network
        new_state = sess.run(model.initial_state)
        loss = 0
        for b, (x, y) in enumerate(get_batch([train_x, train_y], num_steps), 1):
            iteration = e*n_batches + b
            start = time.time()
            feed = {model.inputs: x,
                    model.targets: y,
                    model.keep_prob: 0.5,
                    model.initial_state: new_state}
            summary, batch_loss, new_state, _ = sess.run([model.merged, model.cost, 
                                                          model.final_state, model.optimizer], 
                                                          feed_dict=feed)
            loss += batch_loss
            end = time.time()
            print('Epoch {}/{} '.format(e+1, epochs),
                  'Iteration {}/{}'.format(iteration, iterations),
                  'Training loss: {:.4f}'.format(loss/b),
                  '{:.4f} sec/batch'.format((end-start)))
            
            train_writer.add_summary(summary, iteration)
        
            if (iteration%save_every_n == 0) or (iteration == iterations):
                # Check performance, notice dropout has been set to 1
                val_loss = []
                new_state = sess.run(model.initial_state)
                for x, y in get_batch([val_x, val_y], num_steps):
                    feed = {model.inputs: x,
                            model.targets: y,
                            model.keep_prob: 1.,
                            model.initial_state: new_state}
                    summary, batch_loss, new_state = sess.run([model.merged, model.cost, 
                                                               model.final_state], feed_dict=feed)
                    val_loss.append(batch_loss)
                    
                test_writer.add_summary(summary, iteration)

                print('Validation loss:', np.mean(val_loss),
                      'Saving checkpoint!')
                #saver.save(sess, "checkpoints/anna/i{}_l{}_{:.3f}.ckpt".format(iteration, lstm_size, np.mean(val_loss)))


Epoch 1/1  Iteration 1/178 Training loss: 4.4198 11.5354 sec/batch
Epoch 1/1  Iteration 2/178 Training loss: 4.3826 8.3374 sec/batch
Epoch 1/1  Iteration 3/178 Training loss: 4.2481 8.5395 sec/batch
Epoch 1/1  Iteration 4/178 Training loss: 4.3465 7.5775 sec/batch
Epoch 1/1  Iteration 5/178 Training loss: 4.2729 7.3166 sec/batch
Epoch 1/1  Iteration 6/178 Training loss: 4.1915 7.3668 sec/batch
Epoch 1/1  Iteration 7/178 Training loss: 4.1124 7.2087 sec/batch
Epoch 1/1  Iteration 8/178 Training loss: 4.0374 7.1824 sec/batch
Epoch 1/1  Iteration 9/178 Training loss: 3.9707 7.4702 sec/batch
Epoch 1/1  Iteration 10/178 Training loss: 3.9170 7.3250 sec/batch
Epoch 1/1  Iteration 11/178 Training loss: 3.8704 7.2780 sec/batch
Epoch 1/1  Iteration 12/178 Training loss: 3.8296 7.4336 sec/batch
Epoch 1/1  Iteration 13/178 Training loss: 3.7920 7.4949 sec/batch
Epoch 1/1  Iteration 14/178 Training loss: 3.7588 8.2660 sec/batch
Epoch 1/1  Iteration 15/178 Training loss: 3.7295 7.3540 sec/batch
Epoch 1/1  Iteration 16/178 Training loss: 3.7025 7.8501 sec/batch
Epoch 1/1  Iteration 17/178 Training loss: 3.6776 7.5903 sec/batch
Epoch 1/1  Iteration 18/178 Training loss: 3.6569 8.0996 sec/batch
Epoch 1/1  Iteration 19/178 Training loss: 3.6371 8.2190 sec/batch
Epoch 1/1  Iteration 20/178 Training loss: 3.6172 8.0856 sec/batch
Epoch 1/1  Iteration 21/178 Training loss: 3.5997 8.1649 sec/batch
Epoch 1/1  Iteration 22/178 Training loss: 3.5839 11.0317 sec/batch
Epoch 1/1  Iteration 23/178 Training loss: 3.5680 7.0590 sec/batch
Epoch 1/1  Iteration 24/178 Training loss: 3.5543 6.6502 sec/batch
Epoch 1/1  Iteration 25/178 Training loss: 3.5407 6.5945 sec/batch
Epoch 1/1  Iteration 26/178 Training loss: 3.5286 6.5593 sec/batch
Epoch 1/1  Iteration 27/178 Training loss: 3.5175 6.4269 sec/batch
Epoch 1/1  Iteration 28/178 Training loss: 3.5058 7.1125 sec/batch
Epoch 1/1  Iteration 29/178 Training loss: 3.4954 7.5487 sec/batch
Epoch 1/1  Iteration 30/178 Training loss: 3.4858 7.4759 sec/batch
Epoch 1/1  Iteration 31/178 Training loss: 3.4773 7.5357 sec/batch
Epoch 1/1  Iteration 32/178 Training loss: 3.4683 7.4283 sec/batch
Epoch 1/1  Iteration 33/178 Training loss: 3.4596 7.2546 sec/batch
Epoch 1/1  Iteration 34/178 Training loss: 3.4521 6.8547 sec/batch
Epoch 1/1  Iteration 35/178 Training loss: 3.4442 6.8781 sec/batch
Epoch 1/1  Iteration 36/178 Training loss: 3.4373 6.7849 sec/batch
Epoch 1/1  Iteration 37/178 Training loss: 3.4300 6.8085 sec/batch
Epoch 1/1  Iteration 38/178 Training loss: 3.4231 6.8616 sec/batch
Epoch 1/1  Iteration 39/178 Training loss: 3.4163 7.1010 sec/batch
Epoch 1/1  Iteration 40/178 Training loss: 3.4100 6.8417 sec/batch
Epoch 1/1  Iteration 41/178 Training loss: 3.4039 7.4384 sec/batch
Epoch 1/1  Iteration 42/178 Training loss: 3.3980 9.0958 sec/batch
Epoch 1/1  Iteration 43/178 Training loss: 3.3924 6.9311 sec/batch
Epoch 1/1  Iteration 44/178 Training loss: 3.3869 6.7839 sec/batch
Epoch 1/1  Iteration 45/178 Training loss: 3.3815 7.3006 sec/batch
Epoch 1/1  Iteration 46/178 Training loss: 3.3767 6.8641 sec/batch
Epoch 1/1  Iteration 47/178 Training loss: 3.3720 6.1393 sec/batch
Epoch 1/1  Iteration 48/178 Training loss: 3.3678 6.7995 sec/batch
Epoch 1/1  Iteration 49/178 Training loss: 3.3636 6.9706 sec/batch
Epoch 1/1  Iteration 50/178 Training loss: 3.3595 6.8837 sec/batch
Epoch 1/1  Iteration 51/178 Training loss: 3.3555 6.7655 sec/batch
Epoch 1/1  Iteration 52/178 Training loss: 3.3514 6.7962 sec/batch
Epoch 1/1  Iteration 53/178 Training loss: 3.3477 6.7940 sec/batch
Epoch 1/1  Iteration 54/178 Training loss: 3.3437 6.8121 sec/batch
Epoch 1/1  Iteration 55/178 Training loss: 3.3402 6.8035 sec/batch
Epoch 1/1  Iteration 56/178 Training loss: 3.3364 6.8449 sec/batch
Epoch 1/1  Iteration 57/178 Training loss: 3.3329 6.9609 sec/batch
Epoch 1/1  Iteration 58/178 Training loss: 3.3295 6.9099 sec/batch
Epoch 1/1  Iteration 59/178 Training loss: 3.3261 6.8023 sec/batch
Epoch 1/1  Iteration 60/178 Training loss: 3.3229 6.8761 sec/batch
Epoch 1/1  Iteration 61/178 Training loss: 3.3198 6.8360 sec/batch
Epoch 1/1  Iteration 62/178 Training loss: 3.3171 6.7841 sec/batch
Epoch 1/1  Iteration 63/178 Training loss: 3.3144 6.9077 sec/batch
Epoch 1/1  Iteration 64/178 Training loss: 3.3113 6.8276 sec/batch
Epoch 1/1  Iteration 65/178 Training loss: 3.3083 6.8938 sec/batch
Epoch 1/1  Iteration 66/178 Training loss: 3.3058 7.6658 sec/batch
Epoch 1/1  Iteration 67/178 Training loss: 3.3032 7.1347 sec/batch
Epoch 1/1  Iteration 68/178 Training loss: 3.3000 6.8775 sec/batch
Epoch 1/1  Iteration 69/178 Training loss: 3.2972 6.8573 sec/batch
Epoch 1/1  Iteration 70/178 Training loss: 3.2947 6.8496 sec/batch
Epoch 1/1  Iteration 71/178 Training loss: 3.2920 6.8602 sec/batch
Epoch 1/1  Iteration 72/178 Training loss: 3.2898 6.9206 sec/batch
Epoch 1/1  Iteration 73/178 Training loss: 3.2873 6.9763 sec/batch
Epoch 1/1  Iteration 74/178 Training loss: 3.2849 6.9099 sec/batch
Epoch 1/1  Iteration 75/178 Training loss: 3.2826 6.9975 sec/batch
Epoch 1/1  Iteration 76/178 Training loss: 3.2804 7.0012 sec/batch
Epoch 1/1  Iteration 77/178 Training loss: 3.2782 6.9433 sec/batch
Epoch 1/1  Iteration 78/178 Training loss: 3.2759 8.6365 sec/batch
Epoch 1/1  Iteration 79/178 Training loss: 3.2735 7.7169 sec/batch
Epoch 1/1  Iteration 80/178 Training loss: 3.2711 6.8593 sec/batch
Epoch 1/1  Iteration 81/178 Training loss: 3.2688 6.8157 sec/batch
Epoch 1/1  Iteration 82/178 Training loss: 3.2666 7.1197 sec/batch
Epoch 1/1  Iteration 83/178 Training loss: 3.2646 6.9017 sec/batch
Epoch 1/1  Iteration 84/178 Training loss: 3.2626 6.8662 sec/batch
Epoch 1/1  Iteration 85/178 Training loss: 3.2605 7.1496 sec/batch
Epoch 1/1  Iteration 86/178 Training loss: 3.2586 6.7998 sec/batch
Epoch 1/1  Iteration 87/178 Training loss: 3.2566 6.8352 sec/batch
Epoch 1/1  Iteration 88/178 Training loss: 3.2545 7.0210 sec/batch
Epoch 1/1  Iteration 89/178 Training loss: 3.2526 6.9410 sec/batch
Epoch 1/1  Iteration 90/178 Training loss: 3.2508 6.8971 sec/batch
Epoch 1/1  Iteration 91/178 Training loss: 3.2490 6.7294 sec/batch
Epoch 1/1  Iteration 92/178 Training loss: 3.2471 7.4869 sec/batch
Epoch 1/1  Iteration 93/178 Training loss: 3.2451 6.8117 sec/batch
Epoch 1/1  Iteration 94/178 Training loss: 3.2433 6.8730 sec/batch
Epoch 1/1  Iteration 95/178 Training loss: 3.2413 8.2963 sec/batch
Epoch 1/1  Iteration 96/178 Training loss: 3.2393 7.4251 sec/batch
Epoch 1/1  Iteration 97/178 Training loss: 3.2375 9.7642 sec/batch
Epoch 1/1  Iteration 98/178 Training loss: 3.2355 6.3678 sec/batch
Epoch 1/1  Iteration 99/178 Training loss: 3.2335 7.4747 sec/batch
Epoch 1/1  Iteration 100/178 Training loss: 3.2315 8.0394 sec/batch
Validation loss: 2.98954 Saving checkpoint!
Epoch 1/1  Iteration 101/178 Training loss: 3.2296 6.6316 sec/batch
Epoch 1/1  Iteration 102/178 Training loss: 3.2276 8.9139 sec/batch
Epoch 1/1  Iteration 103/178 Training loss: 3.2256 8.2324 sec/batch
Epoch 1/1  Iteration 104/178 Training loss: 3.2237 6.9952 sec/batch
Epoch 1/1  Iteration 105/178 Training loss: 3.2217 6.6361 sec/batch
Epoch 1/1  Iteration 106/178 Training loss: 3.2197 7.6155 sec/batch
Epoch 1/1  Iteration 107/178 Training loss: 3.2177 6.9172 sec/batch
Epoch 1/1  Iteration 108/178 Training loss: 3.2157 6.6827 sec/batch
Epoch 1/1  Iteration 109/178 Training loss: 3.2138 7.1197 sec/batch
Epoch 1/1  Iteration 110/178 Training loss: 3.2114 6.8597 sec/batch
Epoch 1/1  Iteration 111/178 Training loss: 3.2093 6.5188 sec/batch
Epoch 1/1  Iteration 112/178 Training loss: 3.2072 6.3794 sec/batch
Epoch 1/1  Iteration 113/178 Training loss: 3.2049 6.2755 sec/batch
Epoch 1/1  Iteration 114/178 Training loss: 3.2026 6.3716 sec/batch
Epoch 1/1  Iteration 115/178 Training loss: 3.2001 9.0204 sec/batch
Epoch 1/1  Iteration 116/178 Training loss: 3.1976 8.2940 sec/batch
Epoch 1/1  Iteration 117/178 Training loss: 3.1951 6.5829 sec/batch
Epoch 1/1  Iteration 118/178 Training loss: 3.1927 6.2745 sec/batch
Epoch 1/1  Iteration 119/178 Training loss: 3.1904 6.2821 sec/batch
Epoch 1/1  Iteration 120/178 Training loss: 3.1880 6.2374 sec/batch
Epoch 1/1  Iteration 121/178 Training loss: 3.1858 6.2681 sec/batch
Epoch 1/1  Iteration 122/178 Training loss: 3.1834 6.3049 sec/batch
Epoch 1/1  Iteration 123/178 Training loss: 3.1809 6.2907 sec/batch
Epoch 1/1  Iteration 124/178 Training loss: 3.1785 6.4454 sec/batch
Epoch 1/1  Iteration 125/178 Training loss: 3.1759 6.5658 sec/batch
Epoch 1/1  Iteration 126/178 Training loss: 3.1732 6.4536 sec/batch
Epoch 1/1  Iteration 127/178 Training loss: 3.1706 6.3127 sec/batch
Epoch 1/1  Iteration 128/178 Training loss: 3.1680 6.4717 sec/batch
Epoch 1/1  Iteration 129/178 Training loss: 3.1652 6.3643 sec/batch
Epoch 1/1  Iteration 130/178 Training loss: 3.1624 6.3935 sec/batch
Epoch 1/1  Iteration 131/178 Training loss: 3.1596 6.6144 sec/batch
Epoch 1/1  Iteration 132/178 Training loss: 3.1567 6.7770 sec/batch
Epoch 1/1  Iteration 133/178 Training loss: 3.1542 6.5738 sec/batch
Epoch 1/1  Iteration 134/178 Training loss: 3.1519 6.5589 sec/batch
Epoch 1/1  Iteration 135/178 Training loss: 3.1493 7.2144 sec/batch
Epoch 1/1  Iteration 136/178 Training loss: 3.1465 6.7330 sec/batch
Epoch 1/1  Iteration 137/178 Training loss: 3.1439 6.7521 sec/batch
Epoch 1/1  Iteration 138/178 Training loss: 3.1412 6.6340 sec/batch
Epoch 1/1  Iteration 139/178 Training loss: 3.1387 6.5537 sec/batch
Epoch 1/1  Iteration 140/178 Training loss: 3.1361 6.5621 sec/batch
Epoch 1/1  Iteration 141/178 Training loss: 3.1333 6.5149 sec/batch
Epoch 1/1  Iteration 142/178 Training loss: 3.1304 6.3986 sec/batch
Epoch 1/1  Iteration 143/178 Training loss: 3.1275 6.3388 sec/batch
Epoch 1/1  Iteration 144/178 Training loss: 3.1246 6.4280 sec/batch
Epoch 1/1  Iteration 145/178 Training loss: 3.1217 6.5542 sec/batch
Epoch 1/1  Iteration 146/178 Training loss: 3.1189 6.9582 sec/batch
Epoch 1/1  Iteration 147/178 Training loss: 3.1159 6.6180 sec/batch
Epoch 1/1  Iteration 148/178 Training loss: 3.1132 6.4691 sec/batch
Epoch 1/1  Iteration 149/178 Training loss: 3.1100 6.4827 sec/batch
Epoch 1/1  Iteration 150/178 Training loss: 3.1069 6.3239 sec/batch
Epoch 1/1  Iteration 151/178 Training loss: 3.1042 7.0204 sec/batch
Epoch 1/1  Iteration 152/178 Training loss: 3.1014 6.3352 sec/batch
Epoch 1/1  Iteration 153/178 Training loss: 3.0984 6.3553 sec/batch
Epoch 1/1  Iteration 154/178 Training loss: 3.0955 6.3201 sec/batch
Epoch 1/1  Iteration 155/178 Training loss: 3.0924 6.2609 sec/batch
Epoch 1/1  Iteration 156/178 Training loss: 3.0893 6.7548 sec/batch
Epoch 1/1  Iteration 157/178 Training loss: 3.0861 6.5146 sec/batch
Epoch 1/1  Iteration 158/178 Training loss: 3.0830 6.2497 sec/batch
Epoch 1/1  Iteration 159/178 Training loss: 3.0797 6.2531 sec/batch
Epoch 1/1  Iteration 160/178 Training loss: 3.0767 6.3010 sec/batch
Epoch 1/1  Iteration 161/178 Training loss: 3.0736 6.3407 sec/batch
Epoch 1/1  Iteration 162/178 Training loss: 3.0703 6.3320 sec/batch
Epoch 1/1  Iteration 163/178 Training loss: 3.0671 6.4173 sec/batch
Epoch 1/1  Iteration 164/178 Training loss: 3.0640 6.5119 sec/batch
Epoch 1/1  Iteration 165/178 Training loss: 3.0608 6.3241 sec/batch
Epoch 1/1  Iteration 166/178 Training loss: 3.0578 6.4703 sec/batch
Epoch 1/1  Iteration 167/178 Training loss: 3.0547 6.3929 sec/batch
Epoch 1/1  Iteration 168/178 Training loss: 3.0516 6.7677 sec/batch
Epoch 1/1  Iteration 169/178 Training loss: 3.0486 6.8073 sec/batch
Epoch 1/1  Iteration 170/178 Training loss: 3.0454 6.7840 sec/batch
Epoch 1/1  Iteration 171/178 Training loss: 3.0424 6.4806 sec/batch
Epoch 1/1  Iteration 172/178 Training loss: 3.0395 6.6917 sec/batch
Epoch 1/1  Iteration 173/178 Training loss: 3.0367 6.3780 sec/batch
Epoch 1/1  Iteration 174/178 Training loss: 3.0339 6.3075 sec/batch
Epoch 1/1  Iteration 175/178 Training loss: 3.0314 6.4663 sec/batch
Epoch 1/1  Iteration 176/178 Training loss: 3.0295 6.4146 sec/batch
Epoch 1/1  Iteration 177/178 Training loss: 3.0267 6.3592 sec/batch
Epoch 1/1  Iteration 178/178 Training loss: 3.0237 6.2561 sec/batch
Validation loss: 2.42845 Saving checkpoint!

In [13]:
tf.train.get_checkpoint_state('checkpoints/anna')

Sampling

Now that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the network with some text by passing in a string and building up a state from that.

The network gives us predictions for each character. To reduce noise and make things a little less random, I'm going to only choose a new character from the top N most likely characters.


In [17]:
def pick_top_n(preds, vocab_size, top_n=5):
    p = np.squeeze(preds)
    p[np.argsort(p)[:-top_n]] = 0
    p = p / np.sum(p)
    c = np.random.choice(vocab_size, 1, p=p)[0]
    return c

In [41]:
def sample(checkpoint, n_samples, lstm_size, vocab_size, prime="The "):
    prime = "Far"
    samples = [c for c in prime]
    model = build_rnn(vocab_size, lstm_size=lstm_size, sampling=True)
    saver = tf.train.Saver()
    with tf.Session() as sess:
        saver.restore(sess, checkpoint)
        new_state = sess.run(model.initial_state)
        for c in prime:
            x = np.zeros((1, 1))
            x[0,0] = vocab_to_int[c]
            feed = {model.inputs: x,
                    model.keep_prob: 1.,
                    model.initial_state: new_state}
            preds, new_state = sess.run([model.preds, model.final_state], 
                                         feed_dict=feed)

        c = pick_top_n(preds, len(vocab))
        samples.append(int_to_vocab[c])

        for i in range(n_samples):
            x[0,0] = c
            feed = {model.inputs: x,
                    model.keep_prob: 1.,
                    model.initial_state: new_state}
            preds, new_state = sess.run([model.preds, model.final_state], 
                                         feed_dict=feed)

            c = pick_top_n(preds, len(vocab))
            samples.append(int_to_vocab[c])
        
    return ''.join(samples)

In [44]:
checkpoint = "checkpoints/anna/i3560_l512_1.122.ckpt"
samp = sample(checkpoint, 2000, lstm_size, len(vocab), prime="Far")
print(samp)


Farlathit that if had so
like it that it were. He could not trouble to his wife, and there was
anything in them of the side of his weaky in the creature at his forteren
to him.

"What is it? I can't bread to those," said Stepan Arkadyevitch. "It's not
my children, and there is an almost this arm, true it mays already,
and tell you what I have say to you, and was not looking at the peasant,
why is, I don't know him out, and she doesn't speak to me immediately, as
you would say the countess and the more frest an angelembre, and time and
things's silent, but I was not in my stand that is in my head. But if he
say, and was so feeling with his soul. A child--in his soul of his
soul of his soul. He should not see that any of that sense of. Here he
had not been so composed and to speak for as in a whole picture, but
all the setting and her excellent and society, who had been delighted
and see to anywing had been being troed to thousand words on them,
we liked him.

That set in her money at the table, he came into the party. The capable
of his she could not be as an old composure.

"That's all something there will be down becime by throe is
such a silent, as in a countess, I should state it out and divorct.
The discussion is not for me. I was that something was simply they are
all three manshess of a sensitions of mind it all."

"No," he thought, shouted and lifting his soul. "While it might see your
honser and she, I could burst. And I had been a midelity. And I had a
marnief are through the countess," he said, looking at him, a chosing
which they had been carried out and still solied, and there was a sen that
was to be completely, and that this matter of all the seconds of it, and
a concipation were to her husband, who came up and conscaously, that he
was not the station. All his fourse she was always at the country,,
to speak oft, and though they were to hear the delightful throom and
whether they came towards the morning, and his living and a coller and
hold--the children. 

In [43]:
checkpoint = "checkpoints/anna/i200_l512_2.432.ckpt"
samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far")
print(samp)


Farnt him oste wha sorind thans tout thint asd an sesand an hires on thime sind thit aled, ban thand and out hore as the ter hos ton ho te that, was tis tart al the hand sostint him sore an tit an son thes, win he se ther san ther hher tas tarereng,.

Anl at an ades in ond hesiln, ad hhe torers teans, wast tar arering tho this sos alten sorer has hhas an siton ther him he had sin he ard ate te anling the sosin her ans and
arins asd and ther ale te tot an tand tanginge wath and ho ald, so sot th asend sat hare sother horesinnd, he hesense wing ante her so tith tir sherinn, anded and to the toul anderin he sorit he torsith she se atere an ting ot hand and thit hhe so the te wile har
ens ont in the sersise, and we he seres tar aterer, to ato tat or has he he wan ton here won and sen heren he sosering, to to theer oo adent har herere the wosh oute, was serild ward tous hed astend..

I's sint on alt in har tor tit her asd hade shithans ored he talereng an soredendere tim tot hees. Tise sor and 

In [46]:
checkpoint = "checkpoints/anna/i600_l512_1.750.ckpt"
samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far")
print(samp)


Fard as astice her said he celatice of to seress in the raice, and to be the some and sere allats to that said to that the sark and a cast a the wither ald the pacinesse of her had astition, he said to the sount as she west at hissele. Af the cond it he was a fact onthis astisarianing.


"Or a ton to to be that's a more at aspestale as the sont of anstiring as
thours and trey.

The same wo dangring the
raterst, who sore and somethy had ast out an of his book. "We had's beane were that, and a morted a thay he had to tere. Then to
her homent andertersed his his ancouted to the pirsted, the soution for of the pirsice inthirgest and stenciol, with the hard and and
a colrice of to be oneres,
the song to this anderssad.
The could ounterss the said to serom of
soment a carsed of sheres of she
torded
har and want in their of hould, but
her told in that in he tad a the same to her. Serghing an her has and with the seed, and the camt ont his about of the
sail, the her then all houg ant or to hus to 

In [47]:
checkpoint = "checkpoints/anna/i1000_l512_1.484.ckpt"
samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far")
print(samp)


Farrat, his felt has at it.

"When the pose ther hor exceed
to his sheant was," weat a sime of his sounsed. The coment and the facily that which had began terede a marilicaly whice whether the pose of his hand, at she was alligated herself the same on she had to
taiking to his forthing and streath how to hand
began in a lang at some at it, this he cholded not set all her. "Wo love that is setthing. Him anstering as seen that."

"Yes in the man that say the mare a crances is it?" said Sergazy Ivancatching. "You doon think were somether is ifficult of a mone of
though the most at the countes that the
mean on the come to say the most, to
his feesing of
a man she, whilo he
sained and well, that he would still at to said. He wind at his for the sore in the most
of hoss and almoved to see him. They have betine the sumper into at he his stire, and what he was that at the so steate of the
sound, and shin should have a geest of shall feet on the conderation to she had been at that imporsing the dre