📑   P3: TV Script Generation

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

In [2]:
%%html
<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron|Roboto');
body {background-color: aliceblue;}
a {color: darksteelblue; font-family: Roboto;}
h1, h2 {color: #338DD4; font-family: Orbitron; text-shadow: 4px 4px 4px #ccc;}
h3, h4 {color: steelblue; font-family: Roboto; text-shadow: 4px 4px 4px #ccc;}
span {text-shadow: 4px 4px 4px #ccc;}
div.output_prompt, div.output_area pre {color: slategray;}
div.input_prompt, div.output_subarea {color: darksteelblue;}      
div.output_stderr pre {background-color: aliceblue;}  
div.output_stderr {background-color: slategrey;}        
</style>
<script>
code_show = true; 
function code_display() {
    if (code_show) {
        $('div.input').each(function(id) {
            if (id == 0 || $(this).html().indexOf('hide_code') > -1) {$(this).hide();}
        });
        $('div.output_prompt').css('opacity', 0);
    } else {
        $('div.input').each(function(id) {$(this).show();});
        $('div.output_prompt').css('opacity', 1);
    };
    code_show = !code_show;
} 
$(document).ready(code_display);
</script>
<form action="javascript: code_display()">
<input style="color: #338DD4; background: aliceblue; text-shadow: 4px 4px 4px #ccc;" \ 
type="submit" value="Click to display or hide code cells">
</form>
In [3]:
hide_code=''
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

import numpy as np
import os
import pickle

import tensorflow as tf
from tensorflow.contrib import rnn
from tensorflow.contrib import seq2seq

from distutils.version import LooseVersion
import warnings
In [4]:
hide_code
# https://github.com/udacity/deep-learning/blob/master/tv-script-generation/helper.py
def load_data(path):
    """Load Dataset from File"""
    with open(os.path.join(path), "r") as f:
        data = f.read()
    return data

def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
    """Preprocess Text Data"""
    text = load_data(dataset_path)
    
    # Ignore notice, since we don't use it for analysing the data
    text = text[81:]

    token_dict = token_lookup()
    for key, token in token_dict.items():
        text = text.replace(key, ' {} '.format(token))

    text = text.lower()
    text = text.split()

    vocab_to_int, int_to_vocab = create_lookup_tables(text)
    int_text = [vocab_to_int[word] for word in text]
    pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('preprocess.p', 'wb'))

def load_preprocess():
    """Load the Preprocessed Training data and return them in batches of <batch_size> or less"""
    return pickle.load(open('preprocess.p', mode='rb'))

def save_params(params):
    """Save parameters to file"""
    pickle.dump(params, open('params.p', 'wb'))

def load_params():
    """Load parameters from file"""
    return pickle.load(open('params.p', mode='rb'))
In [5]:
hide_code
# https://github.com/udacity/deep-learning/blob/master/tv-script-generation/problem_unittests.py
def _print_success_message():
    print('Tests Passed')

def test_create_lookup_tables(create_lookup_tables):
    with tf.Graph().as_default():
        test_text = '''
        Moe_Szyslak Moe's Tavern Where the elite meet to drink         
        Bart_Simpson Eh yeah hello is Mike there Last name Rotch        
        Moe_Szyslak Hold on I'll check Mike Rotch Mike Rotch Hey has anybody seen Mike Rotch lately       
        Moe_Szyslak Listen you little puke One of these days 
                    I'm gonna catch you and I'm gonna carve my name on your back with an ice pick                   
        Moe_Szyslak Whats the matter Homer You're not your normal effervescent self        
        Homer_Simpson I got my problems Moe Give me another one       
        Moe_Szyslak Homer hey you should not drink to forget your problems       
        Barney_Gumble Yeah you should only drink to enhance your social skills'''

        test_text = test_text.lower()
        test_text = test_text.split()

        vocab_to_int, int_to_vocab = create_lookup_tables(test_text)

        # Check types
        assert isinstance(vocab_to_int, dict),\
            'vocab_to_int is not a dictionary.'
        assert isinstance(int_to_vocab, dict),\
            'int_to_vocab is not a dictionary.'

        # Compare lengths of dicts
        assert len(vocab_to_int) == len(int_to_vocab),\
            'Length of vocab_to_int and int_to_vocab don\'t match. ' \
            'vocab_to_int is length {}. int_to_vocab is length {}'.format(len(vocab_to_int), len(int_to_vocab))

        # Make sure the dicts have the same words
        vocab_to_int_word_set = set(vocab_to_int.keys())
        int_to_vocab_word_set = set(int_to_vocab.values())

        assert not (vocab_to_int_word_set - int_to_vocab_word_set),\
            'vocab_to_int and int_to_vocab don\'t have the same words.' \
            '{} found in vocab_to_int, but not in int_to_vocab'\
            .format(vocab_to_int_word_set - int_to_vocab_word_set)
        assert not (int_to_vocab_word_set - vocab_to_int_word_set),\
            'vocab_to_int and int_to_vocab don\'t have the same words.' \
            '{} found in int_to_vocab, but not in vocab_to_int'\
            .format(int_to_vocab_word_set - vocab_to_int_word_set)

        # Make sure the dicts have the same word ids
        vocab_to_int_word_id_set = set(vocab_to_int.values())
        int_to_vocab_word_id_set = set(int_to_vocab.keys())

        assert not (vocab_to_int_word_id_set - int_to_vocab_word_id_set),\
            'vocab_to_int and int_to_vocab don\'t contain the same word ids.' \
            '{} found in vocab_to_int, but not in int_to_vocab'\
            .format(vocab_to_int_word_id_set - int_to_vocab_word_id_set)
        assert not (int_to_vocab_word_id_set - vocab_to_int_word_id_set),\
            'vocab_to_int and int_to_vocab don\'t contain the same word ids.' \
            '{} found in int_to_vocab, but not in vocab_to_int'\
            .format(int_to_vocab_word_id_set - vocab_to_int_word_id_set)

        # Make sure the dicts make the same lookup
        missmatches = [(word, id, id, int_to_vocab[id]) \
                       for word, id in vocab_to_int.items() if int_to_vocab[id] != word]

        assert not missmatches,\
            'Found {} missmatche(s). First missmatch: vocab_to_int[{}] = {} and int_to_vocab[{}] = {}'\
            .format(len(missmatches),*missmatches[0])

        assert len(vocab_to_int) > len(set(test_text))/2,\
            'The length of vocab seems too small.  Found a length of {}'.format(len(vocab_to_int))

    _print_success_message()

def test_get_batches(get_batches):
    with tf.Graph().as_default():
        test_batch_size = 128
        test_seq_length = 5
        test_int_text = list(range(1000*test_seq_length))
        batches = get_batches(test_int_text, test_batch_size, test_seq_length)

        # Check type
        assert isinstance(batches, np.ndarray),\
            'Batches is not a Numpy array'

        # Check shape
        assert batches.shape == (7, 2, 128, 5),\
            'Batches returned wrong shape.  Found {}'.format(batches.shape)

        for x in range(batches.shape[2]):
            assert np.array_equal(batches[0,0,x], np.array(range(x * 35, x * 35 + batches.shape[3]))),\
                'Batches returned wrong contents. For example, input sequence {} in the first batch was {}'\
                .format(x, batches[0,0,x])
            assert np.array_equal(batches[0,1,x], np.array(range(x * 35 + 1, x * 35 + 1 + batches.shape[3]))),\
                'Batches returned wrong contents. For example, target sequence {} in the first batch was {}'\
                .format(x, batches[0,1,x])


        last_seq_target = (test_batch_size-1) * 35 + 31
        last_seq = np.array(range(last_seq_target, last_seq_target+ batches.shape[3]))
        last_seq[-1] = batches[0,0,0,0]

        assert np.array_equal(batches[-1,1,-1], last_seq),\
            'The last target of the last batch should be the first input of the first batch. \
            Found {} but expected {}'.format(batches[-1,1,-1], last_seq)

    _print_success_message()

def test_tokenize(token_lookup):
    with tf.Graph().as_default():
        symbols = set(['.', ',', '"', ';', '!', '?', '(', ')', '--', '\n'])
        token_dict = token_lookup()

        # Check type
        assert isinstance(token_dict, dict), \
            'Returned type is {}.'.format(type(token_dict))

        # Check symbols
        missing_symbols = symbols - set(token_dict.keys())
        unknown_symbols = set(token_dict.keys()) - symbols

        assert not missing_symbols, \
            'Missing symbols: {}'.format(missing_symbols)
        assert not unknown_symbols, \
            'Unknown symbols: {}'.format(unknown_symbols)

        # Check values type
        bad_value_type = [type(val) for val in token_dict.values() if not isinstance(val, str)]

        assert not bad_value_type,\
            'Found token as {} type.'.format(bad_value_type[0])

        # Check for spaces
        key_has_spaces = [k for k in token_dict.keys() if ' ' in k]
        val_has_spaces = [val for val in token_dict.values() if ' ' in val]

        assert not key_has_spaces,\
            'The key "{}" includes spaces. Remove spaces from keys and values'.format(key_has_spaces[0])
        assert not val_has_spaces,\
            'The value "{}" includes spaces. Remove spaces from keys and values'.format(val_has_spaces[0])

        # Check for symbols in values
        symbol_val = ()
        for symbol in symbols:
            for val in token_dict.values():
                if symbol in val:
                    symbol_val = (symbol, val)

        assert not symbol_val,\
            'Don\'t use a symbol that will be replaced in your tokens. Found the symbol {} in value {}'\
            .format(*symbol_val)

    _print_success_message()

def test_get_inputs(get_inputs):
    with tf.Graph().as_default():
        input_data, targets, lr = get_inputs()

        # Check type
        assert input_data.op.type == 'Placeholder',\
            'Input not a Placeholder.'
        assert targets.op.type == 'Placeholder',\
            'Targets not a Placeholder.'
        assert lr.op.type == 'Placeholder',\
            'Learning Rate not a Placeholder.'

        # Check name
        assert input_data.name == 'input:0',\
            'Input has bad name.  Found name {}'.format(input_data.name)

        # Check rank
        input_rank = 0 if input_data.get_shape() == None else len(input_data.get_shape())
        targets_rank = 0 if targets.get_shape() == None else len(targets.get_shape())
        lr_rank = 0 if lr.get_shape() == None else len(lr.get_shape())

        assert input_rank == 2,\
            'Input has wrong rank.  Rank {} found.'.format(input_rank)
        assert targets_rank == 2,\
            'Targets has wrong rank. Rank {} found.'.format(targets_rank)
        assert lr_rank == 0,\
            'Learning Rate has wrong rank. Rank {} found'.format(lr_rank)

    _print_success_message()

def test_get_init_cell(get_init_cell):
    with tf.Graph().as_default():
        test_batch_size_ph = tf.placeholder(tf.int32, [])
        test_rnn_size = 256

        cell, init_state = get_init_cell(test_batch_size_ph, test_rnn_size)

        # Check type
        assert isinstance(cell, tf.contrib.rnn.MultiRNNCell),\
            'Cell is wrong type.  Found {} type'.format(type(cell))

        # Check for name attribute
        assert hasattr(init_state, 'name'),\
            'Initial state doesn\'t have the "name" attribute.  Try using `tf.identity` to set the name.'

        # Check name
        assert init_state.name == 'initial_state:0',\
            'Initial state doesn\'t have the correct name. Found the name {}'.format(init_state.name)

    _print_success_message()

def test_get_embed(get_embed):
    with tf.Graph().as_default():
        embed_shape = [50, 5, 256]
        test_input_data = tf.placeholder(tf.int32, embed_shape[:2])
        test_vocab_size = 27
        test_embed_dim = embed_shape[2]

        embed = get_embed(test_input_data, test_vocab_size, test_embed_dim)

        # Check shape
        assert embed.shape == embed_shape,\
            'Wrong shape.  Found shape {}'.format(embed.shape)

    _print_success_message()

def test_build_rnn(build_rnn):
    with tf.Graph().as_default():
        test_rnn_size = 256
        test_rnn_layer_size = 2
        test_cell = rnn.MultiRNNCell([rnn.BasicLSTMCell(test_rnn_size) for _ in range(test_rnn_layer_size)])

        test_inputs = tf.placeholder(tf.float32, [None, None, test_rnn_size])
        outputs, final_state = build_rnn(test_cell, test_inputs)

        # Check name
        assert hasattr(final_state, 'name'),\
            'Final state doesn\'t have the "name" attribute.  Try using `tf.identity` to set the name.'
        assert final_state.name == 'final_state:0',\
            'Final state doesn\'t have the correct name. Found the name {}'.format(final_state.name)

        # Check shape
        assert outputs.get_shape().as_list() == [None, None, test_rnn_size],\
            'Outputs has wrong shape.  Found shape {}'.format(outputs.get_shape())
        assert final_state.get_shape().as_list() == [test_rnn_layer_size, 2, None, test_rnn_size],\
            'Final state wrong shape.  Found shape {}'.format(final_state.get_shape())

    _print_success_message()


def test_build_nn(build_nn):
    with tf.Graph().as_default():
        test_input_data_shape = [128, 5]
        test_input_data = tf.placeholder(tf.int32, test_input_data_shape)
        test_rnn_size = 256
        test_embed_dim = 300
        test_rnn_layer_size = 2
        test_vocab_size = 27
        test_cell = rnn.MultiRNNCell([rnn.BasicLSTMCell(test_rnn_size) for _ in range(test_rnn_layer_size)])

        logits, final_state = build_nn(test_cell, test_rnn_size, test_input_data, test_vocab_size, test_embed_dim)

        # Check name
        assert hasattr(final_state, 'name'), \
            'Final state doesn\'t have the "name" attribute.  Are you using build_rnn?'
        assert final_state.name == 'final_state:0', \
            'Final state doesn\'t have the correct name. Found the name {}. Are you using build_rnn?'\
            .format(final_state.name)

        # Check Shape
        assert logits.get_shape().as_list() == test_input_data_shape + [test_vocab_size], \
            'Outputs has wrong shape.  Found shape {}'.format(logits.get_shape())
        assert final_state.get_shape().as_list() == [test_rnn_layer_size, 2, None, test_rnn_size], \
            'Final state wrong shape.  Found shape {}'.format(final_state.get_shape())

    _print_success_message()

def test_get_tensors(get_tensors):
    test_graph = tf.Graph()
    with test_graph.as_default():
        test_input = tf.placeholder(tf.int32, name='input')
        test_initial_state = tf.placeholder(tf.int32, name='initial_state')
        test_final_state = tf.placeholder(tf.int32, name='final_state')
        test_probs = tf.placeholder(tf.float32, name='probs')

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

    # Check correct tensor
    assert input_text == test_input,\
        'Test input is wrong tensor'
    assert initial_state == test_initial_state, \
        'Initial state is wrong tensor'
    assert final_state == test_final_state, \
        'Final state is wrong tensor'
    assert probs == test_probs, \
        'Probabilities is wrong tensor'

    _print_success_message()

def test_pick_word(pick_word):
    with tf.Graph().as_default():
        test_probabilities = np.array([0.1, 0.8, 0.05, 0.05])
        test_int_to_vocab = {word_i: word for word_i, word in enumerate(['this', 'is', 'a', 'test'])}

        pred_word = pick_word(test_probabilities, test_int_to_vocab)

        # Check type
        assert isinstance(pred_word, str),\
            'Predicted word is wrong type. Found {} type.'.format(type(pred_word))

        # Check word is from vocab
        assert pred_word in test_int_to_vocab.values(),\
            'Predicted word not found in int_to_vocab.'

    _print_success_message()

Get the Data

The data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc..

In [6]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""
data_dir = 'data/simpsons/moes_tavern_lines.txt'
text = load_data(data_dir)
# Ignore notice, since we don't use it for analysing the data
text = text[81:]

Explore the Data

Play around with view_sentence_range to view different parts of the data.

In [7]:
hide_code
view_sentence_range = (0, 15)

"""DON'T MODIFY ANYTHING IN THIS CELL"""
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()
print('The sentences {} to {}:'.format(*view_sentence_range))
print('\n'.join(text.split('\n')[view_sentence_range[0]:view_sentence_range[1]]))
Dataset Stats
Roughly the number of unique words: 11492
Number of scenes: 262
Average number of sentences in each scene: 15.248091603053435
Number of lines: 4257
Average number of words in each line: 11.50434578341555

The sentences 0 to 15:
Moe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink.
Bart_Simpson: Eh, yeah, hello, is Mike there? Last name, Rotch.
Moe_Szyslak: (INTO PHONE) Hold on, I'll check. (TO BARFLIES) Mike Rotch. Mike Rotch. Hey, has anybody seen Mike Rotch, lately?
Moe_Szyslak: (INTO PHONE) Listen you little puke. One of these days I'm gonna catch you, and I'm gonna carve my name on your back with an ice pick.
Moe_Szyslak: What's the matter Homer? You're not your normal effervescent self.
Homer_Simpson: I got my problems, Moe. Give me another one.
Moe_Szyslak: Homer, hey, you should not drink to forget your problems.
Barney_Gumble: Yeah, you should only drink to enhance your social skills.


Moe_Szyslak: Ah, isn't that nice. Now, there is a politician who cares.
Barney_Gumble: If I ever vote, it'll be for him. (BELCH)


Barney_Gumble: Hey Homer, how's your neighbor's store doing?

Implement Preprocessing Functions

The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:

  • Lookup Table
  • Tokenize Punctuation

Lookup Table

To create a word embedding, you first need to transform the words to ids. In this function, 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

Return these dictionaries in the following tuple (vocab_to_int, int_to_vocab)

In [8]:
hide_code
def create_lookup_tables(text):
    """
    Create lookup tables for vocabulary
    :param text: The text of tv scripts split into words
    :return: A tuple of dicts (vocab_to_int, int_to_vocab)
    """
    # TODO: Implement Function
    
    vocabulary = set(text)
    int_to_vocab = dict(enumerate(vocabulary))
    vocab_to_int = dict((v,k) for k,v in int_to_vocab.items())
    
    return vocab_to_int, int_to_vocab

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_create_lookup_tables(create_lookup_tables)
Tests Passed

Tokenize Punctuation

We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".

Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". 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. 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||".

In [9]:
hide_code
def token_lookup():
    """
    Generate a dict to turn punctuation into a token.
    :return: Tokenize dictionary where the key is the punctuation and the value is the token
    """
    # TODO: Implement Function
    
    punctuation_dict = {'.': '$$dot$$', ',': '$$comma$$', '"': '$$quot_mark$$', 
                        ';': '$$semicolon$$', '!': '$$excl_mark$$', '?': '$$question$$',
                        '(': '$$l_parentheses$$', ')': '$$r_parentheses$$',
                        '--': '$$dash$$', '\n': '$$return$$'}
    return punctuation_dict

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_tokenize(token_lookup)
Tests Passed

Preprocess All the Data and Save It

Running the code cell below will preprocess all the data and save it to file.

In [10]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""
# Preprocess Training, Validation, and Testing Data
preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)

Checkpoint 1

This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.

In [11]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""
int_text, vocab_to_int, int_to_vocab, token_dict = load_preprocess()
In [12]:
hide_code
print('Example of int_text \n', int_text[:100], '\n')
l = [0,1,2,3,4]
print('Example of vocab_to_int \n', {k:v for k,v in vocab_to_int.items() if v in [0,1,2,3,4]}, '\n')
print('Example of int_to_vocab \n', {k:v for k,v in int_to_vocab.items() if k in [0,1,2,3,4]}, '\n')
print('Example of token_dict \n', token_dict)
Example of int_text 
 [975, 691, 2348, 6692, 6026, 3742, 2501, 4657, 3729, 4286, 6447, 2040, 5213, 3318, 4657, 3541, 1221, 5569, 2648, 3668, 2648, 6626, 2648, 2452, 1125, 4079, 5508, 6758, 5230, 2648, 3803, 4657, 3541, 975, 691, 2348, 6692, 6026, 1139, 3663, 2648, 522, 4951, 4657, 691, 5213, 609, 6026, 1125, 3803, 4657, 1125, 3803, 4657, 4810, 2648, 945, 1437, 3022, 1125, 3803, 2648, 201, 5508, 3541, 975, 691, 2348, 6692, 6026, 5994, 1160, 1890, 2481, 4657, 2768, 5709, 5332, 1393, 5450, 584, 6092, 1160, 2648, 396, 5450, 584, 3244, 5882, 5230, 3663, 5897, 2191, 6315, 5322, 5835, 5568, 4657, 3541, 975] 

Example of vocab_to_int 
 {'type': 0, "writin'": 1, 'griffith': 2, 'wolveriskey': 3, 'occasion': 4} 

Example of int_to_vocab 
 {0: 'type', 1: "writin'", 2: 'griffith', 3: 'wolveriskey', 4: 'occasion'} 

Example of token_dict 
 {'.': '$$dot$$', ',': '$$comma$$', '"': '$$quot_mark$$', ';': '$$semicolon$$', '!': '$$excl_mark$$', '?': '$$question$$', '(': '$$l_parentheses$$', ')': '$$r_parentheses$$', '--': '$$dash$$', '\n': '$$return$$'}

Build the Neural Network

You'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

Check the Version of TensorFlow and Access to GPU

In [13]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
TensorFlow Version: 1.0.0
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/ipykernel_launcher.py:10: UserWarning: No GPU found. Please use a GPU to train your neural network.
  # Remove the CWD from sys.path while we load stuff.

Input

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)

