This project is part of the Nanodegree em Deep Learning Foundation taught by Udacity. The source code for running this project is available in my repository on GitHub.

In this project, I’ll generate my own Simpsons TV scripts using RNNs. I’ll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network I’ll build will generate a new TV script for a scene at Moe’s Tavern.

Step 1: Get the data

import helper

data_dir = './data/simpsons/moes_tavern_lines.txt'
text = helper.load_data(data_dir)

text = text[81:]

Step 2: Explore the data

In view_sentence_range is possible to view different parts of the data.

view_sentence_range = (0, 10)

import numpy as np

print('Dataset Stats')
print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))
scenes = text.split('\n\n')
print('Number of scenes: {}'.format(len(scenes)))
sentence_count_scene = [scene.count('\n') for scene in scenes]
print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))

sentences = [sentence for scene in scenes for sentence in scene.split('\n')]
print('Number of lines: {}'.format(len(sentences)))
word_count_sentence = [len(sentence.split()) for sentence in sentences]
print('Average number of words in each line: {}'.format(np.average(word_count_sentence)))

print('The sentences {} to {}:'.format(*view_sentence_range))

Expected outcome:
The first sentence

Step 3: Implement preprocessing functions

The first thing to do to any dataset is preprocessing using following preprocessing functions:

  • Lookup Table
  • Tokenize Punctuation

Lookup table

To create a word embedding, you first I need to transform the words to ids and create two dictionaries:

  • Dictionary to go from the words to an id, we’ll call vocab_to_int
  • Dictionary to go from the id to word, we’ll call int_to_vocab

I return these dictionaries in the following tuple (vocab_to_int, int_to_vocab)

import numpy as np
import problem_unittests as tests

def create_lookup_tables(text):
    wordsetlist = list(set(text))
    vocab_to_int = dict()
    int_to_vocab = dict()
    for idx in range(len(wordsetlist)):
        vocab_to_int[wordsetlist[idx]] = idx
        int_to_vocab[idx] = wordsetlist[idx]
    return (vocab_to_int, int_to_vocab)


Tokenize punctuation

I’ll be splitting the script into a word array using spaces as delimiters. The punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word “bye” and “bye!”.

I implement the function token_lookup to return a dict that will be used to tokenize symbols like “!” into “||Exclamation_Mark||”. I create a dictionary for the following symbols where the symbol is the key and value is the token:

  • Period (.)
  • Comma (,)
  • Quotation Mark (“)
  • Semicolon (;)
  • Exclamation mark (!)
  • Question mark (?)
  • Left Parentheses (()
  • Right Parentheses ())
  • Dash (–)
  • Return (\n)

This dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it’s own word, making it easier for the neural network to predict on the next word. I make sure you don’t use a token that could be confused as a word. Instead of using the token “dash”, try using something like “||dash||”.

def token_lookup():
    token_dict = {'.':"||period||",
    return token_dict


Step 4: Build the neural network

I’ll build the components necessary to build a RNN by implementing the following functions below:

  • get_inputs
  • get_init_cell
  • get_embed
  • build_rnn
  • build_nn
  • get_batches


Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:

  • Input text placeholder named “input” using the TF Placeholder name parameter;
  • Targets placeholder;
  • Learning Rate placeholder;
  • Return the placeholders in the following tuple (Input, Targets, LearningRate).
def get_inputs():
    inputs_ = tf.placeholder(tf.int32, [None, None], name="input")
    targets_ = tf.placeholder(tf.int32, [None, None], name="targets")
    learningrate_ = tf.placeholder(tf.float32, name="learningrate")
    return (inputs_, targets_, learningrate_)


Build RNN cell and initialize

Stack one or more BasicLSTMCells in a MultiRNNCell.

  • The RNN size should be set using rnn_size
  • Initalize Cell State using the MultiRNNCell’s zero_state() function
    • Apply the name “initial_state” to the initial state using tf.identity()

Return the cell and initial state in the following tuple (Cell, InitialState)

def get_init_cell(batch_size, rnn_size):
    lstm1 = tf.contrib.rnn.BasicLSTMCell(rnn_size)
    cell = tf.contrib.rnn.MultiRNNCell([lstm1])
    initial_state = tf.identity(cell.zero_state(batch_size, tf.float32), name = "initial_state")  
    return (cell, initial_state)


Word embedding

Apply embedding to input_data using TensorFlow. Return the embedded sequence

def get_embed(input_data, vocab_size, embed_dim):
    embedding = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1))
    embed = tf.nn.embedding_lookup(embedding, input_data) 
    return embed


Step 5: Build RNN

Created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.

  • Build the RNN using the tf.nn.dynamic_rnn()
    • Apply the name “final_state” to the final state using tf.identity()

Return the outputs and final_state state in the following tuple (Outputs, FinalState)

def build_rnn(cell, inputs):
    outputs, provisional_final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
    final_state = tf.identity(provisional_final_state, name="final_state")

    return outputs, final_state


Step 6: Build the neural network

Apply the functions you implemented above to:

  • Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
  • Build RNN using cell and your build_rnn(cell, inputs) function.
  • Apply a fully connected layer with a linear activation and vocab_size as the number of outputs.

Return the logits and final state in the following tuple (Logits, FinalState)

