{
 "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": 1,
   "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": 19,
   "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": 21,
   "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": {
    "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": 2,
   "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": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "def get_inputs():\n",
    "    \"\"\"\n",
    "    Create TF Placeholders for input, targets, and learning rate.\n",
    "    :return: Tuple (input, targets, learning rate)\n",
    "    \"\"\"\n",
    "    # TODO: Implement Function\n",
    "    return None, None, None\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": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "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",
    "    # TODO: Implement Function\n",
    "    return None, None\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": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "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",
    "    # 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_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": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "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",
    "    # TODO: Implement Function\n",
    "    return None, None\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": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "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",
    "    # TODO: Implement Function\n",
    "    return None, None\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": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "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",
    "    # 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_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
}