In [14]:
hide_code
def get_inputs():
    """
    Create TF Placeholders for input, targets, and learning rate.
    :return: Tuple (input, targets, learning rate)
    """
    # TODO: Implement Function
    
    inputs = tf.placeholder(tf.int32, shape=[None, None], name='input') # rank 2
    targets = tf.placeholder(tf.int32, shape=[None, None], name='targets') # rank 2    
    learning_rate = tf.placeholder(tf.float32, shape=[], name='learning_rate') # rank 0
    
    return inputs, targets, learning_rate    

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_get_inputs(get_inputs)
Tests Passed

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)

In [15]:
hide_code
def get_init_cell(batch_size, rnn_size, keep_prob=0.8, num_layers=2):
    """
    Create an RNN Cell and initialize it.
    :param batch_size: Size of batches
    :param rnn_size: Size of RNNs
    :return: Tuple (cell, initialize state)
    """
    # TODO: Implement Function
    def create_lstm_cell(state_size):
        lstm_layer = tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(state_size)
        
        return tf.contrib.rnn.core_rnn_cell.DropoutWrapper(lstm_layer, 
                                                           input_keep_prob=1.0,
                                                           output_keep_prob=keep_prob)

    rnn_cell = tf.contrib.rnn.\
    core_rnn_cell.MultiRNNCell([create_lstm_cell(rnn_size) for _ in range(num_layers)])

    
    initial_state = rnn_cell.zero_state(batch_size, tf.float32)
    initial_state = tf.identity(initial_state, name='initial_state')
    
    return rnn_cell, initial_state

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_get_init_cell(get_init_cell)
Tests Passed

