{"id":18268425,"url":"https://github.com/coreyjs/tv-script-generator-rnn","last_synced_at":"2026-01-27T18:06:49.647Z","repository":{"id":73451021,"uuid":"341037410","full_name":"coreyjs/tv-script-generator-rnn","owner":"coreyjs","description":null,"archived":false,"fork":false,"pushed_at":"2021-02-23T18:15:28.000Z","size":2447,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-04T22:56:38.455Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/coreyjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-02-22T00:37:54.000Z","updated_at":"2021-02-23T18:15:30.000Z","dependencies_parsed_at":"2023-02-24T19:45:16.599Z","dependency_job_id":null,"html_url":"https://github.com/coreyjs/tv-script-generator-rnn","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/coreyjs/tv-script-generator-rnn","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Ftv-script-generator-rnn","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Ftv-script-generator-rnn/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Ftv-script-generator-rnn/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Ftv-script-generator-rnn/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coreyjs","download_url":"https://codeload.github.com/coreyjs/tv-script-generator-rnn/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Ftv-script-generator-rnn/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28817796,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-27T18:01:38.485Z","status":"ssl_error","status_checked_at":"2026-01-27T18:01:27.499Z","response_time":168,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-05T11:31:28.998Z","updated_at":"2026-01-27T18:06:49.619Z","avatar_url":"https://github.com/coreyjs.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# This notebook builds a RNN that can genrate tv scripts for the show Seinfeld\n\n\n---\n\n\n\n\n# TV Script Generation\n\nIn this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs.  You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons.  The Neural Network you'll build will generate a new ,\"fake\" TV script, based on patterns it recognizes in this training data.\n\n## Get the Data\n\nThe data is already provided for you in `./data/Seinfeld_Scripts.txt` and you're encouraged to open that file and look at the text. \n\u003e* As a first step, we'll load in this data and look at some samples. \n* Then, you'll be tasked with defining and training an RNN to generate a new script!\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# load in data\nimport helper\ndata_dir = './data/Seinfeld_Scripts.txt'\ntext = helper.load_data(data_dir)\n```\n\n## Explore the Data\nPlay around with `view_line_range` to view different parts of the data. This will give you a sense of the data you'll be working with. You can see, for example, that it is all lowercase text, and each new line of dialogue is separated by a newline character `\\n`.\n\n\n```python\nview_line_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()})))\n\nlines = text.split('\\n')\nprint('Number of lines: {}'.format(len(lines)))\nword_count_line = [len(line.split()) for line in lines]\nprint('Average number of words in each line: {}'.format(np.average(word_count_line)))\n\nprint()\nprint('The lines {} to {}:'.format(*view_line_range))\nprint('\\n'.join(text.split('\\n')[view_line_range[0]:view_line_range[1]]))\n```\n\n    Dataset Stats\n    Roughly the number of unique words: 46367\n    Number of lines: 109233\n    Average number of words in each line: 5.544240293684143\n    \n    The lines 0 to 10:\n    jerry: do you know what this is all about? do you know, why were here? to be out, this is out...and out is one of the single most enjoyable experiences of life. people...did you ever hear people talking about we should go out? this is what theyre talking about...this whole thing, were all out now, no one is home. not one person here is home, were all out! there are people trying to find us, they dont know where we are. (on an imaginary phone) did you ring?, i cant find him. where did he go? he didnt tell me where he was going. he must have gone out. you wanna go out you get ready, you pick out the clothes, right? you take the shower, you get all ready, get the cash, get your friends, the car, the spot, the reservation...then youre standing around, what do you do? you go we gotta be getting back. once youre out, you wanna get back! you wanna go to sleep, you wanna get up, you wanna go out again tomorrow, right? where ever you are in life, its my feeling, youve gotta go. \n    \n    jerry: (pointing at georges shirt) see, to me, that button is in the worst possible spot. the second button literally makes or breaks the shirt, look at it. its too high! its in no-mans-land. you look like you live with your mother. \n    \n    george: are you through? \n    \n    jerry: you do of course try on, when you buy? \n    \n    george: yes, it was purple, i liked it, i dont actually recall considering the buttons. \n    \n    \n\n---\n## Implement Pre-processing Functions\nThe first thing to do to any dataset is pre-processing.  Implement the following pre-processing functions below:\n- Lookup Table\n- Tokenize Punctuation\n\n### Lookup Table\nTo 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\nReturn these dictionaries in the following **tuple** `(vocab_to_int, int_to_vocab)`\n\n\n```python\nimport problem_unittests as tests\nfrom collections import Counter\n```\n\n\n```python\n\ndef 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    # TODO: Implement Function\n    #get a list of all unique words\n    counts = Counter(text)\n    vocab = sorted(counts, key=counts.get, reverse=True)\n    vocab_to_int = {word: ii for ii, word in enumerate(vocab, 1)}\n    int_to_vocab = {ii: word for ii, word in enumerate(vocab, 1)}\n    # return tuple\n    return (vocab_to_int, int_to_vocab)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_create_lookup_tables(create_lookup_tables)\n```\n\n    Tests Passed\n    \n\n### Tokenize Punctuation\nWe'll be splitting the script into a word array using spaces as delimiters.  However, punctuations like periods and exclamation marks can create multiple ids for the same word. For example, \"bye\" and \"bye!\" would generate two different word ids.\n\nImplement 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\nThis dictionary will be used to tokenize the symbols and add the delimiter (space) around it.  This separates each symbols as its own word, making it easier for the neural network to predict the next word. Make sure you don't use a value that could be confused as a word; for example, instead of using the value \"dash\", try using something like \"||dash||\".\n\n\n```python\ndef token_lookup():\n    \"\"\"\n    Generate a dict to turn punctuation into a token.\n    :return: Tokenized dictionary where the key is the punctuation and the value is the token\n    \"\"\"\n    # TODO: Implement Function\n        \n    return {\n        '.': '\u003cPERIOD\u003e',\n        ',': '\u003cCOMMA\u003e',\n        '\"': '\u003cQUTATION\u003e',\n        ';': '\u003cSEMICOLON\u003e',\n        '!': '\u003cEXLAMATION_MARK\u003e',\n        '?': '\u003cQUESTION\u003e',\n        '(': '\u003cLPAREN\u003e',\n        ')': '\u003cRPAREN\u003e',\n        '-': '\u003cDASH\u003e',\n        '\\n': '\u003cRETURN\u003e'\n    }\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_tokenize(token_lookup)\n```\n\n    Tests Passed\n    \n\n## Pre-process all the data and save it\n\nRunning the code cell below will pre-process all the data and save it to file. You're encouraged to look at the code for `preprocess_and_save_data` in the `helpers.py` file to see what it's doing in detail, but you do not need to change this code.\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# pre-process training data|\nhelper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)\n```\n\n# Check Point\nThis 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.\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport problem_unittests as tests\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\n```\n\n## Build the Neural Network\nIn this section, you'll build the components necessary to build an RNN by implementing the RNN Module and forward and backpropagation functions.\n\n### Check Access to GPU\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\n\n# Check for a GPU\ntrain_on_gpu = torch.cuda.is_available()\nif not train_on_gpu:\n    print('No GPU found. Please use a GPU to train your neural network.')\n```\n\n## Input\nLet's start with the preprocessed input data. We'll use [TensorDataset](http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset) to provide a known format to our dataset; in combination with [DataLoader](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader), it will handle batching, shuffling, and other dataset iteration functions.\n\nYou can create data with TensorDataset by passing in feature and target tensors. Then create a DataLoader as usual.\n```\ndata = TensorDataset(feature_tensors, target_tensors)\ndata_loader = torch.utils.data.DataLoader(data, \n                                          batch_size=batch_size)\n```\n\n### Batching\nImplement the `batch_data` function to batch `words` data into chunks of size `batch_size` using the `TensorDataset` and `DataLoader` classes.\n\n\u003eYou can batch words using the DataLoader, but it will be up to you to create `feature_tensors` and `target_tensors` of the correct size and content for a given `sequence_length`.\n\nFor example, say we have these as input:\n```\nwords = [1, 2, 3, 4, 5, 6, 7]\nsequence_length = 4\n```\n\nYour first `feature_tensor` should contain the values:\n```\n[1, 2, 3, 4]\n```\nAnd the corresponding `target_tensor` should just be the next \"word\"/tokenized word value:\n```\n5\n```\nThis should continue with the second `feature_tensor`, `target_tensor` being:\n```\n[2, 3, 4, 5]  # features\n6             # target\n```\n\n\n```python\nfrom torch.utils.data import TensorDataset, DataLoader\n\n\ndef batch_data(words, sequence_length, batch_size):\n    \"\"\"\n    Batch the neural network data using DataLoader\n    :param words: The word ids of the TV scripts\n    :param sequence_length: The sequence length of each batch\n    :param batch_size: The size of each batch; the number of sequences in a batch\n    :return: DataLoader with batched data\n    \"\"\"\n    # TODO: Implement function\n    print(f'Words: {len(words)}')\n    # Need to turn words into feature_tensor = [[]]\n    feature_tensors, target_tensors = [], []\n    \n    # this is my original attempt, its not accurate, the working process is credit to https://github.com/tooth2\n#     for i in range(0, (len(words)//sequence_length)):\n#         tensor = words[i:sequence_length+i]\n#         target = words[sequence_length+i:sequence_length+i+1][0]\n        \n#         feature_tensors.append(tensor)\n#         target_tensors.append(target)\n\n    feature_tensors = [words[i:i+sequence_length] for i, word in enumerate(words[0:-sequence_length])]\n    target_tensors = [words[i+sequence_length] for i, word in enumerate(words[0:-sequence_length])]\n\n    data = TensorDataset(torch.from_numpy(np.array(feature_tensors)), \n                         torch.from_numpy(np.array(target_tensors)))\n    data_loader = torch.utils.data.DataLoader(data, \n                                              shuffle=True, \n                                              batch_size=batch_size)\n\n    return data_loader\n\n# there is no test for this function, but you are encouraged to create\n# print statements and tests of your own\n\n```\n\n### Test your dataloader \n\nYou'll have to modify this code to test a batching function, but it should look fairly similar.\n\nBelow, we're generating some test text data and defining a dataloader using the function you defined, above. Then, we are getting some sample batch of inputs `sample_x` and targets `sample_y` from our dataloader.\n\nYour code should return something like the following (likely in a different order, if you shuffled your data):\n\n```\ntorch.Size([10, 5])\ntensor([[ 28,  29,  30,  31,  32],\n        [ 21,  22,  23,  24,  25],\n        [ 17,  18,  19,  20,  21],\n        [ 34,  35,  36,  37,  38],\n        [ 11,  12,  13,  14,  15],\n        [ 23,  24,  25,  26,  27],\n        [  6,   7,   8,   9,  10],\n        [ 38,  39,  40,  41,  42],\n        [ 25,  26,  27,  28,  29],\n        [  7,   8,   9,  10,  11]])\n\ntorch.Size([10])\ntensor([ 33,  26,  22,  39,  16,  28,  11,  43,  30,  12])\n```\n\n### Sizes\nYour sample_x should be of size `(batch_size, sequence_length)` or (10, 5) in this case and sample_y should just have one dimension: batch_size (10). \n\n### Values\n\nYou should also notice that the targets, sample_y, are the *next* value in the ordered test_text data. So, for an input sequence `[ 28,  29,  30,  31,  32]` that ends with the value `32`, the corresponding output should be `33`.\n\n\n```python\n# test dataloader\n\ntest_text = range(50)\nt_loader = batch_data(test_text, sequence_length=5, batch_size=10)\n\ndata_iter = iter(t_loader)\nsample_x, sample_y = data_iter.next()\n\nprint(sample_x.shape)\nprint(sample_x)\nprint()\nprint(sample_y.shape)\nprint(sample_y)\n```\n\n    Words: 50\n    torch.Size([10, 5])\n    tensor([[ 0,  1,  2,  3,  4],\n            [40, 41, 42, 43, 44],\n            [30, 31, 32, 33, 34],\n            [24, 25, 26, 27, 28],\n            [32, 33, 34, 35, 36],\n            [18, 19, 20, 21, 22],\n            [43, 44, 45, 46, 47],\n            [20, 21, 22, 23, 24],\n            [33, 34, 35, 36, 37],\n            [34, 35, 36, 37, 38]], dtype=torch.int32)\n    \n    torch.Size([10])\n    tensor([ 5, 45, 35, 29, 37, 23, 48, 25, 38, 39], dtype=torch.int32)\n    \n\n---\n## Build the Neural Network\nImplement an RNN using PyTorch's [Module class](http://pytorch.org/docs/master/nn.html#torch.nn.Module). You may choose to use a GRU or an LSTM. To complete the RNN, you'll have to implement the following functions for the class:\n - `__init__` - The initialize function. \n - `init_hidden` - The initialization function for an LSTM/GRU hidden state\n - `forward` - Forward propagation function.\n \nThe initialize function should create the layers of the neural network and save them to the class. The forward propagation function will use these layers to run forward propagation and generate an output and a hidden state.\n\n**The output of this model should be the *last* batch of word scores** after a complete sequence has been processed. That is, for each input sequence of words, we only want to output the word scores for a single, most likely, next word.\n\n### Hints\n\n1. Make sure to stack the outputs of the lstm to pass to your fully-connected layer, you can do this with `lstm_output = lstm_output.contiguous().view(-1, self.hidden_dim)`\n2. You can get the last batch of word scores by shaping the output of the final, fully-connected layer like so:\n\n```\n# reshape into (batch_size, seq_length, output_size)\noutput = output.view(batch_size, -1, self.output_size)\n# get last batch\nout = output[:, -1]\n```\n\n\n```python\nprint(torch.__version__)\n```\n\n    1.7.1+cu110\n    \n\n\n```python\nimport torch.nn as nn\n\nclass RNN(nn.Module):\n    \n    def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.2):\n        \"\"\"\n        Initialize the PyTorch RNN Module\n        :param vocab_size: The number of input dimensions of the neural network (the size of the vocabulary)\n        :param output_size: The number of output dimensions of the neural network\n        :param embedding_dim: The size of embeddings, should you choose to use them        \n        :param hidden_dim: The size of the hidden layer outputs\n        :param dropout: dropout to add in between LSTM/GRU layers\n        \"\"\"\n        super(RNN, self).__init__()\n        # TODO: Implement function\n        \n        # set class variables\n        self.output_size = output_size\n        self.n_layers = n_layers\n        self.hidden_dim = hidden_dim\n        \n        # define model layers\n        self.embedding = nn.Embedding(vocab_size, embedding_dim)\n        self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers,\n                           dropout=dropout, batch_first=True)\n        \n        self.dropout = nn.Dropout(dropout)\n        \n        self.fc = nn.Linear(hidden_dim, output_size)\n       \n    \n    def forward(self, nn_input, hidden):\n        \"\"\"\n        Forward propagation of the neural network\n        :param nn_input: The input to the neural network\n        :param hidden: The hidden state        \n        :return: Two Tensors, the output of the neural network and the latest hidden state\n        \"\"\"\n        # TODO: Implement function   \n        batch_size = nn_input.size(0)\n        \n        #embeddings and lstm out\n        if train_on_gpu:\n            # wihtout this we were getting strang windows only errors about Long indices\n            nn_input = nn_input.to(\"cuda\").long()\n        embeds = self.embedding(nn_input)\n        lstm_out, hidden = self.lstm(embeds, hidden)\n        \n        # stack lstm outputs\n        lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)\n        \n        #dropout and FC\n        out = self.dropout(lstm_out)\n        out = self.fc(out)\n        \n        # reshape to be batch_size first\n        out = out.view(batch_size, -1, self.output_size)\n        out = out[:, -1] # get last batch of labels\n\n        # return one batch of output word scores and the hidden state\n        return out, hidden\n    \n    \n    def init_hidden(self, batch_size):\n        '''\n        Initialize the hidden state of an LSTM/GRU\n        :param batch_size: The batch_size of the hidden state\n        :return: hidden state of dims (n_layers, batch_size, hidden_dim)\n        '''\n         # Create two new tensors with sizes n_layers x batch_size x hidden_dim,\n        # initialized to zero, for hidden state and cell state of LSTM\n        weight = next(self.parameters()).data\n        \n        if (train_on_gpu):\n            hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda(),\n                  weight.new(self.n_layers, batch_size, self.hidden_dim).zero_().cuda())\n        else:\n            hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),\n                      weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())\n        \n        return hidden\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_rnn(RNN, train_on_gpu)\n```\n\n    Tests Passed\n    \n\n### Define forward and backpropagation\n\nUse the RNN class you implemented to apply forward and back propagation. This function will be called, iteratively, in the training loop as follows:\n```\nloss = forward_back_prop(decoder, decoder_optimizer, criterion, inp, target)\n```\n\nAnd it should return the average loss over a batch and the hidden state returned by a call to `RNN(inp, hidden)`. Recall that you can get this loss by computing it, as usual, and calling `loss.item()`.\n\n**If a GPU is available, you should move your data to that GPU device, here.**\n\n\n```python\ndef forward_back_prop(rnn, optimizer, criterion, inp, target, hidden):\n    \"\"\"\n    Forward and backward propagation on the neural network\n    :param rnn: The PyTorch Module that holds the neural network\n    :param optimizer: The PyTorch optimizer for the neural network\n    :param criterion: The PyTorch loss function\n    :param inp: A batch of input to the neural network\n    :param target: The target output for the batch of input\n    :return: The loss and the latest hidden state Tensor\n    \"\"\"\n    \n    # TODO: Implement Function\n    clip = 5\n    \n    # move data to GPU, if available\n    if train_on_gpu:\n        inp, target = inp.cuda(), target.cuda().long()\n        #target = torch.as_tensor(target).to(\"cuda\")\n    \n    # perform backpropagation and optimization\n    hidden = tuple([each.data for each in hidden])\n    \n    # zero accumulated gradients\n    rnn.zero_grad()\n    \n    output, hidden = rnn(inp, hidden)\n    \n    # calculate the loss and perform backprop\n    \n    loss = criterion(output.squeeze(), target)\n    loss.backward()\n    \n    # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.\n    nn.utils.clip_grad_norm_(rnn.parameters(), clip)\n    optimizer.step()\n    \n    # return the loss over a batch and the hidden state produced by our model\n    return loss.item(), hidden\n\n# Note that these tests aren't completely extensive.\n# they are here to act as general checks on the expected outputs of your functions\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_forward_back_prop(RNN, forward_back_prop, train_on_gpu)\n```\n\n    Tests Passed\n    \n\n## Neural Network Training\n\nWith the structure of the network complete and data ready to be fed in the neural network, it's time to train it.\n\n### Train Loop\n\nThe training loop is implemented for you in the `train_decoder` function. This function will train the network over all the batches for the number of epochs given. The model progress will be shown every number of batches. This number is set with the `show_every_n_batches` parameter. You'll set this parameter along with other parameters in the next section.\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n\ndef train_rnn(rnn, batch_size, optimizer, criterion, n_epochs, show_every_n_batches=100):\n    if train_on_gpu:\n        print('Training on GPU')\n    else:\n        print('Training on CPU')\n    batch_losses = []\n    \n    rnn.train()\n\n    print(\"Training for %d epoch(s)...\" % n_epochs)\n    for epoch_i in range(1, n_epochs + 1):\n        \n        # initialize hidden state\n        hidden = rnn.init_hidden(batch_size)\n        \n        for batch_i, (inputs, labels) in enumerate(train_loader, 1):\n            \n            # make sure you iterate over completely full batches, only\n            n_batches = len(train_loader.dataset)//batch_size\n            if(batch_i \u003e n_batches):\n                break\n            \n            # forward, back prop\n            loss, hidden = forward_back_prop(rnn, optimizer, criterion, inputs, labels, hidden)          \n            # record loss\n            batch_losses.append(loss)\n\n            # printing loss stats\n            if batch_i % show_every_n_batches == 0:\n                print('Epoch: {:\u003e4}/{:\u003c4}  Loss: {}\\n'.format(\n                    epoch_i, n_epochs, np.average(batch_losses)))\n                batch_losses = []\n\n    # returns a trained rnn\n    return rnn\n```\n\n### Hyperparameters\n\nSet and train the neural network with the following parameters:\n- Set `sequence_length` to the length of a sequence.\n- Set `batch_size` to the batch size.\n- Set `num_epochs` to the number of epochs to train for.\n- Set `learning_rate` to the learning rate for an Adam optimizer.\n- Set `vocab_size` to the number of unique tokens in our vocabulary.\n- Set `output_size` to the desired size of the output.\n- Set `embedding_dim` to the embedding dimension; smaller than the vocab_size.\n- Set `hidden_dim` to the hidden dimension of your RNN.\n- Set `n_layers` to the number of layers/cells in your RNN.\n- Set `show_every_n_batches` to the number of batches at which the neural network should print progress.\n\nIf the network isn't getting the desired results, tweak these parameters and/or the layers in the `RNN` class.\n\n\n```python\n# Data params\n# Sequence Length\nsequence_length = 10  # of words in a sequence\n# Batch Size\nbatch_size = 128\n\n# data loader - do not change\ntrain_loader = batch_data(int_text, sequence_length, batch_size)\n```\n\n    Words: 892110\n    \n\n\n```python\n# Training parameters\n# Number of Epochs\nnum_epochs = 12\n# Learning Rate\nlearning_rate = 0.001\n\n# Model parameters\n# Vocab size\nvocab_size = len(vocab_to_int) + 1\n# Output size\noutput_size = len(vocab_to_int) + 1\n# Embedding Dimension\nembedding_dim = 200\n# Hidden Dimension\nhidden_dim = 300\n# Number of RNN Layers\nn_layers = 2\n\n# Show stats for every n number of batches\nshow_every_n_batches = 1000\n```\n\n### Train\nIn the next cell, you'll train the neural network on the pre-processed data.  If you have a hard time getting a good loss, you may consider changing your hyperparameters. In general, you may get better results with larger hidden and n_layer dimensions, but larger models take a longer time to train. \n\u003e **You should aim for a loss less than 3.5.** \n\nYou should also experiment with different sequence lengths, which determine the size of the long range dependencies that a model can learn.\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n\n# create model and move to gpu if available\nrnn = RNN(vocab_size, output_size, embedding_dim, hidden_dim, n_layers, dropout=0.2)\nif train_on_gpu:\n    rnn.cuda()\n\n# defining loss and optimization functions for training\noptimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate)\ncriterion = nn.CrossEntropyLoss()\n\n# training the model\ntrained_rnn = train_rnn(rnn, batch_size, optimizer, criterion, num_epochs, show_every_n_batches)\n\n# saving the trained model\nhelper.save_model('./save/trained_rnn', trained_rnn)\nprint('Model Trained and Saved')\n```\n\n    Training on GPU\n    Training for 12 epoch(s)...\n    Epoch:    1/12    Loss: 5.186786951065064\n    \n    Epoch:    1/12    Loss: 4.618807245969772\n    \n    Epoch:    1/12    Loss: 4.429368690490723\n    \n    Epoch:    1/12    Loss: 4.350166130304337\n    \n    Epoch:    1/12    Loss: 4.276277262449264\n    \n    Epoch:    1/12    Loss: 4.233497644424438\n    \n    Epoch:    2/12    Loss: 4.110029435024581\n    \n    Epoch:    2/12    Loss: 4.021084939956665\n    \n    Epoch:    2/12    Loss: 4.010999446392059\n    \n    Epoch:    2/12    Loss: 3.9857825989723206\n    \n    Epoch:    2/12    Loss: 3.9725612218379975\n    \n    Epoch:    2/12    Loss: 3.964773478746414\n    \n    Epoch:    3/12    Loss: 3.8847461360671787\n    \n    Epoch:    3/12    Loss: 3.826342351198196\n    \n    Epoch:    3/12    Loss: 3.8141064376831055\n    \n    Epoch:    3/12    Loss: 3.809804986000061\n    \n    Epoch:    3/12    Loss: 3.827624360322952\n    \n    Epoch:    3/12    Loss: 3.8074213392734526\n    \n    Epoch:    4/12    Loss: 3.7555783630446653\n    \n    Epoch:    4/12    Loss: 3.6756546976566313\n    \n    Epoch:    4/12    Loss: 3.7026719570159914\n    \n    Epoch:    4/12    Loss: 3.6875808806419372\n    \n    Epoch:    4/12    Loss: 3.7063822939395905\n    \n    Epoch:    4/12    Loss: 3.7216410496234893\n    \n    Epoch:    5/12    Loss: 3.6436678693644464\n    \n    Epoch:    5/12    Loss: 3.593005282640457\n    \n    Epoch:    5/12    Loss: 3.5855228543281554\n    \n    Epoch:    5/12    Loss: 3.601815385341644\n    \n    Epoch:    5/12    Loss: 3.6267472643852234\n    \n    Epoch:    5/12    Loss: 3.646820603609085\n    \n    Epoch:    6/12    Loss: 3.5751632280674244\n    \n    Epoch:    6/12    Loss: 3.508531565666199\n    \n    Epoch:    6/12    Loss: 3.5289502770900727\n    \n    Epoch:    6/12    Loss: 3.5491431546211243\n    \n    Epoch:    6/12    Loss: 3.5516954898834228\n    \n    Epoch:    6/12    Loss: 3.5521895377635957\n    \n    Epoch:    7/12    Loss: 3.5050939914234522\n    \n    Epoch:    7/12    Loss: 3.4616376464366914\n    \n    Epoch:    7/12    Loss: 3.4579782786369324\n    \n    Epoch:    7/12    Loss: 3.483021015882492\n    \n    Epoch:    7/12    Loss: 3.477337319135666\n    \n    Epoch:    7/12    Loss: 3.506958493232727\n    \n    Epoch:    8/12    Loss: 3.4453640808727366\n    \n    Epoch:    8/12    Loss: 3.3833394968509674\n    \n    Epoch:    8/12    Loss: 3.4031225383281707\n    \n    Epoch:    8/12    Loss: 3.4225183312892913\n    \n    Epoch:    8/12    Loss: 3.4482937929630277\n    \n    Epoch:    8/12    Loss: 3.474582174539566\n    \n    Epoch:    9/12    Loss: 3.3998568066489945\n    \n    Epoch:    9/12    Loss: 3.3391570250988005\n    \n    Epoch:    9/12    Loss: 3.3679213864803312\n    \n    Epoch:    9/12    Loss: 3.3791939322948457\n    \n    Epoch:    9/12    Loss: 3.4106602046489716\n    \n    Epoch:    9/12    Loss: 3.413899941444397\n    \n    Epoch:   10/12    Loss: 3.352872897913881\n    \n    Epoch:   10/12    Loss: 3.3058280081748963\n    \n    Epoch:   10/12    Loss: 3.3300526957511902\n    \n    Epoch:   10/12    Loss: 3.338808496236801\n    \n    Epoch:   10/12    Loss: 3.3643982033729554\n    \n    Epoch:   10/12    Loss: 3.381549740791321\n    \n    Epoch:   11/12    Loss: 3.322094236187913\n    \n    Epoch:   11/12    Loss: 3.258641685962677\n    \n    Epoch:   11/12    Loss: 3.3086230175495146\n    \n    Epoch:   11/12    Loss: 3.3055105426311493\n    \n    Epoch:   11/12    Loss: 3.3317499074935912\n    \n    Epoch:   11/12    Loss: 3.3629328429698946\n    \n    Epoch:   12/12    Loss: 3.28363179143399\n    \n    Epoch:   12/12    Loss: 3.237078080177307\n    \n    Epoch:   12/12    Loss: 3.2476292326450347\n    \n    Epoch:   12/12    Loss: 3.286781324148178\n    \n    Epoch:   12/12    Loss: 3.297789664506912\n    \n    Epoch:   12/12    Loss: 3.321721970081329\n    \n    Model Trained and Saved\n    \n\n### Question: How did you decide on your model hyperparameters? \nFor example, did you try different sequence_lengths and find that one size made the model converge faster? What about your hidden_dim and n_layers; how did you decide on those?\n\n#### **Answer:** (Write answer, here)\n\nMy initial decision on the hyperparameter values was based on previous expierence in the course.  I originally had a `sequence_length=5` but went with a higher value of `12`.  This allowed the rnn to converge to a loss of `3.38`.\n\nExpiermenting with the n_layer parameter provided varying results.  With 2 layers I achieved final out put of `Epoch:    8/8     Loss: 3.3894933780719496`.  With `4` layers I got `Epoch:    8/8     Loss: 4.618726428897902`, which tells me it needs more epochs to train. Finllay, I ended with `n_layers=3` with `hidden_dim=512`.  I achieved end loss of `3.4434` with 12 epochs of training.  In hindsight I would have been just as good with a lower layer count.\n\n\n---\nUpdate:  After playing around with the final script generation, I decided to go back into the training to see if I can get a lower loss, to see if the script generation can make a little more sense.  I ran this for `11` epochs this time to achieve a loss of `3.321721970081329` with a sequence lenght of 10, and `embedding_dim = 200`, `hidden_dim = 300`, `n_layers = 2`.  With much trial and error, I am happy with these results.\n\n---\n# Checkpoint\n\nAfter running the above training cell, your model will be saved by name, `trained_rnn`, and if you save your notebook progress, **you can pause here and come back to this code at another time**. You can resume your progress by running the next cell, which will load in our word:id dictionaries _and_ load in your saved model by name!\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport torch\nimport helper\nimport problem_unittests as tests\n\n_, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\ntrained_rnn = helper.load_model('./save/trained_rnn')\n```\n\n## Generate TV Script\nWith the network trained and saved, you'll use it to generate a new, \"fake\" Seinfeld TV script in this section.\n\n### Generate Text\nTo generate the text, the network needs to start with a single word and repeat its predictions until it reaches a set length. You'll be using the `generate` function to do this. It takes a word id to start with, `prime_id`, and generates a set length of text, `predict_len`. Also note that it uses topk sampling to introduce some randomness in choosing the most likely next word, given an output set of word scores!\n\n\n```python\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nimport torch.nn.functional as F\n\ndef generate(rnn, prime_id, int_to_vocab, token_dict, pad_value, predict_len=100):\n    \"\"\"\n    Generate text using the neural network\n    :param decoder: The PyTorch Module that holds the trained neural network\n    :param prime_id: The word id to start the first prediction\n    :param int_to_vocab: Dict of word id keys to word values\n    :param token_dict: Dict of puncuation tokens keys to puncuation values\n    :param pad_value: The value used to pad a sequence\n    :param predict_len: The length of text to generate\n    :return: The generated text\n    \"\"\"\n    rnn.eval()\n    \n    # create a sequence (batch_size=1) with the prime_id\n    current_seq = np.full((1, sequence_length), pad_value)\n    current_seq[-1][-1] = prime_id\n    predicted = [int_to_vocab[prime_id]]\n    \n    for _ in range(predict_len):\n        if train_on_gpu:\n            current_seq = torch.LongTensor(current_seq).cuda()\n        else:\n            current_seq = torch.LongTensor(current_seq)\n        \n        # initialize the hidden state\n        hidden = rnn.init_hidden(current_seq.size(0))\n        \n        # get the output of the rnn\n        output, _ = rnn(current_seq, hidden)\n        \n        # get the next word probabilities\n        p = F.softmax(output, dim=1).data\n        if(train_on_gpu):\n            p = p.cpu() # move to cpu\n         \n        # use top_k sampling to get the index of the next word\n        top_k = 5\n        p, top_i = p.topk(top_k)\n        top_i = top_i.numpy().squeeze()\n        \n        # select the likely next word index with some element of randomness\n        p = p.numpy().squeeze()\n        word_i = np.random.choice(top_i, p=p/p.sum())\n        \n        # retrieve that word from the dictionary\n        word = int_to_vocab[word_i]\n        predicted.append(word)     \n        \n        if(train_on_gpu):\n            current_seq = current_seq.cpu() # move to cpu\n        # the generated word becomes the next \"current sequence\" and the cycle can continue\n        if train_on_gpu:\n            current_seq = current_seq.cpu()\n        current_seq = np.roll(current_seq, -1, 1)\n        current_seq[-1][-1] = word_i\n    \n    gen_sentences = ' '.join(predicted)\n    \n    # Replace punctuation tokens\n    for key, token in token_dict.items():\n        ending = ' ' if key in ['\\n', '(', '\"'] else ''\n        gen_sentences = gen_sentences.replace(' ' + token.lower(), key)\n    gen_sentences = gen_sentences.replace('\\n ', '\\n')\n    gen_sentences = gen_sentences.replace('( ', '(')\n    \n    # return all the sentences\n    return gen_sentences\n```\n\n### Generate a New Script\nIt's time to generate the text. Set `gen_length` to the length of TV script you want to generate and set `prime_word` to one of the following to start the prediction:\n- \"jerry\"\n- \"elaine\"\n- \"george\"\n- \"kramer\"\n\nYou can set the prime word to _any word_ in our dictionary, but it's best to start with a name for generating a TV script. (You can also start with any other names you find in the original text file!)\n\n\n```python\n# run the cell multiple times to get different results!\ngen_length = 400 # modify the length to your preference\nprime_word = 'kramer' # name for starting the script\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\npad_word = helper.SPECIAL_WORDS['PADDING']\ngenerated_script = generate(trained_rnn, vocab_to_int[prime_word + ':'], int_to_vocab, token_dict, vocab_to_int[pad_word], gen_length)\nprint(generated_script)\n```\n\n    kramer: troubling modest troubling troubling troubling keen landis like this.\n    \n    george: you know, i don't like you in the car.\n    \n    elaine:(pointing) hey\n    \n    george: i can't believe i'm saying, i don't know...\n    \n    elaine: i know what you're saying, but i can't tell you, i'm gonna be in the mood.\n    \n    jerry: what?\n    \n    jerry: well, i just came back to the apartment to see a woman in my car, you know...\n    \n    george:(to kramer) hey.\n    \n    kramer: well, what d'you mean?\n    \n    jerry: no, i got it. i was just trying to find it.\n    \n    george: you can't tell her what happened.\n    \n    jerry:(to kramer) what?(kramer enters.) oh, i don't know how you can.\n    \n    george:(to elaine) what do you think, you don't know?\n    \n    jerry: no!\n    \n    george:(pointing) you know, i think i could have been able to get a good job to do.\n    \n    jerry: oh. i think it's a little... i was in the middle of a few years ago. i think i am, i don't know what to do. i got to get some help.\n    \n    jerry: i can't believe that!!!\n    \n    jerry:(to george) i think i could have been able to get some ice cubes.\n    \n    jerry:(looking around) well...(jerry looks like) i don't know what you want. i don't wanna know why you want to see a psychiatrist, i have to go back to my house.\n    \n    george: i don't know.\n    \n    elaine: well, i don't want to see him.\n    \n    elaine:(laughs) i know... you see the idea of a lot of people.\n    \n    george: i don't want to go to the bathroom, but i got the same thing, but i got a call.\n    \n    jerry: i know.\n    \n    \n\n#### Save your favorite scripts\n\nOnce you have a script that you like (or find interesting), save it to a text file!\n\n\n```python\n# save script to a text file\nf =  open(\"generated_script_1.txt\",\"w\")\nf.write(generated_script)\nf.close()\n```\n\n# The TV Script is Not Perfect\nIt's ok if the TV script doesn't make perfect sense. It should look like alternating lines of dialogue, here is one such example of a few generated lines.\n\n### Example generated script\n\n\u003ejerry: what about me?\n\u003e\n\u003ejerry: i don't have to wait.\n\u003e\n\u003ekramer:(to the sales table)\n\u003e\n\u003eelaine:(to jerry) hey, look at this, i'm a good doctor.\n\u003e\n\u003enewman:(to elaine) you think i have no idea of this...\n\u003e\n\u003eelaine: oh, you better take the phone, and he was a little nervous.\n\u003e\n\u003ekramer:(to the phone) hey, hey, jerry, i don't want to be a little bit.(to kramer and jerry) you can't.\n\u003e\n\u003ejerry: oh, yeah. i don't even know, i know.\n\u003e\n\u003ejerry:(to the phone) oh, i know.\n\u003e\n\u003ekramer:(laughing) you know...(to jerry) you don't know.\n\nYou can see that there are multiple characters that say (somewhat) complete sentences, but it doesn't have to be perfect! It takes quite a while to get good results, and often, you'll have to use a smaller vocabulary (and discard uncommon words), or get more data.  The Seinfeld dataset is about 3.4 MB, which is big enough for our purposes; for script generation you'll want more than 1 MB of text, generally. \n\n# Submitting This Project\nWhen 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 another copy as an HTML file by clicking \"File\" -\u003e \"Download as..\"-\u003e\"html\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission. Once you download these files, compress them into one zip file for submission.\n\n\n```python\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyjs%2Ftv-script-generator-rnn","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoreyjs%2Ftv-script-generator-rnn","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyjs%2Ftv-script-generator-rnn/lists"}