{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 嵌入\n",
    "\n",
    "在之前的例子中，我们处理的是长度为 `vocab_size` 的高维词袋向量，并且我们显式地将低维位置表示向量转换为稀疏的独热表示。这种独热表示并不节省内存，而且每个单词都是彼此独立处理的，也就是说，独热编码的向量无法表达单词之间的语义相似性。\n",
    "\n",
    "在本单元中，我们将继续探索 **News AG** 数据集。首先，让我们加载数据并从之前的笔记本中获取一些定义。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading dataset...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\WORK\\ai-for-beginners\\5-NLP\\14-Embeddings\\data\\train.csv: 29.5MB [00:01, 18.8MB/s]                            \n",
      "d:\\WORK\\ai-for-beginners\\5-NLP\\14-Embeddings\\data\\test.csv: 1.86MB [00:00, 11.2MB/s]                          \n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Building vocab...\n",
      "Vocab size =  95812\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torchtext\n",
    "import numpy as np\n",
    "from torchnlp import *\n",
    "train_dataset, test_dataset, classes, vocab = load_dataset()\n",
    "vocab_size = len(vocab)\n",
    "print(\"Vocab size = \",vocab_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 什么是嵌入？\n",
    "\n",
    "**嵌入**的概念是用低维密集向量来表示单词，这些向量能够在某种程度上反映单词的语义意义。稍后我们会讨论如何构建有意义的单词嵌入，但现在可以简单地将嵌入理解为一种降低单词向量维度的方法。\n",
    "\n",
    "嵌入层会将一个单词作为输入，并生成指定`embedding_size`的输出向量。从某种意义上说，它与`Linear`层非常相似，但嵌入层不需要接收独热编码向量，而是可以直接接收单词编号作为输入。\n",
    "\n",
    "通过将嵌入层作为网络的第一层，我们可以从词袋模型切换到**嵌入袋**模型。在嵌入袋模型中，我们首先将文本中的每个单词转换为对应的嵌入向量，然后对所有这些嵌入向量进行某种聚合操作，例如`sum`（求和）、`average`（平均）或`max`（最大值）。\n",
    "\n",
    "![展示五个序列单词的嵌入分类器的图片。](../../../../../lessons/5-NLP/14-Embeddings/images/embedding-classifier-example.png)\n",
    "\n",
    "我们的分类器神经网络将从嵌入层开始，然后是聚合层，最后是线性分类器：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class EmbedClassifier(torch.nn.Module):\n",
    "    def __init__(self, vocab_size, embed_dim, num_class):\n",
    "        super().__init__()\n",
    "        self.embedding = torch.nn.Embedding(vocab_size, embed_dim)\n",
    "        self.fc = torch.nn.Linear(embed_dim, num_class)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.embedding(x)\n",
    "        x = torch.mean(x,dim=1)\n",
    "        return self.fc(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 处理变量序列长度\n",
    "\n",
    "由于这种架构，我们需要以特定方式创建网络的微批次。在前一个单元中，使用词袋模型（BoW）时，微批次中的所有 BoW 张量都具有相同的大小 `vocab_size`，无论文本序列的实际长度是多少。一旦我们转向词嵌入，每个文本样本中会包含不同数量的单词，而在将这些样本组合成微批次时，我们需要进行一些填充。\n",
    "\n",
    "这可以通过向数据源提供 `collate_fn` 函数的相同技术来实现：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def padify(b):\n",
    "    # b is the list of tuples of length batch_size\n",
    "    #   - first element of a tuple = label, \n",
    "    #   - second = feature (text sequence)\n",
    "    # build vectorized sequence\n",
    "    v = [encode(x[1]) for x in b]\n",
    "    # first, compute max length of a sequence in this minibatch\n",
    "    l = max(map(len,v))\n",
    "    return ( # tuple of two tensors - labels and features\n",
    "        torch.LongTensor([t[0]-1 for t in b]),\n",
    "        torch.stack([torch.nn.functional.pad(torch.tensor(t),(0,l-len(t)),mode='constant',value=0) for t in v])\n",
    "    )\n",
    "\n",
    "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, collate_fn=padify, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 训练嵌入分类器\n",
    "\n",
    "现在我们已经定义了合适的数据加载器，可以使用我们在上一单元中定义的训练函数来训练模型：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3200: acc=0.6415625\n",
      "6400: acc=0.6865625\n",
      "9600: acc=0.7103125\n",
      "12800: acc=0.726953125\n",
      "16000: acc=0.739375\n",
      "19200: acc=0.75046875\n",
      "22400: acc=0.7572321428571429\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(0.889799795315499, 0.7623160588611644)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = EmbedClassifier(vocab_size,32,len(classes)).to(device)\n",
    "train_epoch(net,train_loader, lr=1, epoch_size=25000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **注意**：我们这里只训练了25k条记录（少于一个完整的周期）以节省时间，但您可以继续训练，编写一个函数来训练多个周期，并尝试调整学习率参数以获得更高的准确性。您应该能够达到大约90%的准确率。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### EmbeddingBag层与可变长度序列表示\n",
    "\n",
    "在之前的架构中，我们需要将所有序列填充到相同的长度，以便将它们放入一个小批量中。这并不是表示可变长度序列的最有效方式——另一种方法是使用**偏移量**向量，它可以存储一个大向量中所有序列的偏移量。\n",
    "\n",
    "![显示偏移量序列表示的图片](../../../../../lessons/5-NLP/14-Embeddings/images/offset-sequence-representation.png)\n",
    "\n",
    "> **注意**：在上图中，我们展示的是字符序列，但在我们的示例中，我们处理的是单词序列。然而，用偏移量向量表示序列的基本原理是相同的。\n",
    "\n",
    "为了使用偏移量表示，我们使用[`EmbeddingBag`](https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html)层。它与`Embedding`类似，但它以内容向量和偏移量向量作为输入，并且还包括一个平均层，可以是`mean`、`sum`或`max`。\n",
    "\n",
    "以下是使用`EmbeddingBag`的修改后的网络：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class EmbedClassifier(torch.nn.Module):\n",
    "    def __init__(self, vocab_size, embed_dim, num_class):\n",
    "        super().__init__()\n",
    "        self.embedding = torch.nn.EmbeddingBag(vocab_size, embed_dim)\n",
    "        self.fc = torch.nn.Linear(embed_dim, num_class)\n",
    "\n",
    "    def forward(self, text, off):\n",
    "        x = self.embedding(text, off)\n",
    "        return self.fc(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为了准备用于训练的数据集，我们需要提供一个转换函数来准备偏移向量：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def offsetify(b):\n",
    "    # first, compute data tensor from all sequences\n",
    "    x = [torch.tensor(encode(t[1])) for t in b]\n",
    "    # now, compute the offsets by accumulating the tensor of sequence lengths\n",
    "    o = [0] + [len(t) for t in x]\n",
    "    o = torch.tensor(o[:-1]).cumsum(dim=0)\n",
    "    return ( \n",
    "        torch.LongTensor([t[0]-1 for t in b]), # labels\n",
    "        torch.cat(x), # text \n",
    "        o\n",
    "    )\n",
    "\n",
    "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, collate_fn=offsetify, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，与之前的所有示例不同，我们的网络现在接受两个参数：数据向量和偏移向量，它们的大小不同。同样，我们的数据加载器也为我们提供了3个值而不是2个：文本和偏移向量都作为特征提供。因此，我们需要稍微调整我们的训练函数来处理这一点：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3200: acc=0.6153125\n",
      "6400: acc=0.6615625\n",
      "9600: acc=0.6932291666666667\n",
      "12800: acc=0.715078125\n",
      "16000: acc=0.7270625\n",
      "19200: acc=0.7382291666666667\n",
      "22400: acc=0.7486160714285715\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(22.771553103007037, 0.7551983365323096)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = EmbedClassifier(vocab_size,32,len(classes)).to(device)\n",
    "\n",
    "def train_epoch_emb(net,dataloader,lr=0.01,optimizer=None,loss_fn = torch.nn.CrossEntropyLoss(),epoch_size=None, report_freq=200):\n",
    "    optimizer = optimizer or torch.optim.Adam(net.parameters(),lr=lr)\n",
    "    loss_fn = loss_fn.to(device)\n",
    "    net.train()\n",
    "    total_loss,acc,count,i = 0,0,0,0\n",
    "    for labels,text,off in dataloader:\n",
    "        optimizer.zero_grad()\n",
    "        labels,text,off = labels.to(device), text.to(device), off.to(device)\n",
    "        out = net(text, off)\n",
    "        loss = loss_fn(out,labels) #cross_entropy(out,labels)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        total_loss+=loss\n",
    "        _,predicted = torch.max(out,1)\n",
    "        acc+=(predicted==labels).sum()\n",
    "        count+=len(labels)\n",
    "        i+=1\n",
    "        if i%report_freq==0:\n",
    "            print(f\"{count}: acc={acc.item()/count}\")\n",
    "        if epoch_size and count>epoch_size:\n",
    "            break\n",
    "    return total_loss.item()/count, acc.item()/count\n",
    "\n",
    "\n",
    "train_epoch_emb(net,train_loader, lr=4, epoch_size=25000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 语义嵌入：Word2Vec\n",
    "\n",
    "在之前的例子中，模型的嵌入层学习了将单词映射为向量表示，但这种表示并没有太多语义上的意义。如果能够学习一种向量表示，使得相似的单词或同义词在某种向量距离（例如欧几里得距离）上彼此接近，那就更好了。\n",
    "\n",
    "为了实现这一点，我们需要以特定的方式在大量文本集合上预训练嵌入模型。最早的一种训练语义嵌入的方法被称为 [Word2Vec](https://en.wikipedia.org/wiki/Word2vec)。它基于两种主要架构，用于生成单词的分布式表示：\n",
    "\n",
    " - **连续词袋模型** (CBoW) —— 在这种架构中，我们训练模型根据上下文预测一个单词。给定 ngram $(W_{-2},W_{-1},W_0,W_1,W_2)$，模型的目标是从 $(W_{-2},W_{-1},W_1,W_2)$ 中预测 $W_0$。\n",
    " - **连续跳词模型** (Skip-Gram) 与 CBoW 相反。模型使用上下文窗口中的单词来预测当前单词。\n",
    "\n",
    "CBoW 的训练速度更快，而 Skip-Gram 虽然较慢，但在表示不常见单词方面表现更好。\n",
    "\n",
    "![展示 CBoW 和 Skip-Gram 算法将单词转换为向量的图片。](../../../../../lessons/5-NLP/14-Embeddings/images/example-algorithms-for-converting-words-to-vectors.png)\n",
    "\n",
    "为了实验基于 Google News 数据集预训练的 Word2Vec 嵌入，我们可以使用 **gensim** 库。下面我们找到与“neural”最相似的单词：\n",
    "\n",
    "> **注意:** 当你第一次创建单词向量时，下载它们可能需要一些时间！\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gensim.downloader as api\n",
    "w2v = api.load('word2vec-google-news-300')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "neuronal -> 0.7804799675941467\n",
      "neurons -> 0.7326500415802002\n",
      "neural_circuits -> 0.7252851724624634\n",
      "neuron -> 0.7174385190010071\n",
      "cortical -> 0.6941086649894714\n",
      "brain_circuitry -> 0.6923246383666992\n",
      "synaptic -> 0.6699118614196777\n",
      "neural_circuitry -> 0.6638563275337219\n",
      "neurochemical -> 0.6555314064025879\n",
      "neuronal_activity -> 0.6531826257705688\n"
     ]
    }
   ],
   "source": [
    "for w,p in w2v.most_similar('neural'):\n",
    "    print(f\"{w} -> {p}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们还可以从单词计算向量嵌入，用于训练分类模型（为清晰起见，我们仅显示向量的前20个分量）：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.01226807,  0.06225586,  0.10693359,  0.05810547,  0.23828125,\n",
       "        0.03686523,  0.05151367, -0.20703125,  0.01989746,  0.10058594,\n",
       "       -0.03759766, -0.1015625 , -0.15820312, -0.08105469, -0.0390625 ,\n",
       "       -0.05053711,  0.16015625,  0.2578125 ,  0.10058594, -0.25976562],\n",
       "      dtype=float32)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "w2v.word_vec('play')[:20]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "语义嵌入的一个伟大之处在于，你可以操控向量编码来改变语义。例如，我们可以要求找到一个词，其向量表示尽可能接近词语*国王*和*女人*，并尽可能远离词语*男人*：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('queen', 0.7118192911148071)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "w2v.most_similar(positive=['king','woman'],negative=['man'])[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "CBoW 和 Skip-Grams 都是“预测型”嵌入，因为它们只考虑局部上下文。Word2Vec 并未利用全局上下文。\n",
    "\n",
    "**FastText** 基于 Word2Vec，通过为每个单词以及单词中的字符 n-gram 学习向量表示来扩展功能。在每次训练步骤中，这些表示的值会被平均成一个向量。虽然这增加了预训练的计算量，但它使得词嵌入能够编码子词信息。\n",
    "\n",
    "另一种方法 **GloVe** 利用了共现矩阵的概念，使用神经方法将共现矩阵分解为更具表现力和非线性的词向量。\n",
    "\n",
    "你可以通过将嵌入模型切换为 FastText 和 GloVe 来尝试示例，因为 gensim 支持多种不同的词嵌入模型。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在 PyTorch 中使用预训练的嵌入\n",
    "\n",
    "我们可以修改上面的示例，在嵌入层的矩阵中预填充语义嵌入，例如 Word2Vec。需要注意的是，预训练嵌入的词汇表和我们的文本语料库的词汇表可能不完全匹配，因此我们会用随机值初始化缺失词的权重：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Embedding size: 300\n",
      "Populating matrix, this will take some time...Done, found 41080 words, 54732 words missing\n"
     ]
    }
   ],
   "source": [
    "embed_size = len(w2v.get_vector('hello'))\n",
    "print(f'Embedding size: {embed_size}')\n",
    "\n",
    "net = EmbedClassifier(vocab_size,embed_size,len(classes))\n",
    "\n",
    "print('Populating matrix, this will take some time...',end='')\n",
    "found, not_found = 0,0\n",
    "for i,w in enumerate(vocab.get_itos()):\n",
    "    try:\n",
    "        net.embedding.weight[i].data = torch.tensor(w2v.get_vector(w))\n",
    "        found+=1\n",
    "    except:\n",
    "        net.embedding.weight[i].data = torch.normal(0.0,1.0,(embed_size,))\n",
    "        not_found+=1\n",
    "\n",
    "print(f\"Done, found {found} words, {not_found} words missing\")\n",
    "net = net.to(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在让我们训练我们的模型。请注意，由于嵌入层大小更大，因此参数数量显著增加，训练模型所需的时间比前一个例子要长得多。此外，正因为如此，如果我们想避免过拟合，可能需要在更多的例子上训练我们的模型。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3200: acc=0.6359375\n",
      "6400: acc=0.68109375\n",
      "9600: acc=0.7067708333333333\n",
      "12800: acc=0.723671875\n",
      "16000: acc=0.73625\n",
      "19200: acc=0.7463541666666667\n",
      "22400: acc=0.7560714285714286\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(214.1013875559821, 0.7626759436980166)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_epoch_emb(net,train_loader, lr=4, epoch_size=25000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在我们的案例中，准确率并没有显著提升，这可能是由于词汇差异较大。  \n",
    "为了解决词汇差异的问题，我们可以采用以下解决方案：  \n",
    "* 重新训练 word2vec 模型以适应我们的词汇  \n",
    "* 使用预训练的 word2vec 模型的词汇加载我们的数据集。在加载数据集时，可以指定使用的词汇。  \n",
    "\n",
    "后一种方法似乎更简单，尤其是因为 PyTorch 的 `torchtext` 框架内置了对嵌入的支持。例如，我们可以通过以下方式实例化基于 GloVe 的词汇：  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|█████████▉| 399999/400000 [00:15<00:00, 25411.14it/s]\n"
     ]
    }
   ],
   "source": [
    "vocab = torchtext.vocab.GloVe(name='6B', dim=50)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "加载的词汇表具有以下基本操作：\n",
    "* `vocab.stoi` 字典允许我们将单词转换为其在字典中的索引\n",
    "* `vocab.itos` 则执行相反的操作——将数字转换为单词\n",
    "* `vocab.vectors` 是嵌入向量的数组，因此要获取单词 `s` 的嵌入，我们需要使用 `vocab.vectors[vocab.stoi[s]]`\n",
    "\n",
    "以下是操作嵌入的一个示例，用来展示方程 **kind-man+woman = queen**（我稍微调整了一下系数以使其生效）：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'queen'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# get the vector corresponding to kind-man+woman\n",
    "qvec = vocab.vectors[vocab.stoi['king']]-vocab.vectors[vocab.stoi['man']]+1.3*vocab.vectors[vocab.stoi['woman']]\n",
    "# find the index of the closest embedding vector \n",
    "d = torch.sum((vocab.vectors-qvec)**2,dim=1)\n",
    "min_idx = torch.argmin(d)\n",
    "# find the corresponding word\n",
    "vocab.itos[min_idx]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要使用这些嵌入训练分类器，我们首先需要使用GloVe词汇表对数据集进行编码：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def offsetify(b):\n",
    "    # first, compute data tensor from all sequences\n",
    "    x = [torch.tensor(encode(t[1],voc=vocab)) for t in b] # pass the instance of vocab to encode function!\n",
    "    # now, compute the offsets by accumulating the tensor of sequence lengths\n",
    "    o = [0] + [len(t) for t in x]\n",
    "    o = torch.tensor(o[:-1]).cumsum(dim=0)\n",
    "    return ( \n",
    "        torch.LongTensor([t[0]-1 for t in b]), # labels\n",
    "        torch.cat(x), # text \n",
    "        o\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "正如我们上面所看到的，所有向量嵌入都存储在 `vocab.vectors` 矩阵中。通过简单的复制操作，可以非常轻松地将这些权重加载到嵌入层的权重中：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "net = EmbedClassifier(len(vocab),len(vocab.vectors[0]),len(classes))\n",
    "net.embedding.weight.data = vocab.vectors\n",
    "net = net.to(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在让我们训练我们的模型，看看是否能获得更好的结果：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3200: acc=0.6271875\n",
      "6400: acc=0.68078125\n",
      "9600: acc=0.7030208333333333\n",
      "12800: acc=0.71984375\n",
      "16000: acc=0.7346875\n",
      "19200: acc=0.7455729166666667\n",
      "22400: acc=0.7529464285714286\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(35.53972978646833, 0.7575175943698017)"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, collate_fn=offsetify, shuffle=True)\n",
    "train_epoch_emb(net,train_loader, lr=4, epoch_size=25000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们没有看到准确率显著提高的原因之一是因为我们数据集中的一些词在预训练的GloVe词汇表中缺失，因此它们实际上被忽略了。为了克服这一问题，我们可以在我们的数据集上训练自己的嵌入。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 上下文嵌入\n",
    "\n",
    "传统预训练嵌入表示（如 Word2Vec）的一个主要局限是词义消歧问题。虽然预训练嵌入可以在一定程度上捕捉单词在上下文中的含义，但每个单词的所有可能含义都会被编码到同一个嵌入中。这可能会导致下游模型出现问题，因为许多单词（例如“play”）的含义会根据使用的上下文而有所不同。\n",
    "\n",
    "例如，“play”在以下两句话中的含义就完全不同：\n",
    "- 我去剧院看了一场**戏剧**。\n",
    "- 约翰想和他的朋友们一起**玩**。\n",
    "\n",
    "上述预训练嵌入将“play”的这两种含义表示为同一个嵌入。为了克服这一局限，我们需要基于**语言模型**来构建嵌入。语言模型是在大规模文本语料库上训练的，它*了解*单词如何在不同的上下文中组合。关于上下文嵌入的讨论超出了本教程的范围，但我们将在下一单元讨论语言模型时回到这个话题。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n---\n\n**免责声明**：  \n本文档使用AI翻译服务[Co-op Translator](https://github.com/Azure/co-op-translator)进行翻译。尽管我们努力确保翻译的准确性，但请注意，自动翻译可能包含错误或不准确之处。应以原文档的原始语言版本作为权威来源。对于关键信息，建议使用专业人工翻译。我们对因使用此翻译而引起的任何误解或误读不承担责任。\n"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "0cb620c6d4b9f7a635928804c26cf22403d89d98d79684e4529119355ee6d5a5"
  },
  "kernelspec": {
   "display_name": "py37_pytorch",
   "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.8.12"
  },
  "coopTranslator": {
   "original_hash": "f50b026abce5cf36783a560ea72cb9b1",
   "translation_date": "2025-08-31T10:55:41+00:00",
   "source_file": "lessons/5-NLP/14-Embeddings/EmbeddingsPyTorch.ipynb",
   "language_code": "zh"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}