Word Embedding

Apply embedding to input_data using TensorFlow. Return the embedded sequence.

In [16]:
hide_code
def get_embed(input_data, vocab_size, embed_dim):
    """
    Create embedding for <input_data>.
    :param input_data: TF placeholder for text input.
    :param vocab_size: Number of words in vocabulary.
    :param embed_dim: Number of embedding dimensions
    :return: Embedded input.
    """
    # TODO: Implement Function
    
    word_embeddings = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1))
    embedded_word_ids = tf.nn.embedding_lookup(word_embeddings, input_data)
    
    return embedded_word_ids

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_get_embed(get_embed)
Tests Passed

Build RNN

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

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

In [17]:
hide_code
def build_rnn(cell, inputs):
    """
    Create a RNN using a RNN Cell
    :param cell: RNN Cell
    :param inputs: Input text data
    :return: Tuple (Outputs, Final State)
    """
    # TODO: Implement Function

    outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)
    final_state = tf.identity(final_state, name='final_state')
    
    return outputs, final_state

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_build_rnn(build_rnn)
Tests Passed

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)

In [18]:
hide_code
def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
    """
    Build part of the neural network
    :param cell: RNN cell
    :param rnn_size: Size of rnns
    :param input_data: Input data
    :param vocab_size: Vocabulary size
    :param embed_dim: Number of embedding dimensions
    :return: Tuple (Logits, FinalState)
    """
    # TODO: Implement Function
    
    emb_outputs = get_embed(input_data, vocab_size, embed_dim)
    
    rnn_outputs, final_state = build_rnn(cell, emb_outputs)
    
    # activation_fn=None == linear activation   
    logits = tf.contrib.layers.fully_connected(inputs=rnn_outputs, 
                                               num_outputs=vocab_size, 
                                               activation_fn = None,
                                               weights_initializer = tf.truncated_normal_initializer(stddev=0.1),
                                               biases_initializer = tf.zeros_initializer())
    
    return logits, final_state

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_build_nn(build_nn)
Tests Passed

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.

