第15章自然言語処理:事前学習
15.4.2. Training15.4.2 訓練
Before training the skip-gram model with negative sampling, let’s first define its loss function.
英語のヒント
負例サンプリングでスキップグラムモデルを訓練する前に、まずその損失関数を定義しよう。
15.4.2.1. Binary Cross-Entropy Loss15.4.2.1 二値交差エントロピー損失
According to the definition of the loss function for negative sampling in Section 15.2.1, we will use the binary cross-entropy loss.
英語のヒント
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()Recall our descriptions of the mask variable and the label variable in Section 15.3.5. The following calculates the binary cross-entropy loss for the given variables.
英語のヒント
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])Below shows how the above results are calculated (in a less efficient way) using the sigmoid activation function in the binary cross-entropy loss. We can consider the two outputs as two normalized losses that are averaged over non-masked predictions.
英語のヒント
以下に、上の結果が、二値交差エントロピー損失の中のシグモイド活性化関数を使って(もっと効率の悪いやり方で)どう計算されるかを示す。二つの出力は、マスクされていない予測について平均した、正規化された二つの損失とみなせる。
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.846215.4.2.2. Initializing Model Parameters15.4.2.2 モデルのパラメータを初期化する
We define two embedding layers for all the words in the vocabulary when they are used as center words and context words, respectively. The word vector dimension
embed_size is set to 100.英語のヒント
語彙のすべての単語について、中心語として使われるときと文脈語として使われるときのための、二つの埋め込み層をそれぞれ定義する。単語ベクトルの次元
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))15.4.2.3. Defining the Training Loop15.4.2.3 訓練ループを定義する
The training loop is defined below. Because of the existence of padding, the calculation of the loss function is slightly different compared to the previous training functions.
英語のヒント
訓練ループは以下で定義する。パディングがあるため、損失関数の計算は、これまでの訓練関数と比べて少し異なる。
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)}')Now we can train a skip-gram model using negative sampling.
英語のヒント
これで、負例サンプリングを使ってスキップグラムモデルを訓練できる。
lr, num_epochs = 0.002, 5
train(net, data_iter, lr, num_epochs)loss 0.410, 223485.0 tokens/sec on cuda:0