{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# For tips on running notebooks in Google Colab, see\n", "# https://pytorch.org/tutorials/beginner/colab\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "NLP From Scratch: Generating Names with a Character-Level RNN\n", "=============================================================\n", "\n", "**Author**: [Sean Robertson](https://github.com/spro)\n", "\n", "This is our second of three tutorials on \\\"NLP From Scratch\\\". In the\n", "[first\n", "tutorial](/tutorials/intermediate/char_rnn_classification_tutorial) we\n", "used a RNN to classify names into their language of origin. This time\n", "we\\'ll turn around and generate names from languages.\n", "\n", "``` {.sourceCode .sh}\n", "> python sample.py Russian RUS\n", "Rovakov\n", "Uantov\n", "Shavakov\n", "\n", "> python sample.py German GER\n", "Gerren\n", "Ereng\n", "Rosher\n", "\n", "> python sample.py Spanish SPA\n", "Salla\n", "Parer\n", "Allan\n", "\n", "> python sample.py Chinese CHI\n", "Chan\n", "Hang\n", "Iun\n", "```\n", "\n", "We are still hand-crafting a small RNN with a few linear layers. The big\n", "difference is instead of predicting a category after reading in all the\n", "letters of a name, we input a category and output one letter at a time.\n", "Recurrently predicting characters to form language (this could also be\n", "done with words or other higher order constructs) is often referred to\n", "as a \\\"language model\\\".\n", "\n", "**Recommended Reading:**\n", "\n", "I assume you have at least installed PyTorch, know Python, and\n", "understand Tensors:\n", "\n", "- For installation instructions\n", "- `/beginner/deep_learning_60min_blitz`{.interpreted-text role=\"doc\"}\n", " to get started with PyTorch in general\n", "- `/beginner/pytorch_with_examples`{.interpreted-text role=\"doc\"} for\n", " a wide and deep overview\n", "- `/beginner/former_torchies_tutorial`{.interpreted-text role=\"doc\"}\n", " if you are former Lua Torch user\n", "\n", "It would also be useful to know about RNNs and how they work:\n", "\n", "- [The Unreasonable Effectiveness of Recurrent Neural\n", " Networks](https://karpathy.github.io/2015/05/21/rnn-effectiveness/)\n", " shows a bunch of real life examples\n", "- [Understanding LSTM\n", " Networks](https://colah.github.io/posts/2015-08-Understanding-LSTMs/)\n", " is about LSTMs specifically but also informative about RNNs in\n", " general\n", "\n", "I also suggest the previous tutorial,\n", "`/intermediate/char_rnn_classification_tutorial`{.interpreted-text\n", "role=\"doc\"}\n", "\n", "Preparing the Data\n", "------------------\n", "\n", "
NOTE:
\n", "
\n", "

Download the data fromhereand extract it to the current directory.

\n", "
\n", "\n", "See the last tutorial for more detail of this process. In short, there\n", "are a bunch of plain text files `data/names/[Language].txt` with a name\n", "per line. We split lines into an array, convert Unicode to ASCII, and\n", "end up with a dictionary `{language: [names ...]}`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from io import open\n", "import glob\n", "import os\n", "import unicodedata\n", "import string\n", "\n", "all_letters = string.ascii_letters + \" .,;'-\"\n", "n_letters = len(all_letters) + 1 # Plus EOS marker\n", "\n", "def findFiles(path): return glob.glob(path)\n", "\n", "# Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427\n", "def unicodeToAscii(s):\n", " return ''.join(\n", " c for c in unicodedata.normalize('NFD', s)\n", " if unicodedata.category(c) != 'Mn'\n", " and c in all_letters\n", " )\n", "\n", "# Read a file and split into lines\n", "def readLines(filename):\n", " with open(filename, encoding='utf-8') as some_file:\n", " return [unicodeToAscii(line.strip()) for line in some_file]\n", "\n", "# Build the category_lines dictionary, a list of lines per category\n", "category_lines = {}\n", "all_categories = []\n", "for filename in findFiles('data/names/*.txt'):\n", " category = os.path.splitext(os.path.basename(filename))[0]\n", " all_categories.append(category)\n", " lines = readLines(filename)\n", " category_lines[category] = lines\n", "\n", "n_categories = len(all_categories)\n", "\n", "if n_categories == 0:\n", " raise RuntimeError('Data not found. Make sure that you downloaded data '\n", " 'from https://download.pytorch.org/tutorial/data.zip and extract it to '\n", " 'the current directory.')\n", "\n", "print('# categories:', n_categories, all_categories)\n", "print(unicodeToAscii(\"O'Néàl\"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creating the Network\n", "====================\n", "\n", "This network extends [the last tutorial\\'s RNN](#Creating-the-Network)\n", "with an extra argument for the category tensor, which is concatenated\n", "along with the others. The category tensor is a one-hot vector just like\n", "the letter input.\n", "\n", "We will interpret the output as the probability of the next letter. When\n", "sampling, the most likely output letter is used as the next input\n", "letter.\n", "\n", "I added a second linear layer `o2o` (after combining hidden and output)\n", "to give it more muscle to work with. There\\'s also a dropout layer,\n", "which [randomly zeros parts of its\n", "input](https://arxiv.org/abs/1207.0580) with a given probability (here\n", "0.1) and is usually used to fuzz inputs to prevent overfitting. Here\n", "we\\'re using it towards the end of the network to purposely add some\n", "chaos and increase sampling variety.\n", "\n", "![](https://i.imgur.com/jzVrf7f.png)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import torch\n", "import torch.nn as nn\n", "\n", "class RNN(nn.Module):\n", " def __init__(self, input_size, hidden_size, output_size):\n", " super(RNN, self).__init__()\n", " self.hidden_size = hidden_size\n", "\n", " self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)\n", " self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)\n", " self.o2o = nn.Linear(hidden_size + output_size, output_size)\n", " self.dropout = nn.Dropout(0.1)\n", " self.softmax = nn.LogSoftmax(dim=1)\n", "\n", " def forward(self, category, input, hidden):\n", " input_combined = torch.cat((category, input, hidden), 1)\n", " hidden = self.i2h(input_combined)\n", " output = self.i2o(input_combined)\n", " output_combined = torch.cat((hidden, output), 1)\n", " output = self.o2o(output_combined)\n", " output = self.dropout(output)\n", " output = self.softmax(output)\n", " return output, hidden\n", "\n", " def initHidden(self):\n", " return torch.zeros(1, self.hidden_size)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Training\n", "========\n", "\n", "Preparing for Training\n", "----------------------\n", "\n", "First of all, helper functions to get random pairs of (category, line):\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import random\n", "\n", "# Random item from a list\n", "def randomChoice(l):\n", " return l[random.randint(0, len(l) - 1)]\n", "\n", "# Get a random category and random line from that category\n", "def randomTrainingPair():\n", " category = randomChoice(all_categories)\n", " line = randomChoice(category_lines[category])\n", " return category, line" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For each timestep (that is, for each letter in a training word) the\n", "inputs of the network will be `(category, current letter, hidden state)`\n", "and the outputs will be `(next letter, next hidden state)`. So for each\n", "training set, we\\'ll need the category, a set of input letters, and a\n", "set of output/target letters.\n", "\n", "Since we are predicting the next letter from the current letter for each\n", "timestep, the letter pairs are groups of consecutive letters from the\n", "line - e.g. for `\"ABCD\"` we would create (\\\"A\\\", \\\"B\\\"), (\\\"B\\\",\n", "\\\"C\\\"), (\\\"C\\\", \\\"D\\\"), (\\\"D\\\", \\\"EOS\\\").\n", "\n", "![](https://i.imgur.com/JH58tXY.png)\n", "\n", "The category tensor is a [one-hot\n", "tensor](https://en.wikipedia.org/wiki/One-hot) of size\n", "`<1 x n_categories>`. When training we feed it to the network at every\n", "timestep - this is a design choice, it could have been included as part\n", "of initial hidden state or some other strategy.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# One-hot vector for category\n", "def categoryTensor(category):\n", " li = all_categories.index(category)\n", " tensor = torch.zeros(1, n_categories)\n", " tensor[0][li] = 1\n", " return tensor\n", "\n", "# One-hot matrix of first to last letters (not including EOS) for input\n", "def inputTensor(line):\n", " tensor = torch.zeros(len(line), 1, n_letters)\n", " for li in range(len(line)):\n", " letter = line[li]\n", " tensor[li][0][all_letters.find(letter)] = 1\n", " return tensor\n", "\n", "# ``LongTensor`` of second letter to end (EOS) for target\n", "def targetTensor(line):\n", " letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]\n", " letter_indexes.append(n_letters - 1) # EOS\n", " return torch.LongTensor(letter_indexes)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For convenience during training we\\'ll make a `randomTrainingExample`\n", "function that fetches a random (category, line) pair and turns them into\n", "the required (category, input, target) tensors.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Make category, input, and target tensors from a random category, line pair\n", "def randomTrainingExample():\n", " category, line = randomTrainingPair()\n", " category_tensor = categoryTensor(category)\n", " input_line_tensor = inputTensor(line)\n", " target_line_tensor = targetTensor(line)\n", " return category_tensor, input_line_tensor, target_line_tensor" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Training the Network\n", "====================\n", "\n", "In contrast to classification, where only the last output is used, we\n", "are making a prediction at every step, so we are calculating loss at\n", "every step.\n", "\n", "The magic of autograd allows you to simply sum these losses at each step\n", "and call backward at the end.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "criterion = nn.NLLLoss()\n", "\n", "learning_rate = 0.0005\n", "\n", "def train(category_tensor, input_line_tensor, target_line_tensor):\n", " target_line_tensor.unsqueeze_(-1)\n", " hidden = rnn.initHidden()\n", "\n", " rnn.zero_grad()\n", "\n", " loss = torch.Tensor([0]) # you can also just simply use ``loss = 0``\n", "\n", " for i in range(input_line_tensor.size(0)):\n", " output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)\n", " l = criterion(output, target_line_tensor[i])\n", " loss += l\n", "\n", " loss.backward()\n", "\n", " for p in rnn.parameters():\n", " p.data.add_(p.grad.data, alpha=-learning_rate)\n", "\n", " return output, loss.item() / input_line_tensor.size(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To keep track of how long training takes I am adding a\n", "`timeSince(timestamp)` function which returns a human readable string:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import time\n", "import math\n", "\n", "def timeSince(since):\n", " now = time.time()\n", " s = now - since\n", " m = math.floor(s / 60)\n", " s -= m * 60\n", " return '%dm %ds' % (m, s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Training is business as usual - call train a bunch of times and wait a\n", "few minutes, printing the current time and loss every `print_every`\n", "examples, and keeping store of an average loss per `plot_every` examples\n", "in `all_losses` for plotting later.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "rnn = RNN(n_letters, 128, n_letters)\n", "\n", "n_iters = 100000\n", "print_every = 5000\n", "plot_every = 500\n", "all_losses = []\n", "total_loss = 0 # Reset every ``plot_every`` ``iters``\n", "\n", "start = time.time()\n", "\n", "for iter in range(1, n_iters + 1):\n", " output, loss = train(*randomTrainingExample())\n", " total_loss += loss\n", "\n", " if iter % print_every == 0:\n", " print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))\n", "\n", " if iter % plot_every == 0:\n", " all_losses.append(total_loss / plot_every)\n", " total_loss = 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plotting the Losses\n", "===================\n", "\n", "Plotting the historical loss from all\\_losses shows the network\n", "learning:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "plt.figure()\n", "plt.plot(all_losses)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sampling the Network\n", "====================\n", "\n", "To sample we give the network a letter and ask what the next one is,\n", "feed that in as the next letter, and repeat until the EOS token.\n", "\n", "- Create tensors for input category, starting letter, and empty hidden\n", " state\n", "- Create a string `output_name` with the starting letter\n", "- Up to a maximum output length,\n", " - Feed the current letter to the network\n", " - Get the next letter from highest output, and next hidden state\n", " - If the letter is EOS, stop here\n", " - If a regular letter, add to `output_name` and continue\n", "- Return the final name\n", "\n", "
NOTE:
\n", "
\n", "

Rather than having to give it a starting letter, anotherstrategy would have been to include a \"start of string\" token intraining and have the network choose its own starting letter.

\n", "
\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "max_length = 20\n", "\n", "# Sample from a category and starting letter\n", "def sample(category, start_letter='A'):\n", " with torch.no_grad(): # no need to track history in sampling\n", " category_tensor = categoryTensor(category)\n", " input = inputTensor(start_letter)\n", " hidden = rnn.initHidden()\n", "\n", " output_name = start_letter\n", "\n", " for i in range(max_length):\n", " output, hidden = rnn(category_tensor, input[0], hidden)\n", " topv, topi = output.topk(1)\n", " topi = topi[0][0]\n", " if topi == n_letters - 1:\n", " break\n", " else:\n", " letter = all_letters[topi]\n", " output_name += letter\n", " input = inputTensor(letter)\n", "\n", " return output_name\n", "\n", "# Get multiple samples from one category and multiple starting letters\n", "def samples(category, start_letters='ABC'):\n", " for start_letter in start_letters:\n", " print(sample(category, start_letter))\n", "\n", "samples('Russian', 'RUS')\n", "\n", "samples('German', 'GER')\n", "\n", "samples('Spanish', 'SPA')\n", "\n", "samples('Chinese', 'CHI')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercises\n", "=========\n", "\n", "- Try with a different dataset of category -\\> line, for example:\n", " - Fictional series -\\> Character name\n", " - Part of speech -\\> Word\n", " - Country -\\> City\n", "- Use a \\\"start of sentence\\\" token so that sampling can be done\n", " without choosing a start letter\n", "- Get better results with a bigger and/or better shaped network\n", " - Try the `nn.LSTM` and `nn.GRU` layers\n", " - Combine multiple of these RNNs as a higher level network\n" ] } ], "metadata": { "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.10.14" } }, "nbformat": 4, "nbformat_minor": 0 }