プリンキピア

第15章自然言語処理:事前学習

15.4.1. The Skip-Gram Model15.4.1 スキップグラムモデル

We implement the skip-gram model by using embedding layers and batch matrix multiplications. First, let’s review how embedding layers work.
英語のヒント
スキップグラムモデルは、埋め込み層とバッチ行列積を使って実装する。まず、埋め込み層がどう働くかを復習しよう。

15.4.1.1. Embedding Layer15.4.1.1 埋め込み層

As described in Section 10.7, an embedding layer maps a token’s index to its feature vector. The weight of this layer is a matrix whose number of rows equals to the dictionary size (input_dim) and number of columns equals to the vector dimension for each token (output_dim). After a word embedding model is trained, this weight is what we need.
英語のヒント
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)
The input of an embedding layer is the index of a token (word). For any token index i, its vector representation can be obtained from the ith row of the weight matrix in the embedding layer. Since the vector dimension (output_dim) was set to 4, the embedding layer returns vectors with shape (2, 3, 4) for a minibatch of token indices with shape (2, 3).
英語のヒント
埋め込み層の入力は、トークン(単語)のインデックスである。任意のトークンのインデックスiについて、そのベクトル表現は、埋め込み層の重み行列のithの行から得られる。ベクトルの次元(output_dim)は4に設定したので、埋め込み層は、形状が(2, 3)のトークンのインデックスのミニバッチに対して、形状が(2, 3, 4)のベクトルを返す。
x = torch.tensor([[1, 2, 3], [4, 5, 6]])
embed(x)
tensor([[[ 0.7606,  0.3872, -0.1864,  1.1732],
         [ 1.5035,  2.3623, -1.7542, -1.4990],
         [-1.2639, -1.5313,  2.1719,  0.4151]],

        [[-1.9079,  0.2434,  1.5395,  1.2990],
         [ 0.7470,  1.0129,  0.4039,  0.0591],
         [-0.6293, -0.1814, -0.4782, -0.5289]]], grad_fn=<EmbeddingBackward0>)

15.4.1.2. Defining the Forward Propagation15.4.1.2 順伝播を定義する

In the forward propagation, the input of the skip-gram model includes the center word indices center of shape (batch size, 1) and the concatenated context and noise word indices contexts_and_negatives of shape (batch size, max_len), where max_len is defined in Section 15.3.5. These two variables are first transformed from the token indices into vectors via the embedding layer, then their batch matrix multiplication (described in Section 11.3.2.2) returns an output of shape (batch size, 1, max_len). Each element in the output is the dot product of a center word vector and a context or noise word vector.
英語のヒント
順伝播では、スキップグラムモデルの入力は、形状が(バッチの大きさ, 1)の中心語のインデックスcenterと、形状が(バッチの大きさ, max_len)の、連結した文脈語とノイズ語のインデックスcontexts_and_negativesを含む。ここで、max_lenは15.3.5節で定義したものである。この二つの変数は、まず埋め込み層を通じてトークンのインデックスからベクトルに変換され、それからそれらのバッチ行列積(11.3.2.2節で説明した)が、形状が(バッチの大きさ, 1, max_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
Let’s print the output shape of this skip_gram function for some example inputs.
英語のヒント
いくつかの入力の例について、この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])