For exmple, get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2) would return a Numpy array of the following:

[
  # First Batch
  [
    # Batch of Input
    [[ 1  2], [ 7  8], [13 14]]
    # Batch of targets
    [[ 2  3], [ 8  9], [14 15]]
  ]

  # Second Batch
  [
    # Batch of Input
    [[ 3  4], [ 9 10], [15 16]]
    # Batch of targets
    [[ 4  5], [10 11], [16 17]]
  ]

  # Third Batch
  [
    # Batch of Input
    [[ 5  6], [11 12], [17 18]]
    # Batch of targets
    [[ 6  7], [12 13], [18  1]]
  ]
]

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.

In [19]:
hide_code
def get_batches(int_text, batch_size, seq_length):
    """
    Return batches of input and target
    :param int_text: Text with the words replaced by their ids
    :param batch_size: The size of batch
    :param seq_length: The length of sequence
    :return: Batches as a Numpy array
    """
    # TODO: Implement Function
    
    slice_size = batch_size * seq_length
    n_batches = int(len(int_text) / slice_size)
    
    # targets == features, shifted one character over
    X = int_text[: n_batches*slice_size]
    y = X[1:] + [X[0]]
    
    X = np.array(X).reshape(batch_size, -1)
    y = np.array(y).reshape(batch_size, -1)

    X = np.split(X, n_batches, 1)
    y = np.split(y, n_batches, 1)
    
    return np.array(list(zip(X, y)))

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_get_batches(get_batches)
Tests Passed

