{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# The Dataset for Pretraining Word Embeddings\n",
    ":label:`sec_word2vec_data`\n",
    "\n",
    "Now that we know the technical details of \n",
    "the word2vec models and approximate training methods,\n",
    "let us walk through their implementations. \n",
    "Specifically,\n",
    "we will take the skip-gram model in :numref:`sec_word2vec`\n",
    "and negative sampling in :numref:`sec_approx_train`\n",
    "as an example.\n",
    "In this section,\n",
    "we begin with the dataset\n",
    "for pretraining the word embedding model:\n",
    "the original format of the data\n",
    "will be transformed\n",
    "into minibatches\n",
    "that can be iterated over during training.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 1,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "import math\n",
    "import os\n",
    "import random\n",
    "from mxnet import gluon, np\n",
    "from d2l import mxnet as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 3
   },
   "source": [
    "## Reading the Dataset\n",
    "\n",
    "The dataset that we use here\n",
    "is [Penn Tree Bank (PTB)]( https://catalog.ldc.upenn.edu/LDC99T42). \n",
    "This corpus is sampled\n",
    "from Wall Street Journal articles,\n",
    "split into training, validation, and test sets.\n",
    "In the original format,\n",
    "each line of the text file\n",
    "represents a sentence of words that are separated by spaces.\n",
    "Here we treat each word as a token.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 4,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading ../data/ptb.zip from http://d2l-data.s3-accelerate.amazonaws.com/ptb.zip...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'# sentences: 42069'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#@save\n",
    "d2l.DATA_HUB['ptb'] = (d2l.DATA_URL + 'ptb.zip',\n",
    "                       '319d85e578af0cdc590547f26231e4e31cdf1e42')\n",
    "\n",
    "#@save\n",
    "def read_ptb():\n",
    "    \"\"\"Load the PTB dataset into a list of text lines.\"\"\"\n",
    "    data_dir = d2l.download_extract('ptb')\n",
    "    # Read the training set.\n",
    "    with open(os.path.join(data_dir, 'ptb.train.txt')) as f:\n",
    "        raw_text = f.read()\n",
    "    return [line.split() for line in raw_text.split('\\n')]\n",
    "\n",
    "sentences = read_ptb()\n",
    "f'# sentences: {len(sentences)}'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "After reading the training set,\n",
    "we build a vocabulary for the corpus,\n",
    "where any word that appears \n",
    "less than 10 times is replaced by \n",
    "the \"&lt;unk&gt;\" token.\n",
    "Note that the original dataset\n",
    "also contains \"&lt;unk&gt;\" tokens that represent rare (unknown) words.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 6,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'vocab size: 6719'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "vocab = d2l.Vocab(sentences, min_freq=10)\n",
    "f'vocab size: {len(vocab)}'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 7
   },
   "source": [
    "## Subsampling\n",
    "\n",
    "Text data\n",
    "typically have high-frequency words\n",
    "such as \"the\", \"a\", and \"in\":\n",
    "they may even occur billions of times in\n",
    "very large corpora.\n",
    "However,\n",
    "these words often co-occur\n",
    "with many different words in\n",
    "context windows, providing little useful signals.\n",
    "For instance,\n",
    "consider the word \"chip\" in a context window:\n",
    "intuitively\n",
    "its co-occurrence with a low-frequency word \"intel\"\n",
    "is more useful in training\n",
    "than \n",
    "the co-occurrence with a high-frequency word \"a\".\n",
    "Moreover, training with vast amounts of (high-frequency) words\n",
    "is slow.\n",
    "Thus, when training word embedding models, \n",
    "high-frequency words can be *subsampled* :cite:`Mikolov.Sutskever.Chen.ea.2013`.\n",
    "Specifically, \n",
    "each indexed word $w_i$ \n",
    "in the dataset will be discarded with probability\n",
    "\n",
    "\n",
    "$$ P(w_i) = \\max\\left(1 - \\sqrt{\\frac{t}{f(w_i)}}, 0\\right),$$\n",
    "\n",
    "where $f(w_i)$ is the ratio of \n",
    "the number of words $w_i$\n",
    "to the total number of words in the dataset, \n",
    "and the constant $t$ is a hyperparameter\n",
    "($10^{-4}$ in the experiment). \n",
    "We can see that only when\n",
    "the relative frequency\n",
    "$f(w_i) > t$  can the (high-frequency) word $w_i$ be discarded, \n",
    "and the higher the relative frequency of the word, \n",
    "the greater the probability of being discarded.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 8,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def subsample(sentences, vocab):\n",
    "    \"\"\"Subsample high-frequency words.\"\"\"\n",
    "    # Exclude unknown tokens '<unk>'\n",
    "    sentences = [[token for token in line if vocab[token] != vocab.unk]\n",
    "                 for line in sentences]\n",
    "    counter = d2l.count_corpus(sentences)\n",
    "    num_tokens = sum(counter.values())\n",
    "\n",
    "    # Return True if `token` is kept during subsampling\n",
    "    def keep(token):\n",
    "        return(random.uniform(0, 1) <\n",
    "               math.sqrt(1e-4 / counter[token] * num_tokens))\n",
    "\n",
    "    return ([[token for token in line if keep(token)] for line in sentences],\n",
    "            counter)\n",
    "\n",
    "subsampled, counter = subsample(sentences, vocab)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 9
   },
   "source": [
    "The following code snippet \n",
    "plots the histogram of\n",
    "the number of tokens per sentence\n",
    "before and after subsampling.\n",
    "As expected, \n",
    "subsampling significantly shortens sentences\n",
    "by dropping high-frequency words,\n",
    "which will lead to training speedup.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 10,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"262.190625pt\" height=\"183.012742pt\" viewBox=\"0 0 262.190625 183.012742\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2022-03-24T10:57:50.963610</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.5.1, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 183.012742 \n",
       "L 262.190625 183.012742 \n",
       "L 262.190625 0 \n",
       "L 0 0 \n",
       "L 0 183.012742 \n",
       "z\n",
       "\" style=\"fill: none\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 59.690625 145.456492 \n",
       "L 254.990625 145.456492 \n",
       "L 254.990625 9.556492 \n",
       "L 59.690625 9.556492 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 68.567898 145.456492 \n",
       "L 75.814651 145.456492 \n",
       "L 75.814651 124.131569 \n",
       "L 68.567898 124.131569 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 86.684781 145.456492 \n",
       "L 93.931534 145.456492 \n",
       "L 93.931534 86.33294 \n",
       "L 86.684781 86.33294 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 104.801664 145.456492 \n",
       "L 112.048417 145.456492 \n",
       "L 112.048417 77.152197 \n",
       "L 104.801664 77.152197 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 122.918547 145.456492 \n",
       "L 130.1653 145.456492 \n",
       "L 130.1653 97.105657 \n",
       "L 122.918547 97.105657 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_7\">\n",
       "    <path d=\"M 141.03543 145.456492 \n",
       "L 148.282183 145.456492 \n",
       "L 148.282183 125.298658 \n",
       "L 141.03543 125.298658 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_8\">\n",
       "    <path d=\"M 159.152313 145.456492 \n",
       "L 166.399067 145.456492 \n",
       "L 166.399067 138.609928 \n",
       "L 159.152313 138.609928 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_9\">\n",
       "    <path d=\"M 177.269196 145.456492 \n",
       "L 184.51595 145.456492 \n",
       "L 184.51595 143.907544 \n",
       "L 177.269196 143.907544 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_10\">\n",
       "    <path d=\"M 195.38608 145.456492 \n",
       "L 202.632833 145.456492 \n",
       "L 202.632833 145.063877 \n",
       "L 195.38608 145.063877 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_11\">\n",
       "    <path d=\"M 213.502963 145.456492 \n",
       "L 220.749716 145.456492 \n",
       "L 220.749716 145.322035 \n",
       "L 213.502963 145.322035 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_12\">\n",
       "    <path d=\"M 231.619846 145.456492 \n",
       "L 238.866599 145.456492 \n",
       "L 238.866599 145.381196 \n",
       "L 231.619846 145.381196 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: #1f77b4\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_13\">\n",
       "    <path d=\"M 75.814651 145.456492 \n",
       "L 83.061404 145.456492 \n",
       "L 83.061404 16.027921 \n",
       "L 75.814651 16.027921 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_14\">\n",
       "    <path d=\"M 93.931534 145.456492 \n",
       "L 101.178287 145.456492 \n",
       "L 101.178287 58.946682 \n",
       "L 93.931534 58.946682 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_15\">\n",
       "    <path d=\"M 112.048417 145.456492 \n",
       "L 119.29517 145.456492 \n",
       "L 119.29517 135.711029 \n",
       "L 112.048417 135.711029 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_16\">\n",
       "    <path d=\"M 130.1653 145.456492 \n",
       "L 137.412054 145.456492 \n",
       "L 137.412054 144.924041 \n",
       "L 130.1653 144.924041 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_17\">\n",
       "    <path d=\"M 148.282183 145.456492 \n",
       "L 155.528937 145.456492 \n",
       "L 155.528937 145.413466 \n",
       "L 148.282183 145.413466 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_18\">\n",
       "    <path d=\"M 166.399067 145.456492 \n",
       "L 173.64582 145.456492 \n",
       "L 173.64582 145.456492 \n",
       "L 166.399067 145.456492 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_19\">\n",
       "    <path d=\"M 184.51595 145.456492 \n",
       "L 191.762703 145.456492 \n",
       "L 191.762703 145.456492 \n",
       "L 184.51595 145.456492 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_20\">\n",
       "    <path d=\"M 202.632833 145.456492 \n",
       "L 209.879586 145.456492 \n",
       "L 209.879586 145.456492 \n",
       "L 202.632833 145.456492 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_21\">\n",
       "    <path d=\"M 220.749716 145.456492 \n",
       "L 227.996469 145.456492 \n",
       "L 227.996469 145.456492 \n",
       "L 220.749716 145.456492 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_22\">\n",
       "    <path d=\"M 238.866599 145.456492 \n",
       "L 246.113352 145.456492 \n",
       "L 246.113352 145.456492 \n",
       "L 238.866599 145.456492 \n",
       "z\n",
       "\" clip-path=\"url(#pbc90b1fff8)\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <defs>\n",
       "       <path id=\"mb29ed380b8\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb29ed380b8\" x=\"66.756209\" y=\"145.456492\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 0 -->\n",
       "      <g transform=\"translate(63.574959 160.05493)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_2\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb29ed380b8\" x=\"110.943729\" y=\"145.456492\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 20 -->\n",
       "      <g transform=\"translate(104.581229 160.05493)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb29ed380b8\" x=\"155.131249\" y=\"145.456492\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 40 -->\n",
       "      <g transform=\"translate(148.768749 160.05493)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-34\" d=\"M 2419 4116 \n",
       "L 825 1625 \n",
       "L 2419 1625 \n",
       "L 2419 4116 \n",
       "z\n",
       "M 2253 4666 \n",
       "L 3047 4666 \n",
       "L 3047 1625 \n",
       "L 3713 1625 \n",
       "L 3713 1100 \n",
       "L 3047 1100 \n",
       "L 3047 0 \n",
       "L 2419 0 \n",
       "L 2419 1100 \n",
       "L 313 1100 \n",
       "L 313 1709 \n",
       "L 2253 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-34\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb29ed380b8\" x=\"199.318769\" y=\"145.456492\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 60 -->\n",
       "      <g transform=\"translate(192.956269 160.05493)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-36\" d=\"M 2113 2584 \n",
       "Q 1688 2584 1439 2293 \n",
       "Q 1191 2003 1191 1497 \n",
       "Q 1191 994 1439 701 \n",
       "Q 1688 409 2113 409 \n",
       "Q 2538 409 2786 701 \n",
       "Q 3034 994 3034 1497 \n",
       "Q 3034 2003 2786 2293 \n",
       "Q 2538 2584 2113 2584 \n",
       "z\n",
       "M 3366 4563 \n",
       "L 3366 3988 \n",
       "Q 3128 4100 2886 4159 \n",
       "Q 2644 4219 2406 4219 \n",
       "Q 1781 4219 1451 3797 \n",
       "Q 1122 3375 1075 2522 \n",
       "Q 1259 2794 1537 2939 \n",
       "Q 1816 3084 2150 3084 \n",
       "Q 2853 3084 3261 2657 \n",
       "Q 3669 2231 3669 1497 \n",
       "Q 3669 778 3244 343 \n",
       "Q 2819 -91 2113 -91 \n",
       "Q 1303 -91 875 529 \n",
       "Q 447 1150 447 2328 \n",
       "Q 447 3434 972 4092 \n",
       "Q 1497 4750 2381 4750 \n",
       "Q 2619 4750 2861 4703 \n",
       "Q 3103 4656 3366 4563 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-36\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#mb29ed380b8\" x=\"243.506289\" y=\"145.456492\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 80 -->\n",
       "      <g transform=\"translate(237.143789 160.05493)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-38\" d=\"M 2034 2216 \n",
       "Q 1584 2216 1326 1975 \n",
       "Q 1069 1734 1069 1313 \n",
       "Q 1069 891 1326 650 \n",
       "Q 1584 409 2034 409 \n",
       "Q 2484 409 2743 651 \n",
       "Q 3003 894 3003 1313 \n",
       "Q 3003 1734 2745 1975 \n",
       "Q 2488 2216 2034 2216 \n",
       "z\n",
       "M 1403 2484 \n",
       "Q 997 2584 770 2862 \n",
       "Q 544 3141 544 3541 \n",
       "Q 544 4100 942 4425 \n",
       "Q 1341 4750 2034 4750 \n",
       "Q 2731 4750 3128 4425 \n",
       "Q 3525 4100 3525 3541 \n",
       "Q 3525 3141 3298 2862 \n",
       "Q 3072 2584 2669 2484 \n",
       "Q 3125 2378 3379 2068 \n",
       "Q 3634 1759 3634 1313 \n",
       "Q 3634 634 3220 271 \n",
       "Q 2806 -91 2034 -91 \n",
       "Q 1263 -91 848 271 \n",
       "Q 434 634 434 1313 \n",
       "Q 434 1759 690 2068 \n",
       "Q 947 2378 1403 2484 \n",
       "z\n",
       "M 1172 3481 \n",
       "Q 1172 3119 1398 2916 \n",
       "Q 1625 2713 2034 2713 \n",
       "Q 2441 2713 2670 2916 \n",
       "Q 2900 3119 2900 3481 \n",
       "Q 2900 3844 2670 4047 \n",
       "Q 2441 4250 2034 4250 \n",
       "Q 1625 4250 1398 4047 \n",
       "Q 1172 3844 1172 3481 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-38\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_6\">\n",
       "     <!-- # tokens per sentence -->\n",
       "     <g transform=\"translate(100.6125 173.733055)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-23\" d=\"M 3272 2816 \n",
       "L 2363 2816 \n",
       "L 2100 1772 \n",
       "L 3016 1772 \n",
       "L 3272 2816 \n",
       "z\n",
       "M 2803 4594 \n",
       "L 2478 3297 \n",
       "L 3391 3297 \n",
       "L 3719 4594 \n",
       "L 4219 4594 \n",
       "L 3897 3297 \n",
       "L 4872 3297 \n",
       "L 4872 2816 \n",
       "L 3775 2816 \n",
       "L 3519 1772 \n",
       "L 4513 1772 \n",
       "L 4513 1294 \n",
       "L 3397 1294 \n",
       "L 3072 0 \n",
       "L 2572 0 \n",
       "L 2894 1294 \n",
       "L 1978 1294 \n",
       "L 1656 0 \n",
       "L 1153 0 \n",
       "L 1478 1294 \n",
       "L 494 1294 \n",
       "L 494 1772 \n",
       "L 1594 1772 \n",
       "L 1856 2816 \n",
       "L 850 2816 \n",
       "L 850 3297 \n",
       "L 1978 3297 \n",
       "L 2297 4594 \n",
       "L 2803 4594 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-20\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-74\" d=\"M 1172 4494 \n",
       "L 1172 3500 \n",
       "L 2356 3500 \n",
       "L 2356 3053 \n",
       "L 1172 3053 \n",
       "L 1172 1153 \n",
       "Q 1172 725 1289 603 \n",
       "Q 1406 481 1766 481 \n",
       "L 2356 481 \n",
       "L 2356 0 \n",
       "L 1766 0 \n",
       "Q 1100 0 847 248 \n",
       "Q 594 497 594 1153 \n",
       "L 594 3053 \n",
       "L 172 3053 \n",
       "L 172 3500 \n",
       "L 594 3500 \n",
       "L 594 4494 \n",
       "L 1172 4494 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6b\" d=\"M 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 1991 \n",
       "L 2875 3500 \n",
       "L 3609 3500 \n",
       "L 1753 1863 \n",
       "L 3688 0 \n",
       "L 2938 0 \n",
       "L 1159 1709 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6e\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \n",
       "L 2834 2853 \n",
       "Q 2591 2978 2328 3040 \n",
       "Q 2066 3103 1784 3103 \n",
       "Q 1356 3103 1142 2972 \n",
       "Q 928 2841 928 2578 \n",
       "Q 928 2378 1081 2264 \n",
       "Q 1234 2150 1697 2047 \n",
       "L 1894 2003 \n",
       "Q 2506 1872 2764 1633 \n",
       "Q 3022 1394 3022 966 \n",
       "Q 3022 478 2636 193 \n",
       "Q 2250 -91 1575 -91 \n",
       "Q 1294 -91 989 -36 \n",
       "Q 684 19 347 128 \n",
       "L 347 722 \n",
       "Q 666 556 975 473 \n",
       "Q 1284 391 1588 391 \n",
       "Q 1994 391 2212 530 \n",
       "Q 2431 669 2431 922 \n",
       "Q 2431 1156 2273 1281 \n",
       "Q 2116 1406 1581 1522 \n",
       "L 1381 1569 \n",
       "Q 847 1681 609 1914 \n",
       "Q 372 2147 372 2553 \n",
       "Q 372 3047 722 3315 \n",
       "Q 1072 3584 1716 3584 \n",
       "Q 2034 3584 2315 3537 \n",
       "Q 2597 3491 2834 3397 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \n",
       "L 1159 -1331 \n",
       "L 581 -1331 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "z\n",
       "M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-72\" d=\"M 2631 2963 \n",
       "Q 2534 3019 2420 3045 \n",
       "Q 2306 3072 2169 3072 \n",
       "Q 1681 3072 1420 2755 \n",
       "Q 1159 2438 1159 1844 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1341 3275 1631 3429 \n",
       "Q 1922 3584 2338 3584 \n",
       "Q 2397 3584 2469 3576 \n",
       "Q 2541 3569 2628 3553 \n",
       "L 2631 2963 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-23\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-20\" x=\"83.789062\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-74\" x=\"115.576172\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"154.785156\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6b\" x=\"215.966797\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"270.251953\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"331.775391\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"395.154297\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-20\" x=\"447.253906\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"479.041016\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"542.517578\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"604.041016\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-20\" x=\"645.154297\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"676.941406\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"729.041016\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"790.564453\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-74\" x=\"853.943359\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"893.152344\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"954.675781\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-63\" x=\"1018.054688\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"1073.035156\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_6\">\n",
       "      <defs>\n",
       "       <path id=\"m3c9ae55bcd\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3c9ae55bcd\" x=\"59.690625\" y=\"145.456492\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_7\">\n",
       "      <!-- 0 -->\n",
       "      <g transform=\"translate(46.328125 149.255711)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3c9ae55bcd\" x=\"59.690625\" y=\"118.565038\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 5000 -->\n",
       "      <g transform=\"translate(27.240625 122.364256)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"190.869141\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3c9ae55bcd\" x=\"59.690625\" y=\"91.673583\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 10000 -->\n",
       "      <g transform=\"translate(20.878125 95.472802)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"190.869141\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"254.492188\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3c9ae55bcd\" x=\"59.690625\" y=\"64.782128\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 15000 -->\n",
       "      <g transform=\"translate(20.878125 68.581347)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"190.869141\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"254.492188\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_5\">\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3c9ae55bcd\" x=\"59.690625\" y=\"37.890673\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 20000 -->\n",
       "      <g transform=\"translate(20.878125 41.689892)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"190.869141\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"254.492188\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m3c9ae55bcd\" x=\"59.690625\" y=\"10.999219\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_12\">\n",
       "      <!-- 25000 -->\n",
       "      <g transform=\"translate(20.878125 14.798437)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"190.869141\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"254.492188\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_13\">\n",
       "     <!-- count -->\n",
       "     <g transform=\"translate(14.798438 91.612742)rotate(-90)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-75\" d=\"M 544 1381 \n",
       "L 544 3500 \n",
       "L 1119 3500 \n",
       "L 1119 1403 \n",
       "Q 1119 906 1312 657 \n",
       "Q 1506 409 1894 409 \n",
       "Q 2359 409 2629 706 \n",
       "Q 2900 1003 2900 1516 \n",
       "L 2900 3500 \n",
       "L 3475 3500 \n",
       "L 3475 0 \n",
       "L 2900 0 \n",
       "L 2900 538 \n",
       "Q 2691 219 2414 64 \n",
       "Q 2138 -91 1772 -91 \n",
       "Q 1169 -91 856 284 \n",
       "Q 544 659 544 1381 \n",
       "z\n",
       "M 1991 3584 \n",
       "L 1991 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-63\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"54.980469\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-75\" x=\"116.162109\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"179.541016\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-74\" x=\"242.919922\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"patch_23\">\n",
       "    <path d=\"M 59.690625 145.456492 \n",
       "L 59.690625 9.556492 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_24\">\n",
       "    <path d=\"M 254.990625 145.456492 \n",
       "L 254.990625 9.556492 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_25\">\n",
       "    <path d=\"M 59.690625 145.456492 \n",
       "L 254.990625 145.456492 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_26\">\n",
       "    <path d=\"M 59.690625 9.556492 \n",
       "L 254.990625 9.556492 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"legend_1\">\n",
       "    <g id=\"patch_27\">\n",
       "     <path d=\"M 155.389063 46.912742 \n",
       "L 247.990625 46.912742 \n",
       "Q 249.990625 46.912742 249.990625 44.912742 \n",
       "L 249.990625 16.556492 \n",
       "Q 249.990625 14.556492 247.990625 14.556492 \n",
       "L 155.389063 14.556492 \n",
       "Q 153.389063 14.556492 153.389063 16.556492 \n",
       "L 153.389063 44.912742 \n",
       "Q 153.389063 46.912742 155.389063 46.912742 \n",
       "z\n",
       "\" style=\"fill: #ffffff; opacity: 0.8; stroke: #cccccc; stroke-linejoin: miter\"/>\n",
       "    </g>\n",
       "    <g id=\"patch_28\">\n",
       "     <path d=\"M 157.389063 26.15493 \n",
       "L 177.389063 26.15493 \n",
       "L 177.389063 19.15493 \n",
       "L 157.389063 19.15493 \n",
       "z\n",
       "\" style=\"fill: #1f77b4\"/>\n",
       "    </g>\n",
       "    <g id=\"text_14\">\n",
       "     <!-- origin -->\n",
       "     <g transform=\"translate(185.389063 26.15493)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-69\" d=\"M 603 3500 \n",
       "L 1178 3500 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 3500 \n",
       "z\n",
       "M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 4134 \n",
       "L 603 4134 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-67\" d=\"M 2906 1791 \n",
       "Q 2906 2416 2648 2759 \n",
       "Q 2391 3103 1925 3103 \n",
       "Q 1463 3103 1205 2759 \n",
       "Q 947 2416 947 1791 \n",
       "Q 947 1169 1205 825 \n",
       "Q 1463 481 1925 481 \n",
       "Q 2391 481 2648 825 \n",
       "Q 2906 1169 2906 1791 \n",
       "z\n",
       "M 3481 434 \n",
       "Q 3481 -459 3084 -895 \n",
       "Q 2688 -1331 1869 -1331 \n",
       "Q 1566 -1331 1297 -1286 \n",
       "Q 1028 -1241 775 -1147 \n",
       "L 775 -588 \n",
       "Q 1028 -725 1275 -790 \n",
       "Q 1522 -856 1778 -856 \n",
       "Q 2344 -856 2625 -561 \n",
       "Q 2906 -266 2906 331 \n",
       "L 2906 616 \n",
       "Q 2728 306 2450 153 \n",
       "Q 2172 0 1784 0 \n",
       "Q 1141 0 747 490 \n",
       "Q 353 981 353 1791 \n",
       "Q 353 2603 747 3093 \n",
       "Q 1141 3584 1784 3584 \n",
       "Q 2172 3584 2450 3431 \n",
       "Q 2728 3278 2906 2969 \n",
       "L 2906 3500 \n",
       "L 3481 3500 \n",
       "L 3481 434 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-72\" x=\"61.181641\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"102.294922\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-67\" x=\"130.078125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-69\" x=\"193.554688\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6e\" x=\"221.337891\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"patch_29\">\n",
       "     <path d=\"M 157.389063 40.833055 \n",
       "L 177.389063 40.833055 \n",
       "L 177.389063 33.833055 \n",
       "L 157.389063 33.833055 \n",
       "z\n",
       "\" style=\"fill: url(#hafbddf7219)\"/>\n",
       "    </g>\n",
       "    <g id=\"text_15\">\n",
       "     <!-- subsampled -->\n",
       "     <g transform=\"translate(185.389063 40.833055)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-62\" d=\"M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "M 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2969 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-61\" d=\"M 2194 1759 \n",
       "Q 1497 1759 1228 1600 \n",
       "Q 959 1441 959 1056 \n",
       "Q 959 750 1161 570 \n",
       "Q 1363 391 1709 391 \n",
       "Q 2188 391 2477 730 \n",
       "Q 2766 1069 2766 1631 \n",
       "L 2766 1759 \n",
       "L 2194 1759 \n",
       "z\n",
       "M 3341 1997 \n",
       "L 3341 0 \n",
       "L 2766 0 \n",
       "L 2766 531 \n",
       "Q 2569 213 2275 61 \n",
       "Q 1981 -91 1556 -91 \n",
       "Q 1019 -91 701 211 \n",
       "Q 384 513 384 1019 \n",
       "Q 384 1609 779 1909 \n",
       "Q 1175 2209 1959 2209 \n",
       "L 2766 2209 \n",
       "L 2766 2266 \n",
       "Q 2766 2663 2505 2880 \n",
       "Q 2244 3097 1772 3097 \n",
       "Q 1472 3097 1187 3025 \n",
       "Q 903 2953 641 2809 \n",
       "L 641 3341 \n",
       "Q 956 3463 1253 3523 \n",
       "Q 1550 3584 1831 3584 \n",
       "Q 2591 3584 2966 3190 \n",
       "Q 3341 2797 3341 1997 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6d\" d=\"M 3328 2828 \n",
       "Q 3544 3216 3844 3400 \n",
       "Q 4144 3584 4550 3584 \n",
       "Q 5097 3584 5394 3201 \n",
       "Q 5691 2819 5691 2113 \n",
       "L 5691 0 \n",
       "L 5113 0 \n",
       "L 5113 2094 \n",
       "Q 5113 2597 4934 2840 \n",
       "Q 4756 3084 4391 3084 \n",
       "Q 3944 3084 3684 2787 \n",
       "Q 3425 2491 3425 1978 \n",
       "L 3425 0 \n",
       "L 2847 0 \n",
       "L 2847 2094 \n",
       "Q 2847 2600 2669 2842 \n",
       "Q 2491 3084 2119 3084 \n",
       "Q 1678 3084 1418 2786 \n",
       "Q 1159 2488 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2956 \n",
       "Q 1356 3278 1631 3431 \n",
       "Q 1906 3584 2284 3584 \n",
       "Q 2666 3584 2933 3390 \n",
       "Q 3200 3197 3328 2828 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-64\" d=\"M 2906 2969 \n",
       "L 2906 4863 \n",
       "L 3481 4863 \n",
       "L 3481 0 \n",
       "L 2906 0 \n",
       "L 2906 525 \n",
       "Q 2725 213 2448 61 \n",
       "Q 2172 -91 1784 -91 \n",
       "Q 1150 -91 751 415 \n",
       "Q 353 922 353 1747 \n",
       "Q 353 2572 751 3078 \n",
       "Q 1150 3584 1784 3584 \n",
       "Q 2172 3584 2448 3432 \n",
       "Q 2725 3281 2906 2969 \n",
       "z\n",
       "M 947 1747 \n",
       "Q 947 1113 1208 752 \n",
       "Q 1469 391 1925 391 \n",
       "Q 2381 391 2643 752 \n",
       "Q 2906 1113 2906 1747 \n",
       "Q 2906 2381 2643 2742 \n",
       "Q 2381 3103 1925 3103 \n",
       "Q 1469 3103 1208 2742 \n",
       "Q 947 2381 947 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-73\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-75\" x=\"52.099609\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-62\" x=\"115.478516\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"178.955078\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-61\" x=\"231.054688\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6d\" x=\"292.333984\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"389.746094\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\" x=\"453.222656\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-65\" x=\"481.005859\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-64\" x=\"542.529297\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"pbc90b1fff8\">\n",
       "   <rect x=\"59.690625\" y=\"9.556492\" width=\"195.3\" height=\"135.9\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       " <defs>\n",
       "  <pattern id=\"hafbddf7219\" patternUnits=\"userSpaceOnUse\" x=\"0\" y=\"0\" width=\"72\" height=\"72\">\n",
       "   <rect x=\"0\" y=\"0\" width=\"73\" height=\"73\" fill=\"#ff7f0e\"/>\n",
       "   <path d=\"M -36 36 \n",
       "L 36 -36 \n",
       "M -24 48 \n",
       "L 48 -24 \n",
       "M -12 60 \n",
       "L 60 -12 \n",
       "M 0 72 \n",
       "L 72 0 \n",
       "M 12 84 \n",
       "L 84 12 \n",
       "M 24 96 \n",
       "L 96 24 \n",
       "M 36 108 \n",
       "L 108 36 \n",
       "\" style=\"fill: #000000; stroke: #000000; stroke-width: 1.0; stroke-linecap: butt; stroke-linejoin: miter\"/>\n",
       "  </pattern>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "d2l.show_list_len_pair_hist(['origin', 'subsampled'], '# tokens per sentence',\n",
    "                            'count', sentences, subsampled);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 11
   },
   "source": [
    "For individual tokens, the sampling rate of the high-frequency word \"the\" is less than 1/20.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 12,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'# of \"the\": before=50770, after=2040'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def compare_counts(token):\n",
    "    return (f'# of \"{token}\": '\n",
    "            f'before={sum([l.count(token) for l in sentences])}, '\n",
    "            f'after={sum([l.count(token) for l in subsampled])}')\n",
    "\n",
    "compare_counts('the')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 13
   },
   "source": [
    "In contrast, \n",
    "low-frequency words \"join\" are completely kept.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 14,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'# of \"join\": before=45, after=45'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "compare_counts('join')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 15
   },
   "source": [
    "After subsampling, we map tokens to their indices for the corpus.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "origin_pos": 16,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[], [2115, 145, 274, 406], [5277, 3054, 1580]]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "corpus = [vocab[line] for line in subsampled]\n",
    "corpus[:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 17
   },
   "source": [
    "## Extracting Center Words and Context Words\n",
    "\n",
    "\n",
    "The following `get_centers_and_contexts`\n",
    "function extracts all the \n",
    "center words and their context words\n",
    "from `corpus`.\n",
    "It uniformly samples an integer between 1 and `max_window_size`\n",
    "at random as the context window size.\n",
    "For any center word,\n",
    "those words \n",
    "whose distance from it\n",
    "does not exceed the sampled\n",
    "context window size\n",
    "are its context words.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "origin_pos": 18,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def get_centers_and_contexts(corpus, max_window_size):\n",
    "    \"\"\"Return center words and context words in skip-gram.\"\"\"\n",
    "    centers, contexts = [], []\n",
    "    for line in corpus:\n",
    "        # To form a \"center word--context word\" pair, each sentence needs to\n",
    "        # have at least 2 words\n",
    "        if len(line) < 2:\n",
    "            continue\n",
    "        centers += line\n",
    "        for i in range(len(line)):  # Context window centered at `i`\n",
    "            window_size = random.randint(1, max_window_size)\n",
    "            indices = list(range(max(0, i - window_size),\n",
    "                                 min(len(line), i + 1 + window_size)))\n",
    "            # Exclude the center word from the context words\n",
    "            indices.remove(i)\n",
    "            contexts.append([line[idx] for idx in indices])\n",
    "    return centers, contexts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 19
   },
   "source": [
    "Next, we create an artificial dataset containing two sentences of 7 and 3 words, respectively. \n",
    "Let the maximum context window size be 2 \n",
    "and print all the center words and their context words.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "origin_pos": 20,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dataset [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9]]\n",
      "center 0 has contexts [1]\n",
      "center 1 has contexts [0, 2]\n",
      "center 2 has contexts [1, 3]\n",
      "center 3 has contexts [1, 2, 4, 5]\n",
      "center 4 has contexts [2, 3, 5, 6]\n",
      "center 5 has contexts [4, 6]\n",
      "center 6 has contexts [5]\n",
      "center 7 has contexts [8, 9]\n",
      "center 8 has contexts [7, 9]\n",
      "center 9 has contexts [7, 8]\n"
     ]
    }
   ],
   "source": [
    "tiny_dataset = [list(range(7)), list(range(7, 10))]\n",
    "print('dataset', tiny_dataset)\n",
    "for center, context in zip(*get_centers_and_contexts(tiny_dataset, 2)):\n",
    "    print('center', center, 'has contexts', context)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 21
   },
   "source": [
    "When training on the PTB dataset,\n",
    "we set the maximum context window size to 5. \n",
    "The following extracts all the center words and their context words in the dataset.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "origin_pos": 22,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'# center-context pairs: 1500961'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_centers, all_contexts = get_centers_and_contexts(corpus, 5)\n",
    "f'# center-context pairs: {sum([len(contexts) for contexts in all_contexts])}'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 23
   },
   "source": [
    "## Negative Sampling\n",
    "\n",
    "We use negative sampling for approximate training. \n",
    "To sample noise words according to \n",
    "a predefined distribution,\n",
    "we define the following `RandomGenerator` class,\n",
    "where the (possibly unnormalized) sampling distribution is passed\n",
    "via the argument `sampling_weights`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "origin_pos": 24,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "class RandomGenerator:\n",
    "    \"\"\"Randomly draw among {1, ..., n} according to n sampling weights.\"\"\"\n",
    "    def __init__(self, sampling_weights):\n",
    "        # Exclude\n",
    "        self.population = list(range(1, len(sampling_weights) + 1))\n",
    "        self.sampling_weights = sampling_weights\n",
    "        self.candidates = []\n",
    "        self.i = 0\n",
    "\n",
    "    def draw(self):\n",
    "        if self.i == len(self.candidates):\n",
    "            # Cache `k` random sampling results\n",
    "            self.candidates = random.choices(\n",
    "                self.population, self.sampling_weights, k=10000)\n",
    "            self.i = 0\n",
    "        self.i += 1\n",
    "        return self.candidates[self.i - 1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 25
   },
   "source": [
    "For example, \n",
    "we can draw 10 random variables $X$\n",
    "among indices 1, 2, and 3\n",
    "with sampling probabilities $P(X=1)=2/9, P(X=2)=3/9$, and $P(X=3)=4/9$ as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "origin_pos": 26,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 3, 2, 3, 3, 2, 2, 2, 3, 1]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "generator = RandomGenerator([2, 3, 4])\n",
    "[generator.draw() for _ in range(10)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 27
   },
   "source": [
    "For a pair of center word and context word, \n",
    "we randomly sample `K` (5 in the experiment) noise words. According to the suggestions in the word2vec paper,\n",
    "the sampling probability $P(w)$ of \n",
    "a noise word $w$\n",
    "is \n",
    "set to its relative frequency \n",
    "in the dictionary\n",
    "raised to \n",
    "the power of 0.75 :cite:`Mikolov.Sutskever.Chen.ea.2013`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "origin_pos": 28,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def get_negatives(all_contexts, vocab, counter, K):\n",
    "    \"\"\"Return noise words in negative sampling.\"\"\"\n",
    "    # Sampling weights for words with indices 1, 2, ... (index 0 is the\n",
    "    # excluded unknown token) in the vocabulary\n",
    "    sampling_weights = [counter[vocab.to_tokens(i)]**0.75\n",
    "                        for i in range(1, len(vocab))]\n",
    "    all_negatives, generator = [], RandomGenerator(sampling_weights)\n",
    "    for contexts in all_contexts:\n",
    "        negatives = []\n",
    "        while len(negatives) < len(contexts) * K:\n",
    "            neg = generator.draw()\n",
    "            # Noise words cannot be context words\n",
    "            if neg not in contexts:\n",
    "                negatives.append(neg)\n",
    "        all_negatives.append(negatives)\n",
    "    return all_negatives\n",
    "\n",
    "all_negatives = get_negatives(all_contexts, vocab, counter, 5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 29
   },
   "source": [
    "## Loading Training Examples in Minibatches\n",
    ":label:`subsec_word2vec-minibatch-loading`\n",
    "\n",
    "After\n",
    "all the center words\n",
    "together with their\n",
    "context words and sampled noise words are extracted,\n",
    "they will be transformed into \n",
    "minibatches of examples\n",
    "that can be iteratively loaded\n",
    "during training.\n",
    "\n",
    "\n",
    "\n",
    "In a minibatch,\n",
    "the $i^\\mathrm{th}$ example includes a center word\n",
    "and its $n_i$ context words and $m_i$ noise words. \n",
    "Due to varying context window sizes,\n",
    "$n_i+m_i$ varies for different $i$.\n",
    "Thus,\n",
    "for each example\n",
    "we concatenate its context words and noise words in \n",
    "the `contexts_negatives` variable,\n",
    "and pad zeros until the concatenation length\n",
    "reaches $\\max_i n_i+m_i$ (`max_len`).\n",
    "To exclude paddings\n",
    "in the calculation of the loss,\n",
    "we define a mask variable `masks`.\n",
    "There is a one-to-one correspondence\n",
    "between elements in `masks` and elements in `contexts_negatives`,\n",
    "where zeros (otherwise ones) in `masks` correspond to paddings in `contexts_negatives`.\n",
    "\n",
    "\n",
    "To distinguish between positive and negative examples,\n",
    "we separate context words from noise words in  `contexts_negatives` via a `labels` variable. \n",
    "Similar to `masks`,\n",
    "there is also a one-to-one correspondence\n",
    "between elements in `labels` and elements in `contexts_negatives`,\n",
    "where ones (otherwise zeros) in `labels` correspond to context words (positive examples) in `contexts_negatives`.\n",
    "\n",
    "\n",
    "The above idea is implemented in the following `batchify` function.\n",
    "Its input `data` is a list with length\n",
    "equal to the batch size,\n",
    "where each element is an example\n",
    "consisting of\n",
    "the center word `center`, its context words `context`, and its noise words `negative`.\n",
    "This function returns \n",
    "a minibatch that can be loaded for calculations \n",
    "during training,\n",
    "such as including the mask variable.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "origin_pos": 30,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def batchify(data):\n",
    "    \"\"\"Return a minibatch of examples for skip-gram with negative sampling.\"\"\"\n",
    "    max_len = max(len(c) + len(n) for _, c, n in data)\n",
    "    centers, contexts_negatives, masks, labels = [], [], [], []\n",
    "    for center, context, negative in data:\n",
    "        cur_len = len(context) + len(negative)\n",
    "        centers += [center]\n",
    "        contexts_negatives += [context + negative + [0] * (max_len - cur_len)]\n",
    "        masks += [[1] * cur_len + [0] * (max_len - cur_len)]\n",
    "        labels += [[1] * len(context) + [0] * (max_len - len(context))]\n",
    "    return (np.array(centers).reshape((-1, 1)), np.array(\n",
    "        contexts_negatives), np.array(masks), np.array(labels))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 31
   },
   "source": [
    "Let us test this function using a minibatch of two examples.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "origin_pos": 32,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "centers = [[1.]\n",
      " [1.]]\n",
      "contexts_negatives = [[2. 2. 3. 3. 3. 3.]\n",
      " [2. 2. 2. 3. 3. 0.]]\n",
      "masks = [[1. 1. 1. 1. 1. 1.]\n",
      " [1. 1. 1. 1. 1. 0.]]\n",
      "labels = [[1. 1. 0. 0. 0. 0.]\n",
      " [1. 1. 1. 0. 0. 0.]]\n"
     ]
    }
   ],
   "source": [
    "x_1 = (1, [2, 2], [3, 3, 3, 3])\n",
    "x_2 = (1, [2, 2, 2], [3, 3])\n",
    "batch = batchify((x_1, x_2))\n",
    "\n",
    "names = ['centers', 'contexts_negatives', 'masks', 'labels']\n",
    "for name, data in zip(names, batch):\n",
    "    print(name, '=', data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 33
   },
   "source": [
    "## Putting All Things Together\n",
    "\n",
    "Last, we define the `load_data_ptb` function that reads the PTB dataset and returns the data iterator and the vocabulary.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "origin_pos": 34,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def load_data_ptb(batch_size, max_window_size, num_noise_words):\n",
    "    \"\"\"Download the PTB dataset and then load it into memory.\"\"\"\n",
    "    sentences = read_ptb()\n",
    "    vocab = d2l.Vocab(sentences, min_freq=10)\n",
    "    subsampled, counter = subsample(sentences, vocab)\n",
    "    corpus = [vocab[line] for line in subsampled]\n",
    "    all_centers, all_contexts = get_centers_and_contexts(\n",
    "        corpus, max_window_size)\n",
    "    all_negatives = get_negatives(\n",
    "        all_contexts, vocab, counter, num_noise_words)\n",
    "    dataset = gluon.data.ArrayDataset(\n",
    "        all_centers, all_contexts, all_negatives)\n",
    "    data_iter = gluon.data.DataLoader(\n",
    "        dataset, batch_size, shuffle=True,batchify_fn=batchify,\n",
    "        num_workers=d2l.get_dataloader_workers())\n",
    "    return data_iter, vocab"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36
   },
   "source": [
    "Let us print the first minibatch of the data iterator.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "origin_pos": 37,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "centers shape: (512, 1)\n",
      "contexts_negatives shape: (512, 60)\n",
      "masks shape: (512, 60)\n",
      "labels shape: (512, 60)\n"
     ]
    }
   ],
   "source": [
    "data_iter, vocab = load_data_ptb(512, 5, 5)\n",
    "for batch in data_iter:\n",
    "    for name, data in zip(names, batch):\n",
    "        print(name, 'shape:', data.shape)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 38
   },
   "source": [
    "## Summary\n",
    "\n",
    "* High-frequency words may not be so useful in training. We can subsample them for speedup in training.\n",
    "* For computational efficiency, we load examples in minibatches. We can define other variables to distinguish paddings from non-paddings, and positive examples from negative ones.\n",
    "\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. How does the running time of code in this section changes if not using subsampling?\n",
    "1. The `RandomGenerator` class caches `k` random sampling results. Set `k` to other values and see how it affects the data loading speed.\n",
    "1. What other hyperparameters in the code of this section may affect the data loading speed?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 39,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/383)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}