def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
    embedding_size = 256
    embedding = get_embed(input_data, vocab_size, embedding_size)
    rnn_output, final_state = build_rnn(cell, embedding)
    prediction = tf.contrib.layers.fully_connected(rnn_output, vocab_size, activation_fn = None)
    return prediction, final_state


Step 7: Batches

Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:

  • The first element is a single batch of input with the shape [batch size, sequence length]
  • The second element is a single batch of targets with the shape [batch size, sequence length]
  • If you can’t fill the last batch with enough data, drop the last batch

Notice that the last target value in the last batch is the first input value of the first batch. In this case, 1. This is a common technique used when creating sequence batches, although it is rather unintuitive.

import math

def get_batches(int_text, batch_size, seq_length):
    int_text = np.array(int_text)
    final = [0]
    batch_count = len(int_text) // (batch_size * seq_length)
    inputs = int_text[:batch_count * batch_size * seq_length]

    targets = int_text[1:(batch_count * batch_size * seq_length)+1]
    targets[-1:] = final
    batches = np.zeros([batch_count, 2, batch_size, seq_length])
    x = np.array(np.split(inputs, indices_or_sections = batch_size))
    x_batches = np.split(x.reshape(batch_size, -1), batch_count, 1)
    y = np.array(np.split(targets, indices_or_sections = batch_size))
    y_batches = np.split(y.reshape(batch_size, -1), batch_count, 1)
    zipped_batches = list(zip(x_batches, y_batches))
    return np.array(zipped_batches)


Step 8: Neural network training

Tune the following parameters:

  • Set num_epochs to the number of epochs
  • Set batch_size to the batch size
  • Set rnn_size to the size of the RNNs
  • Set embed_dim to the size of the embedding
  • Set seq_length to the length of sequence
  • Set learning_rate to the learning rate
  • Set show_every_n_batches to the number of batches the neural network should print progress
num_epochs = 50
batch_size = 128
rnn_size = 1024
embed_dim = 2
seq_length = 16
learning_rate = 0.01
show_every_n_batches = 16

save_dir = './save'

Step 9: Build the graph

I build the graph using the neural network implemented.

from tensorflow.contrib import seq2seq

train_graph = tf.Graph()
with train_graph.as_default():
    vocab_size = len(int_to_vocab)
    input_text, targets, lr = get_inputs()
    input_data_shape = tf.shape(input_text)
    cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)
    logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim)

    probs = tf.nn.softmax(logits, name='probs')
    cost = seq2seq.sequence_loss(
        tf.ones([input_data_shape[0], input_data_shape[1]]))

    optimizer = tf.train.AdamOptimizer(lr)

    gradients = optimizer.compute_gradients(cost)
    capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
    train_op = optimizer.apply_gradients(capped_gradients)

Step 10: Train

batches = get_batches(int_text, batch_size, seq_length)

with tf.Session(graph=train_graph) as sess:

    for epoch_i in range(num_epochs):
        state =, {input_text: batches[0][0]})

        for batch_i, (x, y) in enumerate(batches):
            feed = {
                input_text: x,
                targets: y,
                initial_state: state,
                lr: learning_rate}
            train_loss, state, _ =[cost, final_state, train_op], feed)

            if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:
                print('Epoch {:>3} Batch {:>4}/{}   train_loss = {:.3f}'.format(

    saver = tf.train.Saver(), save_dir)
    print('Model Trained and Saved')

Step 11: Implement generate functions

Get tensors

Get tensors from loaded_graph using the function get_tensor_by_name() using the following names:

  • “input:0”
  • “initial_state:0”
  • “final_state:0”
  • “probs:0”

Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)

def get_tensors(loaded_graph):
    inp_tensor = loaded_graph.get_tensor_by_name("input:0")
    ins_tensor = loaded_graph.get_tensor_by_name("initial_state:0")
    fst_tensor = loaded_graph.get_tensor_by_name("final_state:0")
    prb_tensor = loaded_graph.get_tensor_by_name("probs:0")
    return inp_tensor, ins_tensor, fst_tensor, prb_tensor


Choose word

Implement the pick_word() function to select the next word using probabilities.

def pick_word(probabilities, int_to_vocab):
    selection = np.random.choice(range(len(probabilities)), p=probabilities)
    return int_to_vocab[selection]


Step 12: Generate TV script

This will generate the TV. Set gen_length to the length of TV script to generate.

gen_length = 400
prime_word = 'moe_szyslak'

loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
    loader = tf.train.import_meta_graph(load_dir + '.meta')
    loader.restore(sess, load_dir)

    input_text, initial_state, final_state, probs = get_tensors(loaded_graph)

    gen_sentences = [prime_word + ':']
    prev_state =, {input_text: np.array([[1]])})

    for n in range(gen_length):
        # Dynamic Input
        dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]
        dyn_seq_length = len(dyn_input[0])

        probabilities, prev_state =
            [probs, final_state],
            {input_text: dyn_input, initial_state: prev_state})
        pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)

    tv_script = ' '.join(gen_sentences)
    for key, token in token_dict.items():
        ending = ' ' if key in ['\n', '(', '"'] else ''
        tv_script = tv_script.replace(' ' + token.lower(), key)
    tv_script = tv_script.replace('\n ', '\n')
    tv_script = tv_script.replace('( ', '(')

Expected outcome:
Generate TV script

Running the project

Downloading files needed to run this project on my GitHub. There you also have additional information on preparing the environment to run it.