Neural Network Training

Hyperparameters

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.
In [20]:
hide_code
num_epochs = 800
batch_size = 128
rnn_size = 256
embed_dim = 128
seq_length = 32
learning_rate = 0.001

# Show stats for every n number of batches
show_every_n_batches = 128

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
save_dir = './save'

Build the Graph

Build the graph using the neural network you implemented.

In [21]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""

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)

    # Probabilities for generating words
    probs = tf.nn.softmax(logits, name='probs')

    # Loss function
    cost = seq2seq.sequence_loss(
        logits,
        targets,
        tf.ones([input_data_shape[0], input_data_shape[1]]))

    # Optimizer
    optimizer = tf.train.AdamOptimizer(lr)

    # Gradient Clipping
    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)

Train

Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forums to see if anyone is having the same problem.

In [22]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""

batches = get_batches(int_text, batch_size, seq_length)

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

    for epoch_i in range(num_epochs):
        state = sess.run(initial_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, _ = sess.run([cost, final_state, train_op], feed)

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

    # Save Model
    saver = tf.train.Saver()
    saver.save(sess, save_dir)
    print('Model Trained and Saved')
Epoch   0 Batch    0/16   train_loss = 8.830
Epoch   8 Batch    0/16   train_loss = 5.281
Epoch  16 Batch    0/16   train_loss = 4.811
Epoch  24 Batch    0/16   train_loss = 4.483
Epoch  32 Batch    0/16   train_loss = 4.223
Epoch  40 Batch    0/16   train_loss = 3.997
Epoch  48 Batch    0/16   train_loss = 3.788
Epoch  56 Batch    0/16   train_loss = 3.610
Epoch  64 Batch    0/16   train_loss = 3.445
Epoch  72 Batch    0/16   train_loss = 3.275
Epoch  80 Batch    0/16   train_loss = 3.083
Epoch  88 Batch    0/16   train_loss = 2.956
Epoch  96 Batch    0/16   train_loss = 2.853
Epoch 104 Batch    0/16   train_loss = 2.675
Epoch 112 Batch    0/16   train_loss = 2.579
Epoch 120 Batch    0/16   train_loss = 2.408
Epoch 128 Batch    0/16   train_loss = 2.292
Epoch 136 Batch    0/16   train_loss = 2.413
Epoch 144 Batch    0/16   train_loss = 2.101
Epoch 152 Batch    0/16   train_loss = 2.145
Epoch 160 Batch    0/16   train_loss = 1.953
Epoch 168 Batch    0/16   train_loss = 1.821
Epoch 176 Batch    0/16   train_loss = 1.735
Epoch 184 Batch    0/16   train_loss = 1.708
Epoch 192 Batch    0/16   train_loss = 1.577
Epoch 200 Batch    0/16   train_loss = 1.489
Epoch 208 Batch    0/16   train_loss = 1.463
Epoch 216 Batch    0/16   train_loss = 1.493
Epoch 224 Batch    0/16   train_loss = 1.349
Epoch 232 Batch    0/16   train_loss = 1.283
Epoch 240 Batch    0/16   train_loss = 1.188
Epoch 248 Batch    0/16   train_loss = 1.135
Epoch 256 Batch    0/16   train_loss = 1.083
Epoch 264 Batch    0/16   train_loss = 1.036
Epoch 272 Batch    0/16   train_loss = 1.016
Epoch 280 Batch    0/16   train_loss = 0.982
Epoch 288 Batch    0/16   train_loss = 0.926
Epoch 296 Batch    0/16   train_loss = 0.895
Epoch 304 Batch    0/16   train_loss = 0.830
Epoch 312 Batch    0/16   train_loss = 0.807
Epoch 320 Batch    0/16   train_loss = 0.832
Epoch 328 Batch    0/16   train_loss = 0.774
Epoch 336 Batch    0/16   train_loss = 0.700
Epoch 344 Batch    0/16   train_loss = 0.672
Epoch 352 Batch    0/16   train_loss = 0.634
Epoch 360 Batch    0/16   train_loss = 0.635
Epoch 368 Batch    0/16   train_loss = 0.613
Epoch 376 Batch    0/16   train_loss = 0.559
Epoch 384 Batch    0/16   train_loss = 0.538
Epoch 392 Batch    0/16   train_loss = 0.567
Epoch 400 Batch    0/16   train_loss = 0.530
Epoch 408 Batch    0/16   train_loss = 0.498
Epoch 416 Batch    0/16   train_loss = 0.455
Epoch 424 Batch    0/16   train_loss = 0.443
Epoch 432 Batch    0/16   train_loss = 0.450
Epoch 440 Batch    0/16   train_loss = 0.428
Epoch 448 Batch    0/16   train_loss = 0.393
Epoch 456 Batch    0/16   train_loss = 0.367
Epoch 464 Batch    0/16   train_loss = 0.351
Epoch 472 Batch    0/16   train_loss = 0.345
Epoch 480 Batch    0/16   train_loss = 0.346
Epoch 488 Batch    0/16   train_loss = 0.340
Epoch 496 Batch    0/16   train_loss = 0.346
Epoch 504 Batch    0/16   train_loss = 0.354
Epoch 512 Batch    0/16   train_loss = 0.312
Epoch 520 Batch    0/16   train_loss = 0.317
Epoch 528 Batch    0/16   train_loss = 0.285
Epoch 536 Batch    0/16   train_loss = 0.283
Epoch 544 Batch    0/16   train_loss = 0.270
Epoch 552 Batch    0/16   train_loss = 0.268
Epoch 560 Batch    0/16   train_loss = 0.283
Epoch 568 Batch    0/16   train_loss = 0.257
Epoch 576 Batch    0/16   train_loss = 0.246
Epoch 584 Batch    0/16   train_loss = 0.244
Epoch 592 Batch    0/16   train_loss = 0.252
Epoch 600 Batch    0/16   train_loss = 0.225
Epoch 608 Batch    0/16   train_loss = 0.232
Epoch 616 Batch    0/16   train_loss = 0.245
Epoch 624 Batch    0/16   train_loss = 0.224
Epoch 632 Batch    0/16   train_loss = 0.221
Epoch 640 Batch    0/16   train_loss = 0.197
Epoch 648 Batch    0/16   train_loss = 0.206
Epoch 656 Batch    0/16   train_loss = 0.203
Epoch 664 Batch    0/16   train_loss = 0.210
Epoch 672 Batch    0/16   train_loss = 0.199
Epoch 680 Batch    0/16   train_loss = 0.194
Epoch 688 Batch    0/16   train_loss = 0.217
Epoch 696 Batch    0/16   train_loss = 0.199
Epoch 704 Batch    0/16   train_loss = 0.202
Epoch 712 Batch    0/16   train_loss = 0.203
Epoch 720 Batch    0/16   train_loss = 0.184
Epoch 728 Batch    0/16   train_loss = 0.192
Epoch 736 Batch    0/16   train_loss = 0.200
Epoch 744 Batch    0/16   train_loss = 0.182
Epoch 752 Batch    0/16   train_loss = 0.178
Epoch 760 Batch    0/16   train_loss = 0.176
Epoch 768 Batch    0/16   train_loss = 0.185
Epoch 776 Batch    0/16   train_loss = 0.176
Epoch 784 Batch    0/16   train_loss = 0.174
Epoch 792 Batch    0/16   train_loss = 0.169
Model Trained and Saved

Save Parameters

Save seq_length and save_dir for generating a new TV script.

In [23]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""

# Save parameters for checkpoint
save_params((seq_length, save_dir))

Checkpoint 2

In [24]:
hide_code
"""DON'T MODIFY ANYTHING IN THIS CELL"""

_, vocab_to_int, int_to_vocab, token_dict = load_preprocess()
seq_length, load_dir = load_params()

Implement Generate Functions

Get Tensors

Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors 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)

