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.
tv-script-generation/.ipynb_checkpoints/dlnd_tv_script_generation-c...

1351 lines
42 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": 64,
"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": 14,
"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": 65,
"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": 16,
"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": 17,
"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": {
"deletable": true,
"editable": true
},
"source": [
"### Extra hyper parameters"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"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,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"TensorFlow Version: 1.0.0\n",
"Default GPU Device: /gpu:0\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": {
"deletable": true,
"editable": true
},
"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": 66,
"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.int64, [None, None],name='input')\n",
" \n",
" # Targets are [batch_size, seq_length]\n",
" targets_placeholder = tf.placeholder(tf.int64, [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": 67,
"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": 6,
"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": 68,
"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": 157,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"logits after reshape: Tensor(\"logits:0\", shape=(128, 5, 27), dtype=float32)\n",
"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",
" \n",
" \n",
" ## Not sure why the unit test was made without taking into \n",
" # account we are handling dynamic tensor shape that we need to infer\n",
" # at runtime, so I made an if statement just to pass the test case\n",
" #\n",
" # Some references: https://goo.gl/vD3egn\n",
" # https://goo.gl/E8vT2M \n",
" \n",
" if input_data.get_shape().as_list()[1] is not None:\n",
" batch_size = input_data.get_shape().as_list()[0]\n",
" seq_len = input_data.get_shape().as_list()[1]\n",
" \n",
" # Infer dynamic tensor shape of input\n",
" else:\n",
" input_dims = tf.shape(input_data)\n",
" batch_size = input_dims[0]\n",
" seq_len = input_dims[1]\n",
"\n",
" ###############\n",
" # This enables test passing\n",
" ###############\n",
" \n",
"\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], name='rnn_output')\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.05), 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",
" \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, seq_len, num_outputs], name='logits')\n",
" print('logits after reshape: ', logits)\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": 158,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"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",
" 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": 164,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Number of Epochs\n",
"num_epochs = 100\n",
"# Batch Size\n",
"batch_size = 128\n",
"# RNN Size\n",
"rnn_size = 256\n",
"# Sequence Length\n",
"seq_length = 100\n",
"# Learning Rate\n",
"learning_rate = 1e-3\n",
"# Show stats for every n number of batches\n",
"show_every_n_batches = 1\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": 77,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"6779"
]
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vocab_size"
]
},
{
"cell_type": "code",
"execution_count": 165,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"logits after reshape: Tensor(\"logits:0\", shape=(?, ?, 6779), dtype=float32)\n"
]
}
],
"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": "code",
"execution_count": 163,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 163,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"batches = get_batches(int_text, batch_size, seq_length)\n",
"len(batches)"
]
},
{
"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": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch 0 Batch 0/5 train_loss = 8.828\n",
"Epoch 0 Batch 1/5 train_loss = 8.793\n",
"Epoch 0 Batch 2/5 train_loss = 8.737\n",
"Epoch 0 Batch 3/5 train_loss = 8.602\n",
"Epoch 0 Batch 4/5 train_loss = 8.298\n",
"Epoch 1 Batch 0/5 train_loss = 7.938\n",
"Epoch 1 Batch 1/5 train_loss = 7.662\n",
"Epoch 1 Batch 2/5 train_loss = 7.364\n",
"Epoch 1 Batch 3/5 train_loss = 7.164\n",
"Epoch 1 Batch 4/5 train_loss = 6.899\n",
"Epoch 2 Batch 0/5 train_loss = 6.596\n",
"Epoch 2 Batch 1/5 train_loss = 6.462\n",
"Epoch 2 Batch 2/5 train_loss = 6.309\n",
"Epoch 2 Batch 3/5 train_loss = 6.330\n",
"Epoch 2 Batch 4/5 train_loss = 6.250\n",
"Epoch 3 Batch 0/5 train_loss = 6.055\n",
"Epoch 3 Batch 1/5 train_loss = 6.048\n",
"Epoch 3 Batch 2/5 train_loss = 6.012\n",
"Epoch 3 Batch 3/5 train_loss = 6.133\n",
"Epoch 3 Batch 4/5 train_loss = 6.159\n",
"Epoch 4 Batch 0/5 train_loss = 5.996\n",
"Epoch 4 Batch 1/5 train_loss = 6.021\n",
"Epoch 4 Batch 2/5 train_loss = 6.010\n",
"Epoch 4 Batch 3/5 train_loss = 6.125\n",
"Epoch 4 Batch 4/5 train_loss = 6.156\n",
"Epoch 5 Batch 0/5 train_loss = 5.978\n",
"Epoch 5 Batch 1/5 train_loss = 5.993\n",
"Epoch 5 Batch 2/5 train_loss = 5.977\n",
"Epoch 5 Batch 3/5 train_loss = 6.081\n",
"Epoch 5 Batch 4/5 train_loss = 6.103\n",
"Epoch 6 Batch 0/5 train_loss = 5.928\n",
"Epoch 6 Batch 1/5 train_loss = 5.950\n",
"Epoch 6 Batch 2/5 train_loss = 5.938\n",
"Epoch 6 Batch 3/5 train_loss = 6.053\n",
"Epoch 6 Batch 4/5 train_loss = 6.074\n",
"Epoch 7 Batch 0/5 train_loss = 5.909\n",
"Epoch 7 Batch 1/5 train_loss = 5.937\n",
"Epoch 7 Batch 2/5 train_loss = 5.925\n",
"Epoch 7 Batch 3/5 train_loss = 6.043\n",
"Epoch 7 Batch 4/5 train_loss = 6.060\n",
"Epoch 8 Batch 0/5 train_loss = 5.896\n",
"Epoch 8 Batch 1/5 train_loss = 5.922\n",
"Epoch 8 Batch 2/5 train_loss = 5.912\n",
"Epoch 8 Batch 3/5 train_loss = 6.028\n",
"Epoch 8 Batch 4/5 train_loss = 6.049\n",
"Epoch 9 Batch 0/5 train_loss = 5.889\n",
"Epoch 9 Batch 1/5 train_loss = 5.912\n",
"Epoch 9 Batch 2/5 train_loss = 5.906\n",
"Epoch 9 Batch 3/5 train_loss = 6.020\n",
"Epoch 9 Batch 4/5 train_loss = 6.042\n",
"Epoch 10 Batch 0/5 train_loss = 5.884\n",
"Epoch 10 Batch 1/5 train_loss = 5.905\n"
]
}
],
"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.2"
},
"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
}