You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1341 lines
41 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"# TV Script Generation\n",
"In this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at [Moe's Tavern](https://simpsonswiki.com/wiki/Moe's_Tavern).\n",
"## Get the Data\n",
"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.."
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import helper\n",
"\n",
"data_dir = './data/simpsons/moes_tavern_lines.txt'\n",
"text = helper.load_data(data_dir)\n",
"# Ignore notice, since we don't use it for analysing the data\n",
"text = text[81:]"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Explore the Data\n",
"Play around with `view_sentence_range` to view different parts of the data."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Dataset Stats\n",
"Roughly the number of unique words: 11492\n",
"Number of scenes: 262\n",
"Average number of sentences in each scene: 15.248091603053435\n",
"Number of lines: 4257\n",
"Average number of words in each line: 11.50434578341555\n",
"\n",
"The sentences 0 to 10:\n",
"Moe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink.\n",
"Bart_Simpson: Eh, yeah, hello, is Mike there? Last name, Rotch.\n",
"Moe_Szyslak: (INTO PHONE) Hold on, I'll check. (TO BARFLIES) Mike Rotch. Mike Rotch. Hey, has anybody seen Mike Rotch, lately?\n",
"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.\n",
"Moe_Szyslak: What's the matter Homer? You're not your normal effervescent self.\n",
"Homer_Simpson: I got my problems, Moe. Give me another one.\n",
"Moe_Szyslak: Homer, hey, you should not drink to forget your problems.\n",
"Barney_Gumble: Yeah, you should only drink to enhance your social skills.\n",
"\n",
"\n"
]
}
],
"source": [
"view_sentence_range = (0, 10)\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import numpy as np\n",
"\n",
"print('Dataset Stats')\n",
"print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n",
"scenes = text.split('\\n\\n')\n",
"print('Number of scenes: {}'.format(len(scenes)))\n",
"sentence_count_scene = [scene.count('\\n') for scene in scenes]\n",
"print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene)))\n",
"\n",
"sentences = [sentence for scene in scenes for sentence in scene.split('\\n')]\n",
"print('Number of lines: {}'.format(len(sentences)))\n",
"word_count_sentence = [len(sentence.split()) for sentence in sentences]\n",
"print('Average number of words in each line: {}'.format(np.average(word_count_sentence)))\n",
"\n",
"print()\n",
"print('The sentences {} to {}:'.format(*view_sentence_range))\n",
"print('\\n'.join(text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Implement Preprocessing Functions\n",
"The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:\n",
"- Lookup Table\n",
"- Tokenize Punctuation\n",
"\n",
"### Lookup Table\n",
"To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:\n",
"- Dictionary to go from the words to an id, we'll call `vocab_to_int`\n",
"- Dictionary to go from the id to word, we'll call `int_to_vocab`\n",
"\n",
"Return these dictionaries in the following tuple `(vocab_to_int, int_to_vocab)`"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"import numpy as np\n",
"import problem_unittests as tests\n",
"\n",
"def create_lookup_tables(text):\n",
" \"\"\"\n",
" Create lookup tables for vocabulary\n",
" :param text: The text of tv scripts split into words\n",
" :return: A tuple of dicts (vocab_to_int, int_to_vocab)\n",
" \"\"\"\n",
" vocab = set(text)\n",
" \n",
" vocab_to_int = {word: index for index, word in enumerate(vocab)}\n",
" int_to_vocab = {index: word for (word, index) in vocab_to_int.items()}\n",
" \n",
" return vocab_to_int, int_to_vocab\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_create_lookup_tables(create_lookup_tables)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Tokenize Punctuation\n",
"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!\".\n",
"\n",
"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:\n",
"- Period ( . )\n",
"- Comma ( , )\n",
"- Quotation Mark ( \" )\n",
"- Semicolon ( ; )\n",
"- Exclamation mark ( ! )\n",
"- Question mark ( ? )\n",
"- Left Parentheses ( ( )\n",
"- Right Parentheses ( ) )\n",
"- Dash ( -- )\n",
"- Return ( \\n )\n",
"\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||\"."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def token_lookup():\n",
" \"\"\"\n",
" Generate a dict to turn punctuation into a token.\n",
" :return: Tokenize dictionary where the key is the punctuation and the value is the token\n",
" \"\"\"\n",
" \n",
" return {\n",
" '.': '||period||',\n",
" ',': '||comma||',\n",
" '\"': '||quotation_mark||',\n",
" ';': '||semicolon||',\n",
" '!': '||exclamation_mark||',\n",
" '?': '||question_mark||',\n",
" '(': '||left_parentheses',\n",
" ')': '||right_parentheses',\n",
" '--': '||dash||',\n",
" '\\n': '||return||'\n",
" }\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_tokenize(token_lookup)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Preprocess all the data and save it\n",
"Running the code cell below will preprocess all the data and save it to file."
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"# Preprocess Training, Validation, and Testing Data\n",
"helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"# Check Point\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import helper\n",
"import numpy as np\n",
"import problem_unittests as tests\n",
"\n",
"int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Extra hyper parameters"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from collections import namedtuple\n",
"\n",
"hyper_params = (('embedding_size', 128),\n",
" ('lstm_layers', 2),\n",
" ('keep_prob', 0.5)\n",
" )\n",
"\n",
"\n",
"\n",
"\n",
"Hyper = namedtuple('Hyper', map(lambda x: x[0], hyper_params))\n",
"HYPER = Hyper(*list(map(lambda x: x[1], hyper_params)))\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Build the Neural Network\n",
"You'll build the components necessary to build a RNN by implementing the following functions below:\n",
"- get_inputs\n",
"- get_init_cell\n",
"- get_embed\n",
"- build_rnn\n",
"- build_nn\n",
"- get_batches\n",
"\n",
"### Check the Version of TensorFlow and Access to GPU"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"TensorFlow Version: 1.0.0\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/home/spike/.pyenv/versions/3.5.1/envs/ml/lib/python3.5/site-packages/ipykernel/__main__.py:14: UserWarning: No GPU found. Please use a GPU to train your neural network.\n"
]
}
],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"from distutils.version import LooseVersion\n",
"import warnings\n",
"import tensorflow as tf\n",
"\n",
"# Check TensorFlow Version\n",
"assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer'\n",
"print('TensorFlow Version: {}'.format(tf.__version__))\n",
"\n",
"# Check for a GPU\n",
"if not tf.test.gpu_device_name():\n",
" warnings.warn('No GPU found. Please use a GPU to train your neural network.')\n",
"else:\n",
" print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Input\n",
"Implement the `get_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n",
"- Input text placeholder named \"input\" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter.\n",
"- Targets placeholder\n",
"- Learning Rate placeholder\n",
"\n",
"Return the placeholders in the following the tuple `(Input, Targets, LearingRate)`"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def get_inputs():\n",
" \"\"\"\n",
" Create TF Placeholders for input, targets, and learning rate.\n",
" :return: Tuple (input, targets, learning rate)\n",
" \"\"\"\n",
" \n",
" # We use shape [None, None] to feed any batch size and any sequence length\n",
" input_placeholder = tf.placeholder(tf.int32, [None, None],name='input')\n",
" \n",
" # Targets are [batch_size, seq_length]\n",
" targets_placeholder = tf.placeholder(tf.int32, [None, None]) \n",
" \n",
" \n",
" learning_rate_placeholder = tf.placeholder(tf.float32)\n",
" return input_placeholder, targets_placeholder, learning_rate_placeholder\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_get_inputs(get_inputs)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Build RNN Cell and Initialize\n",
"Stack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell).\n",
"- The Rnn size should be set using `rnn_size`\n",
"- Initalize Cell State using the MultiRNNCell's [`zero_state()`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell#zero_state) function\n",
" - Apply the name \"initial_state\" to the initial state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\n",
"\n",
"Return the cell and initial state in the following tuple `(Cell, InitialState)`"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def get_init_cell(batch_size, rnn_size):\n",
" \"\"\"\n",
" Create an RNN Cell and initialize it.\n",
" :param batch_size: Size of batches\n",
" :param rnn_size: Size of RNNs\n",
" :return: Tuple (cell, initialize state)\n",
" \"\"\"\n",
" lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)\n",
" \n",
" # add a dropout wrapper\n",
" drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=HYPER.keep_prob)\n",
" \n",
" #cell = tf.contrib.rnn.MultiRNNCell([drop] * HYPER.lstm_layers)\n",
" \n",
" cell = tf.contrib.rnn.MultiRNNCell([lstm] * HYPER.lstm_layers)\n",
" \n",
" initial_state = cell.zero_state(batch_size, tf.float32)\n",
" initial_state = tf.identity(initial_state, name='initial_state')\n",
" \n",
" return cell, initial_state\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_get_init_cell(get_init_cell)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Word Embedding\n",
"Apply embedding to `input_data` using TensorFlow. Return the embedded sequence."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def get_embed(input_data, vocab_size, embed_dim):\n",
" \"\"\"\n",
" Create embedding for <input_data>.\n",
" :param input_data: TF placeholder for text input.\n",
" :param vocab_size: Number of words in vocabulary.\n",
" :param embed_dim: Number of embedding dimensions\n",
" :return: Embedded input.\n",
" \"\"\"\n",
" embeddings = tf.Variable(\n",
" tf.random_uniform([vocab_size, embed_dim], -1.0, 1.0)\n",
" )\n",
" \n",
" embed = tf.nn.embedding_lookup(embeddings, input_data)\n",
" \n",
" return embed\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_get_embed(get_embed)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Build RNN\n",
"You created a RNN Cell in the `get_init_cell()` function. Time to use the cell to create a RNN.\n",
"- Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn)\n",
" - Apply the name \"final_state\" to the final state using [`tf.identity()`](https://www.tensorflow.org/api_docs/python/tf/identity)\n",
"\n",
"Return the outputs and final_state state in the following tuple `(Outputs, FinalState)` "
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def build_rnn(cell, inputs):\n",
" \"\"\"\n",
" Create a RNN using a RNN Cell\n",
" :param cell: RNN Cell\n",
" :param inputs: Input text data\n",
" :return: Tuple (Outputs, Final State)\n",
" \"\"\"\n",
" ## NOTES\n",
" # dynamic rnn automatically takes the seq size in dim=1 [batch_size, max_time, ...] time_major==false (default)\n",
" \n",
" outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32)\n",
" final_state = tf.identity(final_state, name='final_state')\n",
" \n",
" \n",
" return outputs, final_state\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_build_rnn(build_rnn)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Build the Neural Network\n",
"Apply the functions you implemented above to:\n",
"- Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function.\n",
"- Build RNN using `cell` and your `build_rnn(cell, inputs)` function.\n",
"- Apply a fully connected layer with a linear activation and `vocab_size` as the number of outputs.\n",
"\n",
"Return the logits and final state in the following tuple (Logits, FinalState) "
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tests Passed\n"
]
}
],
"source": [
"def build_nn(cell, rnn_size, input_data, vocab_size):\n",
" \"\"\"\n",
" Build part of the neural network\n",
" :param cell: RNN cell\n",
" :param rnn_size: Size of rnns\n",
" :param input_data: Input data\n",
" :param vocab_size: Vocabulary size\n",
" :return: Tuple (Logits, FinalState)\n",
" \"\"\"\n",
" \n",
" num_outputs = vocab_size\n",
" batch_size = input_data.get_shape().as_list()[0]\n",
" \n",
" embed = get_embed(input_data, vocab_size, HYPER.embedding_size)\n",
" \n",
" \n",
" ## NOTES\n",
" # dynamic rnn automatically takes the seq size in dim=1 [batch_size, max_time, ...] see: time_major==false (default)\n",
" \n",
" ## Output shape\n",
" ## [batch_size, time_step, rnn_size]\n",
" raw_rnn_outputs, final_state = build_rnn(cell, embed)\n",
" \n",
" # Put outputs in rows\n",
" # make the output into [batch_size*time_step, rnn_size] for easy matmul\n",
" outputs = tf.reshape(raw_rnn_outputs, [-1, rnn_size])\n",
" \n",
" \n",
" # Question, why are we using linear activation and not softmax ?\n",
" # My Guess: because seq2seq.sequence_loss has an efficient way to calculate the loss directly from logits \n",
" with tf.variable_scope('linear_layer'):\n",
" linear_w = tf.Variable(tf.truncated_normal((rnn_size, num_outputs), stddev=0.1), name='linear_w')\n",
" linear_b = tf.Variable(tf.zeros(num_outputs), name='linear_b')\n",
" \n",
" logits = tf.matmul(outputs, linear_w) + linear_b\n",
" \n",
" # Reshape the logits back into the original input shape -> [batch_size, seq_len, num_classes]\n",
" # We do this beceause the loss function seq2seq.sequence_loss takes as logits a shape of [batch_size,seq_len,num_decoded_symbols]\n",
" logits = tf.reshape(logits, [batch_size, -1, num_outputs])\n",
" \n",
" \n",
" return logits, final_state\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_build_nn(build_nn)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Batches\n",
"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:\n",
"- The first element is a single batch of **input** with the shape `[batch size, sequence length]`\n",
"- The second element is a single batch of **targets** with the shape `[batch size, sequence length]`\n",
"\n",
"If you can't fill the last batch with enough data, drop the last batch.\n",
"\n",
"For exmple, `get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2, 3)` would return a Numpy array of the following:\n",
"```\n",
"[\n",
" # First Batch\n",
" [\n",
" # Batch of Input\n",
" [[ 1 2 3], [ 7 8 9]],\n",
" # Batch of targets\n",
" [[ 2 3 4], [ 8 9 10]]\n",
" ],\n",
" \n",
" # Second Batch\n",
" [\n",
" # Batch of Input\n",
" [[ 4 5 6], [10 11 12]],\n",
" # Batch of targets\n",
" [[ 5 6 7], [11 12 13]]\n",
" ]\n",
"]\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 238,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(7, 1280)\n",
"[[ 0 1 2 3 4]\n",
" [ 5 6 7 8 9]\n",
" [ 10 11 12 13 14]\n",
" [ 15 16 17 18 19]\n",
" [ 20 21 22 23 24]\n",
" [ 25 26 27 28 29]\n",
" [ 30 31 32 33 34]\n",
" [ 35 36 37 38 39]\n",
" [ 40 41 42 43 44]\n",
" [ 45 46 47 48 49]\n",
" [ 50 51 52 53 54]\n",
" [ 55 56 57 58 59]\n",
" [ 60 61 62 63 64]\n",
" [ 65 66 67 68 69]\n",
" [ 70 71 72 73 74]\n",
" [ 75 76 77 78 79]\n",
" [ 80 81 82 83 84]\n",
" [ 85 86 87 88 89]\n",
" [ 90 91 92 93 94]\n",
" [ 95 96 97 98 99]\n",
" [100 101 102 103 104]\n",
" [105 106 107 108 109]\n",
" [110 111 112 113 114]\n",
" [115 116 117 118 119]\n",
" [120 121 122 123 124]\n",
" [125 126 127 128 129]\n",
" [130 131 132 133 134]\n",
" [135 136 137 138 139]\n",
" [140 141 142 143 144]\n",
" [145 146 147 148 149]\n",
" [150 151 152 153 154]\n",
" [155 156 157 158 159]\n",
" [160 161 162 163 164]\n",
" [165 166 167 168 169]\n",
" [170 171 172 173 174]\n",
" [175 176 177 178 179]\n",
" [180 181 182 183 184]\n",
" [185 186 187 188 189]\n",
" [190 191 192 193 194]\n",
" [195 196 197 198 199]\n",
" [200 201 202 203 204]\n",
" [205 206 207 208 209]\n",
" [210 211 212 213 214]\n",
" [215 216 217 218 219]\n",
" [220 221 222 223 224]\n",
" [225 226 227 228 229]\n",
" [230 231 232 233 234]\n",
" [235 236 237 238 239]\n",
" [240 241 242 243 244]\n",
" [245 246 247 248 249]\n",
" [250 251 252 253 254]\n",
" [255 256 257 258 259]\n",
" [260 261 262 263 264]\n",
" [265 266 267 268 269]\n",
" [270 271 272 273 274]\n",
" [275 276 277 278 279]\n",
" [280 281 282 283 284]\n",
" [285 286 287 288 289]\n",
" [290 291 292 293 294]\n",
" [295 296 297 298 299]\n",
" [300 301 302 303 304]\n",
" [305 306 307 308 309]\n",
" [310 311 312 313 314]\n",
" [315 316 317 318 319]\n",
" [320 321 322 323 324]\n",
" [325 326 327 328 329]\n",
" [330 331 332 333 334]\n",
" [335 336 337 338 339]\n",
" [340 341 342 343 344]\n",
" [345 346 347 348 349]\n",
" [350 351 352 353 354]\n",
" [355 356 357 358 359]\n",
" [360 361 362 363 364]\n",
" [365 366 367 368 369]\n",
" [370 371 372 373 374]\n",
" [375 376 377 378 379]\n",
" [380 381 382 383 384]\n",
" [385 386 387 388 389]\n",
" [390 391 392 393 394]\n",
" [395 396 397 398 399]\n",
" [400 401 402 403 404]\n",
" [405 406 407 408 409]\n",
" [410 411 412 413 414]\n",
" [415 416 417 418 419]\n",
" [420 421 422 423 424]\n",
" [425 426 427 428 429]\n",
" [430 431 432 433 434]\n",
" [435 436 437 438 439]\n",
" [440 441 442 443 444]\n",
" [445 446 447 448 449]\n",
" [450 451 452 453 454]\n",
" [455 456 457 458 459]\n",
" [460 461 462 463 464]\n",
" [465 466 467 468 469]\n",
" [470 471 472 473 474]\n",
" [475 476 477 478 479]\n",
" [480 481 482 483 484]\n",
" [485 486 487 488 489]\n",
" [490 491 492 493 494]\n",
" [495 496 497 498 499]\n",
" [500 501 502 503 504]\n",
" [505 506 507 508 509]\n",
" [510 511 512 513 514]\n",
" [515 516 517 518 519]\n",
" [520 521 522 523 524]\n",
" [525 526 527 528 529]\n",
" [530 531 532 533 534]\n",
" [535 536 537 538 539]\n",
" [540 541 542 543 544]\n",
" [545 546 547 548 549]\n",
" [550 551 552 553 554]\n",
" [555 556 557 558 559]\n",
" [560 561 562 563 564]\n",
" [565 566 567 568 569]\n",
" [570 571 572 573 574]\n",
" [575 576 577 578 579]\n",
" [580 581 582 583 584]\n",
" [585 586 587 588 589]\n",
" [590 591 592 593 594]\n",
" [595 596 597 598 599]\n",
" [600 601 602 603 604]\n",
" [605 606 607 608 609]\n",
" [610 611 612 613 614]\n",
" [615 616 617 618 619]\n",
" [620 621 622 623 624]\n",
" [625 626 627 628 629]\n",
" [630 631 632 633 634]\n",
" [635 636 637 638 639]]\n",
"Tests Passed\n"
]
}
],
"source": [
"def get_batches(int_text, batch_size, seq_length):\n",
" \"\"\"\n",
" Return batches of input and target\n",
" :param int_text: Text with the words replaced by their ids\n",
" :param batch_size: The size of batch\n",
" :param seq_length: The length of sequence\n",
" :return: Batches as a Numpy array\n",
" \"\"\"\n",
" \n",
" slice_size = batch_size * seq_length\n",
" n_batches = int(len(int_text)/slice_size)\n",
" \n",
" # input part\n",
" _inputs = np.array(int_text[:n_batches*slice_size])\n",
" \n",
" # target part\n",
" _targets = np.array(int_text[1:n_batches*slice_size + 1])\n",
" \n",
"\n",
" # Go through all inputs, targets and split them into batch_size*seq_len list of items\n",
" # [batch, batch, ...]\n",
" inputs, targets = np.split(_inputs, n_batches), np.split(_targets, n_batches)\n",
" \n",
" # concat inputs and targets\n",
" batches = np.c_[inputs, targets]\n",
" print(batches.shape)\n",
" \n",
" # Reshape into final batches output\n",
" batches = batches.reshape((-1, 2, batch_size, seq_length))\n",
"\n",
" print(batches[0][0])\n",
"\n",
" \n",
" return batches\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_get_batches(get_batches)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Neural Network Training\n",
"### Hyperparameters\n",
"Tune the following parameters:\n",
"\n",
"- Set `num_epochs` to the number of epochs.\n",
"- Set `batch_size` to the batch size.\n",
"- Set `rnn_size` to the size of the RNNs.\n",
"- Set `seq_length` to the length of sequence.\n",
"- Set `learning_rate` to the learning rate.\n",
"- Set `show_every_n_batches` to the number of batches the neural network should print progress."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Number of Epochs\n",
"num_epochs = None\n",
"# Batch Size\n",
"batch_size = None\n",
"# RNN Size\n",
"rnn_size = None\n",
"# Sequence Length\n",
"seq_length = None\n",
"# Learning Rate\n",
"learning_rate = None\n",
"# Show stats for every n number of batches\n",
"show_every_n_batches = None\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"save_dir = './save'"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Build the Graph\n",
"Build the graph using the neural network you implemented."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"from tensorflow.contrib import seq2seq\n",
"\n",
"train_graph = tf.Graph()\n",
"with train_graph.as_default():\n",
" vocab_size = len(int_to_vocab)\n",
" input_text, targets, lr = get_inputs()\n",
" input_data_shape = tf.shape(input_text)\n",
" cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)\n",
" logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size)\n",
"\n",
" # Probabilities for generating words\n",
" probs = tf.nn.softmax(logits, name='probs')\n",
"\n",
" # Loss function\n",
" cost = seq2seq.sequence_loss(\n",
" logits,\n",
" targets,\n",
" tf.ones([input_data_shape[0], input_data_shape[1]]))\n",
"\n",
" # Optimizer\n",
" optimizer = tf.train.AdamOptimizer(lr)\n",
"\n",
" # Gradient Clipping\n",
" gradients = optimizer.compute_gradients(cost)\n",
" capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients]\n",
" train_op = optimizer.apply_gradients(capped_gradients)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Train\n",
"Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the [forms](https://discussions.udacity.com/) to see if anyone is having the same problem."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"batches = get_batches(int_text, batch_size, seq_length)\n",
"\n",
"with tf.Session(graph=train_graph) as sess:\n",
" sess.run(tf.global_variables_initializer())\n",
"\n",
" for epoch_i in range(num_epochs):\n",
" state = sess.run(initial_state, {input_text: batches[0][0]})\n",
"\n",
" for batch_i, (x, y) in enumerate(batches):\n",
" feed = {\n",
" input_text: x,\n",
" targets: y,\n",
" initial_state: state,\n",
" lr: learning_rate}\n",
" train_loss, state, _ = sess.run([cost, final_state, train_op], feed)\n",
"\n",
" # Show every <show_every_n_batches> batches\n",
" if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0:\n",
" print('Epoch {:>3} Batch {:>4}/{} train_loss = {:.3f}'.format(\n",
" epoch_i,\n",
" batch_i,\n",
" len(batches),\n",
" train_loss))\n",
"\n",
" # Save Model\n",
" saver = tf.train.Saver()\n",
" saver.save(sess, save_dir)\n",
" print('Model Trained and Saved')"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Save Parameters\n",
"Save `seq_length` and `save_dir` for generating a new TV script."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"# Save parameters for checkpoint\n",
"helper.save_params((seq_length, save_dir))"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"# Checkpoint"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL\n",
"\"\"\"\n",
"import tensorflow as tf\n",
"import numpy as np\n",
"import helper\n",
"import problem_unittests as tests\n",
"\n",
"_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\n",
"seq_length, load_dir = helper.load_params()"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Implement Generate Functions\n",
"### Get Tensors\n",
"Get tensors from `loaded_graph` using the function [`get_tensor_by_name()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_tensor_by_name). Get the tensors using the following names:\n",
"- \"input:0\"\n",
"- \"initial_state:0\"\n",
"- \"final_state:0\"\n",
"- \"probs:0\"\n",
"\n",
"Return the tensors in the following tuple `(InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)` "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"def get_tensors(loaded_graph):\n",
" \"\"\"\n",
" Get input, initial state, final state, and probabilities tensor from <loaded_graph>\n",
" :param loaded_graph: TensorFlow graph loaded from file\n",
" :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)\n",
" \"\"\"\n",
" # TODO: Implement Function\n",
" return None, None, None, None\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_get_tensors(get_tensors)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"### Choose Word\n",
"Implement the `pick_word()` function to select the next word using `probabilities`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"def pick_word(probabilities, int_to_vocab):\n",
" \"\"\"\n",
" Pick the next word in the generated text\n",
" :param probabilities: Probabilites of the next word\n",
" :param int_to_vocab: Dictionary of word ids as the keys and words as the values\n",
" :return: String of the predicted word\n",
" \"\"\"\n",
" # TODO: Implement Function\n",
" return None\n",
"\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"tests.test_pick_word(pick_word)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Generate TV Script\n",
"This will generate the TV script for you. Set `gen_length` to the length of TV script you want to generate."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"gen_length = 200\n",
"# homer_simpson, moe_szyslak, or Barney_Gumble\n",
"prime_word = 'moe_szyslak'\n",
"\n",
"\"\"\"\n",
"DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n",
"\"\"\"\n",
"loaded_graph = tf.Graph()\n",
"with tf.Session(graph=loaded_graph) as sess:\n",
" # Load saved model\n",
" loader = tf.train.import_meta_graph(load_dir + '.meta')\n",
" loader.restore(sess, load_dir)\n",
"\n",
" # Get Tensors from loaded model\n",
" input_text, initial_state, final_state, probs = get_tensors(loaded_graph)\n",
"\n",
" # Sentences generation setup\n",
" gen_sentences = [prime_word + ':']\n",
" prev_state = sess.run(initial_state, {input_text: np.array([[1]])})\n",
"\n",
" # Generate sentences\n",
" for n in range(gen_length):\n",
" # Dynamic Input\n",
" dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]\n",
" dyn_seq_length = len(dyn_input[0])\n",
"\n",
" # Get Prediction\n",
" probabilities, prev_state = sess.run(\n",
" [probs, final_state],\n",
" {input_text: dyn_input, initial_state: prev_state})\n",
" \n",
" pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)\n",
"\n",
" gen_sentences.append(pred_word)\n",
" \n",
" # Remove tokens\n",
" tv_script = ' '.join(gen_sentences)\n",
" for key, token in token_dict.items():\n",
" ending = ' ' if key in ['\\n', '(', '\"'] else ''\n",
" tv_script = tv_script.replace(' ' + token.lower(), key)\n",
" tv_script = tv_script.replace('\\n ', '\\n')\n",
" tv_script = tv_script.replace('( ', '(')\n",
" \n",
" print(tv_script)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"# The TV Script is Nonsensical\n",
"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](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data). 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.\n",
"# Submitting This Project\n",
"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."
]
}
],
"metadata": {
"hide_input": false,
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
},
"toc": {
"colors": {
"hover_highlight": "#DAA520",
"running_highlight": "#FF0000",
"selected_highlight": "#FFD700"
},
"moveMenuLeft": true,
"nav_menu": {
"height": "511px",
"width": "251px"
},
"navigate_menu": true,
"number_sections": true,
"sideBar": true,
"threshold": 4,
"toc_cell": false,
"toc_section_display": "block",
"toc_window_display": false
},
"widgets": {
"state": {},
"version": "1.1.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}