In [25]:
hide_code
def get_tensors(loaded_graph):
    """
    Get input, initial state, final state, and probabilities tensor from <loaded_graph>
    :param loaded_graph: TensorFlow graph loaded from file
    :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
    """
    # TODO: Implement Function
    
    input_tensor = loaded_graph.get_tensor_by_name('input:0')
    initial_state_tensor = loaded_graph.get_tensor_by_name('initial_state:0')
    final_state_tensor = loaded_graph.get_tensor_by_name('final_state:0')
    probs_tensor = loaded_graph.get_tensor_by_name('probs:0')
    
    return input_tensor, initial_state_tensor, final_state_tensor, probs_tensor

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_get_tensors(get_tensors)
Tests Passed

Choose Word

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

In [26]:
hide_code
def pick_word(probabilities, int_to_vocab):
    """
    Pick the next word in the generated text
    :param probabilities: Probabilites of the next word
    :param int_to_vocab: Dictionary of word ids as the keys and words as the values
    :return: String of the predicted word
    """
    # TODO: Implement Function

    return int_to_vocab[np.argmax(probabilities)]

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
test_pick_word(pick_word)
Tests Passed

Generate TV Script

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

In [27]:
hide_code
gen_length = 200
# homer_simpson, moe_szyslak, or bart_simpson
prime_word = 'moe_szyslak'

