{ "cells": [ { "cell_type": "markdown", "id": "01f456ba", "metadata": { "origin_pos": 0 }, "source": [ "# 预训练word2vec\n", ":label:`sec_word2vec_pretraining`\n", "\n", "我们继续实现 :numref:`sec_word2vec`中定义的跳元语法模型。然后,我们将在PTB数据集上使用负采样预训练word2vec。首先,让我们通过调用`d2l.load_data_ptb`函数来获得该数据集的数据迭代器和词表,该函数在 :numref:`sec_word2vec_data`中进行了描述。\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "0aeafaa5", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:10.079752Z", "iopub.status.busy": "2023-08-18T07:16:10.079196Z", "iopub.status.idle": "2023-08-18T07:16:27.336361Z", "shell.execute_reply": "2023-08-18T07:16:27.335336Z" }, "origin_pos": 2, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "import math\n", "import torch\n", "from torch import nn\n", "from d2l import torch as d2l\n", "\n", "batch_size, max_window_size, num_noise_words = 512, 5, 5\n", "data_iter, vocab = d2l.load_data_ptb(batch_size, max_window_size,\n", " num_noise_words)" ] }, { "cell_type": "markdown", "id": "d0cf231a", "metadata": { "origin_pos": 4 }, "source": [ "## 跳元模型\n", "\n", "我们通过嵌入层和批量矩阵乘法实现了跳元模型。首先,让我们回顾一下嵌入层是如何工作的。\n", "\n", "### 嵌入层\n", "\n", "如 :numref:`sec_seq2seq`中所述,嵌入层将词元的索引映射到其特征向量。该层的权重是一个矩阵,其行数等于字典大小(`input_dim`),列数等于每个标记的向量维数(`output_dim`)。在词嵌入模型训练之后,这个权重就是我们所需要的。\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "773b7192", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.340860Z", "iopub.status.busy": "2023-08-18T07:16:27.340156Z", "iopub.status.idle": "2023-08-18T07:16:27.365326Z", "shell.execute_reply": "2023-08-18T07:16:27.364347Z" }, "origin_pos": 6, "tab": [ "pytorch" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Parameter embedding_weight (torch.Size([20, 4]), dtype=torch.float32)\n" ] } ], "source": [ "embed = nn.Embedding(num_embeddings=20, embedding_dim=4)\n", "print(f'Parameter embedding_weight ({embed.weight.shape}, '\n", " f'dtype={embed.weight.dtype})')" ] }, { "cell_type": "markdown", "id": "80720da7", "metadata": { "origin_pos": 8 }, "source": [ "嵌入层的输入是词元(词)的索引。对于任何词元索引$i$,其向量表示可以从嵌入层中的权重矩阵的第$i$行获得。由于向量维度(`output_dim`)被设置为4,因此当小批量词元索引的形状为(2,3)时,嵌入层返回具有形状(2,3,4)的向量。\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "1fa70f42", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.368945Z", "iopub.status.busy": "2023-08-18T07:16:27.368367Z", "iopub.status.idle": "2023-08-18T07:16:27.377116Z", "shell.execute_reply": "2023-08-18T07:16:27.376157Z" }, "origin_pos": 9, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[[-1.4754, -0.3612, -0.4246, 0.5805],\n", " [-0.3160, 0.8830, 0.5328, 0.2179],\n", " [-0.0378, -0.5559, 1.4525, 0.6230]],\n", "\n", " [[ 0.0829, -1.0549, 0.6381, 0.7886],\n", " [-0.3862, -0.1291, 0.4160, -0.6710],\n", " [-0.4056, 0.0370, -0.6308, -0.2865]]], grad_fn=)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = torch.tensor([[1, 2, 3], [4, 5, 6]])\n", "embed(x)" ] }, { "cell_type": "markdown", "id": "4b441409", "metadata": { "origin_pos": 10 }, "source": [ "### 定义前向传播\n", "\n", "在前向传播中,跳元语法模型的输入包括形状为(批量大小,1)的中心词索引`center`和形状为(批量大小,`max_len`)的上下文与噪声词索引`contexts_and_negatives`,其中`max_len`在 :numref:`subsec_word2vec-minibatch-loading`中定义。这两个变量首先通过嵌入层从词元索引转换成向量,然后它们的批量矩阵相乘(在 :numref:`subsec_batch_dot`中描述)返回形状为(批量大小,1,`max_len`)的输出。输出中的每个元素是中心词向量和上下文或噪声词向量的点积。\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "cd4cc024", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.380875Z", "iopub.status.busy": "2023-08-18T07:16:27.380348Z", "iopub.status.idle": "2023-08-18T07:16:27.385076Z", "shell.execute_reply": "2023-08-18T07:16:27.384084Z" }, "origin_pos": 12, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "def skip_gram(center, contexts_and_negatives, embed_v, embed_u):\n", " v = embed_v(center)\n", " u = embed_u(contexts_and_negatives)\n", " pred = torch.bmm(v, u.permute(0, 2, 1))\n", " return pred" ] }, { "cell_type": "markdown", "id": "2b5dc971", "metadata": { "origin_pos": 14 }, "source": [ "让我们为一些样例输入打印此`skip_gram`函数的输出形状。\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "1747bbfa", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.388992Z", "iopub.status.busy": "2023-08-18T07:16:27.388308Z", "iopub.status.idle": "2023-08-18T07:16:27.396357Z", "shell.execute_reply": "2023-08-18T07:16:27.395365Z" }, "origin_pos": 16, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "torch.Size([2, 1, 4])" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "skip_gram(torch.ones((2, 1), dtype=torch.long),\n", " torch.ones((2, 4), dtype=torch.long), embed, embed).shape" ] }, { "cell_type": "markdown", "id": "dde6d712", "metadata": { "origin_pos": 18 }, "source": [ "## 训练\n", "\n", "在训练带负采样的跳元模型之前,我们先定义它的损失函数。\n", "\n", "### 二元交叉熵损失\n", "\n", "根据 :numref:`subsec_negative-sampling`中负采样损失函数的定义,我们将使用二元交叉熵损失。\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "5ec8d9c3", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.400654Z", "iopub.status.busy": "2023-08-18T07:16:27.400159Z", "iopub.status.idle": "2023-08-18T07:16:27.405793Z", "shell.execute_reply": "2023-08-18T07:16:27.404774Z" }, "origin_pos": 20, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "class SigmoidBCELoss(nn.Module):\n", " # 带掩码的二元交叉熵损失\n", " def __init__(self):\n", " super().__init__()\n", "\n", " def forward(self, inputs, target, mask=None):\n", " out = nn.functional.binary_cross_entropy_with_logits(\n", " inputs, target, weight=mask, reduction=\"none\")\n", " return out.mean(dim=1)\n", "\n", "loss = SigmoidBCELoss()" ] }, { "cell_type": "markdown", "id": "9dd7eefc", "metadata": { "origin_pos": 22 }, "source": [ "回想一下我们在 :numref:`subsec_word2vec-minibatch-loading`中对掩码变量和标签变量的描述。下面计算给定变量的二进制交叉熵损失。\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "0e0fcee0", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.410664Z", "iopub.status.busy": "2023-08-18T07:16:27.409825Z", "iopub.status.idle": "2023-08-18T07:16:27.423445Z", "shell.execute_reply": "2023-08-18T07:16:27.422478Z" }, "origin_pos": 23, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([0.9352, 1.8462])" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pred = torch.tensor([[1.1, -2.2, 3.3, -4.4]] * 2)\n", "label = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])\n", "mask = torch.tensor([[1, 1, 1, 1], [1, 1, 0, 0]])\n", "loss(pred, label, mask) * mask.shape[1] / mask.sum(axis=1)" ] }, { "cell_type": "markdown", "id": "4bcfe374", "metadata": { "origin_pos": 25 }, "source": [ "下面显示了如何使用二元交叉熵损失中的Sigmoid激活函数(以较低效率的方式)计算上述结果。我们可以将这两个输出视为两个规范化的损失,在非掩码预测上进行平均。\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "b79ec9c9", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.427864Z", "iopub.status.busy": "2023-08-18T07:16:27.427357Z", "iopub.status.idle": "2023-08-18T07:16:27.432489Z", "shell.execute_reply": "2023-08-18T07:16:27.431711Z" }, "origin_pos": 26, "tab": [ "pytorch" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.9352\n", "1.8462\n" ] } ], "source": [ "def sigmd(x):\n", " return -math.log(1 / (1 + math.exp(-x)))\n", "\n", "print(f'{(sigmd(1.1) + sigmd(2.2) + sigmd(-3.3) + sigmd(4.4)) / 4:.4f}')\n", "print(f'{(sigmd(-1.1) + sigmd(-2.2)) / 2:.4f}')" ] }, { "cell_type": "markdown", "id": "0cab2e83", "metadata": { "origin_pos": 27 }, "source": [ "### 初始化模型参数\n", "\n", "我们定义了两个嵌入层,将词表中的所有单词分别作为中心词和上下文词使用。字向量维度`embed_size`被设置为100。\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "8a373a4d", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.436933Z", "iopub.status.busy": "2023-08-18T07:16:27.436455Z", "iopub.status.idle": "2023-08-18T07:16:27.461291Z", "shell.execute_reply": "2023-08-18T07:16:27.460112Z" }, "origin_pos": 29, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "embed_size = 100\n", "net = nn.Sequential(nn.Embedding(num_embeddings=len(vocab),\n", " embedding_dim=embed_size),\n", " nn.Embedding(num_embeddings=len(vocab),\n", " embedding_dim=embed_size))" ] }, { "cell_type": "markdown", "id": "7d9e7090", "metadata": { "origin_pos": 30 }, "source": [ "### 定义训练阶段代码\n", "\n", "训练阶段代码实现定义如下。由于填充的存在,损失函数的计算与以前的训练函数略有不同。\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "763d58ba", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.466398Z", "iopub.status.busy": "2023-08-18T07:16:27.466107Z", "iopub.status.idle": "2023-08-18T07:16:27.478915Z", "shell.execute_reply": "2023-08-18T07:16:27.477777Z" }, "origin_pos": 32, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "def train(net, data_iter, lr, num_epochs, device=d2l.try_gpu()):\n", " def init_weights(m):\n", " if type(m) == nn.Embedding:\n", " nn.init.xavier_uniform_(m.weight)\n", " net.apply(init_weights)\n", " net = net.to(device)\n", " optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n", " animator = d2l.Animator(xlabel='epoch', ylabel='loss',\n", " xlim=[1, num_epochs])\n", " # 规范化的损失之和,规范化的损失数\n", " metric = d2l.Accumulator(2)\n", " for epoch in range(num_epochs):\n", " timer, num_batches = d2l.Timer(), len(data_iter)\n", " for i, batch in enumerate(data_iter):\n", " optimizer.zero_grad()\n", " center, context_negative, mask, label = [\n", " data.to(device) for data in batch]\n", "\n", " pred = skip_gram(center, context_negative, net[0], net[1])\n", " l = (loss(pred.reshape(label.shape).float(), label.float(), mask)\n", " / mask.sum(axis=1) * mask.shape[1])\n", " l.sum().backward()\n", " optimizer.step()\n", " metric.add(l.sum(), l.numel())\n", " if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:\n", " animator.add(epoch + (i + 1) / num_batches,\n", " (metric[0] / metric[1],))\n", " print(f'loss {metric[0] / metric[1]:.3f}, '\n", " f'{metric[1] / timer.stop():.1f} tokens/sec on {str(device)}')" ] }, { "cell_type": "markdown", "id": "ee280a14", "metadata": { "origin_pos": 34 }, "source": [ "现在,我们可以使用负采样来训练跳元模型。\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "c10e8868", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:27.484286Z", "iopub.status.busy": "2023-08-18T07:16:27.483558Z", "iopub.status.idle": "2023-08-18T07:16:54.164551Z", "shell.execute_reply": "2023-08-18T07:16:54.163546Z" }, "origin_pos": 35, "tab": [ "pytorch" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "loss 0.410, 377799.5 tokens/sec on cuda:0\n" ] }, { "data": { "image/svg+xml": [ "\n", "\n", "\n", " \n", " \n", " \n", " \n", " 2023-08-18T07:16:54.129082\n", " image/svg+xml\n", " \n", " \n", " Matplotlib v3.5.1, https://matplotlib.org/\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n" ], "text/plain": [ "
" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "lr, num_epochs = 0.002, 5\n", "train(net, data_iter, lr, num_epochs)" ] }, { "cell_type": "markdown", "id": "9be0d868", "metadata": { "origin_pos": 36 }, "source": [ "## 应用词嵌入\n", ":label:`subsec_apply-word-embed`\n", "\n", "在训练word2vec模型之后,我们可以使用训练好模型中词向量的余弦相似度来从词表中找到与输入单词语义最相似的单词。\n" ] }, { "cell_type": "code", "execution_count": 12, "id": "7cb4d2b0", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T07:16:54.168436Z", "iopub.status.busy": "2023-08-18T07:16:54.168121Z", "iopub.status.idle": "2023-08-18T07:16:54.176483Z", "shell.execute_reply": "2023-08-18T07:16:54.175544Z" }, "origin_pos": 38, "tab": [ "pytorch" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cosine sim=0.773: microprocessor\n", "cosine sim=0.589: hitachi\n", "cosine sim=0.582: computers\n" ] } ], "source": [ "def get_similar_tokens(query_token, k, embed):\n", " W = embed.weight.data\n", " x = W[vocab[query_token]]\n", " # 计算余弦相似性。增加1e-9以获得数值稳定性\n", " cos = torch.mv(W, x) / torch.sqrt(torch.sum(W * W, dim=1) *\n", " torch.sum(x * x) + 1e-9)\n", " topk = torch.topk(cos, k=k+1)[1].cpu().numpy().astype('int32')\n", " for i in topk[1:]: # 删除输入词\n", " print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')\n", "\n", "get_similar_tokens('chip', 3, net[0])" ] }, { "cell_type": "markdown", "id": "1b343f9c", "metadata": { "origin_pos": 40 }, "source": [ "## 小结\n", "\n", "* 我们可以使用嵌入层和二元交叉熵损失来训练带负采样的跳元模型。\n", "* 词嵌入的应用包括基于词向量的余弦相似度为给定词找到语义相似的词。\n", "\n", "## 练习\n", "\n", "1. 使用训练好的模型,找出其他输入词在语义上相似的词。您能通过调优超参数来改进结果吗?\n", "1. 当训练语料库很大时,在更新模型参数时,我们经常对当前小批量的*中心词*进行上下文词和噪声词的采样。换言之,同一中心词在不同的训练迭代轮数可以有不同的上下文词或噪声词。这种方法的好处是什么?尝试实现这种训练方法。\n" ] }, { "cell_type": "markdown", "id": "99139c06", "metadata": { "origin_pos": 42, "tab": [ "pytorch" ] }, "source": [ "[Discussions](https://discuss.d2l.ai/t/5740)\n" ] } ], "metadata": { "language_info": { "name": "python" }, "required_libs": [] }, "nbformat": 4, "nbformat_minor": 5 }