电子说
我们继续实现 15.1 节中定义的 skip-gram 模型。然后我们将在 PTB 数据集上使用负采样来预训练 word2vec。首先,让我们通过调用函数来获取数据迭代器和这个数据集的词汇表 ,这在第 15.3 节d2l.load_data_ptb中有描述
import math
import torch
from torch import nn
from d2l import torch as d2l
batch_size, max_window_size, num_noise_words = 512, 5, 5
data_iter, vocab = d2l.load_data_ptb(batch_size, max_window_size,
num_noise_words)
Downloading ../data/ptb.zip from http://d2l-data.s3-accelerate.amazonaws.com/ptb.zip...
import math
from mxnet import autograd, gluon, np, npx
from mxnet.gluon import nn
from d2l import mxnet as d2l
npx.set_np()
batch_size, max_window_size, num_noise_words = 512, 5, 5
data_iter, vocab = d2l.load_data_ptb(batch_size, max_window_size,
num_noise_words)
15.4.1。Skip-Gram 模型
我们通过使用嵌入层和批量矩阵乘法来实现 skip-gram 模型。首先,让我们回顾一下嵌入层是如何工作的。
15.4.1.1。嵌入层
如第 10.7 节所述,嵌入层将标记的索引映射到其特征向量。该层的权重是一个矩阵,其行数等于字典大小 ( input_dim),列数等于每个标记的向量维数 ( output_dim)。一个词嵌入模型训练好之后,这个权重就是我们所需要的。
embed = nn.Embedding(num_embeddings=20, embedding_dim=4)
print(f'Parameter embedding_weight ({embed.weight.shape}, '
f'dtype={embed.weight.dtype})')
Parameter embedding_weight (torch.Size([20, 4]), dtype=torch.float32)
embed = nn.Embedding(input_dim=20, output_dim=4) embed.initialize() embed.weight
Parameter embedding0_weight (shape=(20, 4), dtype=float32)
嵌入层的输入是标记(单词)的索引。对于任何令牌索引i,它的向量表示可以从ith嵌入层中权重矩阵的行。由于向量维度 ( output_dim) 设置为 4,因此嵌入层返回形状为 (2, 3, 4) 的向量,用于形状为 (2, 3) 的标记索引的小批量。
x = torch.tensor([[1, 2, 3], [4, 5, 6]]) embed(x)
tensor([[[-0.6501, 1.3547, 0.7968, 0.3916],
[ 0.4739, -0.0944, 1.2308, 0.6457],
[ 0.4539, 1.5194, 0.4377, -1.5122]],
[[-0.7032, -0.1213, 0.2657, -0.6797],
[ 0.2930, -0.6564, 0.8960, -0.5637],
[-0.1815, 0.9487, 0.8482, 0.5486]]], grad_fn=)
x = np.array([[1, 2, 3], [4, 5, 6]]) embed(x)
array([[[ 0.01438687, 0.05011239, 0.00628365, 0.04861524],
[-0.01068833, 0.01729892, 0.02042518, -0.01618656],
[-0.00873779, -0.02834515, 0.05484822, -0.06206018]],
[[ 0.06491279, -0.03182812, -0.01631819, -0.00312688],
[ 0.0408415 , 0.04370362, 0.00404529, -0.0028032 ],
[ 0.00952624, -0.01501013, 0.05958354, 0.04705103]]])
15.4.1.2。定义前向传播
在正向传播中,skip-gram 模型的输入包括形状为(批大小,1)的中心词索引和 形状为(批大小,)center的连接上下文和噪声词索引,其中定义在 第 15.3.5 节. 这两个变量首先通过嵌入层从标记索引转换为向量,然后它们的批量矩阵乘法(在第 11.3.2.2 节中描述)返回形状为(批量大小,1, )的输出 。输出中的每个元素都是中心词向量与上下文或噪声词向量的点积。contexts_and_negativesmax_lenmax_lenmax_len
def skip_gram(center, contexts_and_negatives, embed_v, embed_u): v = embed_v(center) u = embed_u(contexts_and_negatives) pred = torch.bmm(v, u.permute(0, 2, 1)) return pred
def skip_gram(center, contexts_and_negatives, embed_v, embed_u): v = embed_v(center) u = embed_u(contexts_and_negatives) pred = npx.batch_dot(v, u.swapaxes(1, 2)) return pred
skip_gram让我们为一些示例输入打印此函数的输出形状。
skip_gram(torch.ones((2, 1), dtype=torch.long),
torch.ones((2, 4), dtype=torch.long), embed, embed).shape
torch.Size([2, 1, 4])
skip_gram(np.ones((2, 1)), np.ones((2, 4)), embed, embed).shape
(2, 1, 4)
15.4.2。训练
在用负采样训练skip-gram模型之前,我们先定义它的损失函数。
15.4.2.1。二元交叉熵损失
根据15.2.1节负采样损失函数的定义,我们将使用二元交叉熵损失。
class SigmoidBCELoss(nn.Module):
# Binary cross-entropy loss with masking
def __init__(self):
super().__init__()
def forward(self, inputs, target, mask=None):
out = nn.functional.binary_cross_entropy_with_logits(
inputs, target, weight=mask, reduction="none")
return out.mean(dim=1)
loss = SigmoidBCELoss()
loss = gluon.loss.SigmoidBCELoss()
回想我们在第 15.3.5 节中对掩码变量和标签变量的描述 。下面计算给定变量的二元交叉熵损失。
pred = torch.tensor([[1.1, -2.2, 3.3, -4.4]] * 2) label = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]) mask = torch.tensor([[1, 1, 1, 1], [1, 1, 0, 0]]) loss(pred, label, mask) * mask.shape[1] / mask.sum(axis=1)
tensor([0.9352, 1.8462])
pred = np.array([[1.1, -2.2, 3.3, -4.4]] * 2) label = np.array([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]) mask = np.array([[1, 1, 1, 1], [1, 1, 0, 0]]) loss(pred, label, mask) * mask.shape[1] / mask.sum(axis=1)
array([0.93521017, 1.8462094 ])
下面显示了如何使用二元交叉熵损失中的 sigmoid 激活函数计算上述结果(以效率较低的方式)。我们可以将这两个输出视为两个归一化损失,对非掩码预测进行平均。
def sigmd(x):
return -math.log(1 / (1 + math.exp(-x)))
print(f'{(sigmd(1.1) + sigmd(2.2) + sigmd(-3.3) + sigmd(4.4)) / 4:.4f}')
print(f'{(sigmd(-1.1) + sigmd(-2.2)) / 2:.4f}')
0.9352 1.8462
def sigmd(x):
return -math.log(1 / (1 + math.exp(-x)))
print(f'{(sigmd(1.1) + sigmd(2.2) + sigmd(-3.3) + sigmd(4.4)) / 4:.4f}')
print(f'{(sigmd(-1.1) + sigmd(-2.2)) / 2:.4f}')
0.9352 1.8462
15.4.2.2。初始化模型参数
当词汇表中的所有词分别用作中心词和上下文词时,我们为它们定义了两个嵌入层。词向量维度embed_size设置为100。
embed_size = 100
net = nn.Sequential(nn.Embedding(num_embeddings=len(vocab),
embedding_dim=embed_size),
nn.Embedding(num_embeddings=len(vocab),
embedding_dim=embed_size))
embed_size = 100
net = nn.Sequential()
net.add(nn.Embedding(input_dim=len(vocab), output_dim=embed_size),
nn.Embedding(input_dim=len(vocab), output_dim=embed_size))
15.4.2.3。定义训练循环
训练循环定义如下。由于padding的存在,损失函数的计算与之前的训练函数略有不同。
def train(net, data_iter, lr, num_epochs, device=d2l.try_gpu()):
def init_weights(module):
if type(module) == nn.Embedding:
nn.init.xavier_uniform_(module.weight)
net.apply(init_weights)
net = net.to(device)
optimizer = torch.optim.Adam(net.parameters(), lr=lr)
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[1, num_epochs])
# Sum of normalized losses, no. of normalized losses
metric = d2l.Accumulator(2)
for epoch in range(num_epochs):
timer, num_batches = d2l.Timer(), len(data_iter)
for i, batch in enumerate(data_iter):
optimizer.zero_grad()
center, context_negative, mask, label = [
data.to(device) for data in batch]
pred = skip_gram(center, context_negative, net[0], net[1])
l = (loss(pred.reshape(label.shape).float(), label.float(), mask)
/ mask.sum(axis=1) * mask.shape[1])
l.sum().backward()
optimizer.step()
metric.add(l.sum(), l.numel())
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(metric[0] / metric[1],))
print(f'loss {metric[0] / metric[1]:.3f}, '
f'{metric[1] / timer.stop():.1f} tokens/sec on {str(device)}')
def train(net, data_iter, lr, num_epochs, device=d2l.try_gpu()):
net.initialize(ctx=device, force_reinit=True)
trainer = gluon.Trainer(net.collect_params(), 'adam',
{'learning_rate': lr})
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[1, num_epochs])
# Sum of normalized losses, no. of normalized losses
metric = d2l.Accumulator(2)
for epoch in range(num_epochs):
timer, num_batches = d2l.Timer(), len(data_iter)
for i, batch in enumerate(data_iter):
center, context_negative, mask, label = [
data.as_in_ctx(device) for data in batch]
with autograd.record():
pred = skip_gram(center, context_negative, net[0], net[1])
l = (loss(pred.reshape(label.shape), label, mask) *
mask.shape[1] / mask.sum(axis=1))
l.backward()
trainer.step(batch_size)
metric.add(l.sum(), l.size)
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i + 1) / num_batches,
(metric[0] / metric[1],))
print(f'loss {metric[0] / metric[1]:.3f}, '
f'{metric[1] / timer.stop():.1f} tokens/sec on {str(device)}')
现在我们可以使用负采样来训练 skip-gram 模型。
lr, num_epochs = 0.002, 5 train(net, data_iter, lr, num_epochs)
loss 0.410, 170397.2 tokens/sec on cuda:0
lr, num_epochs = 0.002, 5 train(net, data_iter, lr, num_epochs)
loss 0.408, 86715.1 tokens/sec on gpu(0)
15.4.3。应用词嵌入
在训练完 word2vec 模型后,我们可以使用来自训练模型的词向量的余弦相似度来从词典中找到与输入词在语义上最相似的词。
def get_similar_tokens(query_token, k, embed):
W = embed.weight.data
x = W[vocab[query_token]]
# Compute the cosine similarity. Add 1e-9 for numerical stability
cos = torch.mv(W, x) / torch.sqrt(torch.sum(W * W, dim=1) *
torch.sum(x * x) + 1e-9)
topk = torch.topk(cos, k=k+1)[1].cpu().numpy().astype('int32')
for i in topk[1:]: # Remove the input words
print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')
get_similar_tokens('chip', 3, net[0])
cosine sim=0.665: microprocessor cosine sim=0.665: chips cosine sim=0.646: intel
def get_similar_tokens(query_token, k, embed):
W = embed.weight.data()
x = W[vocab[query_token]]
# Compute the cosine similarity. Add 1e-9 for numerical stability
cos = np.dot(W, x) / np.sqrt(np.sum(W * W, axis=1) * np.sum(x * x) + 1e-9)
topk = npx.topk(cos, k=k+1, ret_typ='indices').asnumpy().astype('int32')
for i in topk[1:]: # Remove the input words
print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')
get_similar_tokens('chip', 3, net[0])
cosine sim=0.689: intel cosine sim=0.682: desktop cosine sim=0.616: digital
15.4.4。概括
我们可以使用嵌入层和二元交叉熵损失来训练具有负采样的 skip-gram 模型。
词嵌入的应用包括根据词向量的余弦相似度为给定词寻找语义相似的词。
15.4.5。练习
使用经过训练的模型,为其他输入词找到语义相似的词。你能通过调整超参数来改善结果吗?
当训练语料库很大时,我们在更新模型参数时,往往会在当前minibatch中对中心词进行上下文词和噪声词的采样。换句话说,同一个中心词在不同的训练时期可能有不同的上下文词或噪声词。这种方法有什么好处?尝试实施这种训练方法。
全部0条评论
快来发表一下你的评论吧 !