"""DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE"""
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
    # Load saved model
    loader = tf.train.import_meta_graph(load_dir + '.meta')
    loader.restore(sess, load_dir)

    # Get Tensors from loaded model
    input_text, initial_state, final_state, probs = get_tensors(loaded_graph)

    # Sentences generation setup
    gen_sentences = [prime_word + ':']
    prev_state = sess.run(initial_state, {input_text: np.array([[1]])})

    # Generate sentences
    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])

        # Get Prediction
        probabilities, prev_state = sess.run(
            [probs, final_state],
            {input_text: dyn_input, initial_state: prev_state})
        
        pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)

        gen_sentences.append(pred_word)
    
    # Remove tokens
    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('( ', '(')
        
    print(tv_script)
moe_szyslak:(stunned) nigeria?
moe_szyslak:(repressed rage) homer, can i speak to you in private?
homer_simpson: can i try it?
moe_szyslak: eh, i think it was tonight at least it play of the place is lenny, her.
lenny_leonard: just like i want a car is to an old boyfriend for save 'em?
carl_carlson: i-i got and you've never seen this town. you know how i want you to sell it with the kids are yourself.
homer_simpson:(ashamed) i am. i really ain't sick of that.
kemi: i can--
homer_simpson:(shrieks) i am so if it is, okay myself here?
homer_simpson: seymour.
homer_simpson: it was real cold and--
lisa_simpson: that's the perfect!
moe_szyslak: get out and take this home. / now, uh, let me look angry how much he can go.
young_marge: why uh. how are you man?
krusty_the_clown: the sanitation folks? turn him.
moe_szyslak: and i will have this forehead(points)

The TV Script is Nonsensical

It's ok if the TV script doesn't make any sense. We trained on less than a megabyte of text. In order to get good results, you'll have to use a smaller vocabulary or get more data. Luckly there's more data! As we mentioned in the begging of this project, this is a subset of another dataset. We didn't have you train on all the data, because that would take too long. However, you are free to train your neural network on all the data. After you complete the project, of course.

Submitting This Project

When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_tv_script_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.