第16章自然言語処理:応用
16.3.3. The textCNN Model16.3.3 textCNNモデル
Using the one-dimensional convolution and max-over-time pooling, the textCNN model takes individual pretrained token representations as input, then obtains and transforms sequence representations for the downstream application.
英語のヒント
1次元の畳み込みと時間方向の最大プーリングを使って、textCNNモデルは、事前学習した個々のトークンの表現を入力にとり、下流の応用のための系列の表現を得て変換する。
For a single text sequence with tokens represented by -dimensional vectors, the width, height, and number of channels of the input tensor are , , and , respectively. The textCNN model transforms the input into the output as follows:
英語のヒント
次元のベクトルで表された個のトークンからなる単一のテキストの系列について、入力テンソルの幅、高さ、チャネル数は、それぞれ、、である。textCNNモデルは、入力を次のように出力に変換する。
- Define multiple one-dimensional convolution kernels and perform convolution operations separately on the inputs. Convolution kernels with different widths may capture local features among different numbers of adjacent tokens.
英語のヒント
複数の1次元の畳み込みカーネルを定義し、入力に対して別々に畳み込みの演算を行う。幅の異なる畳み込みカーネルは、異なる数の隣り合うトークンの間の局所的な特徴をとらえうる。 - Perform max-over-time pooling on all the output channels, and then concatenate all the scalar pooling outputs as a vector.
英語のヒント
すべての出力チャネルに時間方向の最大プーリングを行い、それからプーリングのスカラー出力をすべてベクトルとして連結する。 - Transform the concatenated vector into the output categories using the fully connected layer. Dropout can be used for reducing overfitting.
英語のヒント
全結合層を使って、連結したベクトルを出力のカテゴリに変換する。過学習を減らすためにドロップアウトを使える。
Fig. 16.3.5図16.3.5
The model architecture of textCNN.
英語のヒント
textCNNのモデルのアーキテクチャ。
Fig. 16.3.5 illustrates the model architecture of textCNN with a concrete example. The input is a sentence with 11 tokens, where each token is represented by a 6-dimensional vectors. So we have a 6-channel input with width 11. Define two one-dimensional convolution kernels of widths 2 and 4, with 4 and 5 output channels, respectively. They produce 4 output channels with width and 5 output channels with width . Despite different widths of these 9 channels, the max-over-time pooling gives a concatenated 9-dimensional vector, which is finally transformed into a 2-dimensional output vector for binary sentiment predictions.
英語のヒント
図16.3.5は、具体的な例でtextCNNのモデルのアーキテクチャを示している。入力は11個のトークンからなる文で、各トークンは6次元のベクトルで表される。したがって、幅11の6チャネルの入力がある。幅が2と4の二つの1次元の畳み込みカーネルを、出力チャネルがそれぞれ4と5になるように定義する。これらは、幅の4個の出力チャネルと、幅の5個の出力チャネルを作る。この9個のチャネルは幅が異なるが、時間方向の最大プーリングは連結した9次元のベクトルを与え、それが最後に、感情の二値予測のための2次元の出力ベクトルに変換される。
16.3.3.1. Defining the Model16.3.3.1 モデルを定義する
We implement the textCNN model in the following class. Compared with the bidirectional RNN model in Section 16.2, besides replacing recurrent layers with convolutional layers, we also use two embedding layers: one with trainable weights and the other with fixed weights.
英語のヒント
次のクラスでtextCNNモデルを実装する。16.2節の双方向RNNモデルと比べて、リカレント層を畳み込み層に置き換えるほかに、二つの埋め込み層も使う。一つは訓練できる重みをもち、もう一つは固定した重みをもつ。
class TextCNN(nn.Module):
def __init__(self, vocab_size, embed_size, kernel_sizes, num_channels,
**kwargs):
super(TextCNN, self).__init__(**kwargs)
self.embedding = nn.Embedding(vocab_size, embed_size)
# The embedding layer not to be trained
self.constant_embedding = nn.Embedding(vocab_size, embed_size)
self.dropout = nn.Dropout(0.5)
self.decoder = nn.Linear(sum(num_channels), 2)
# The max-over-time pooling layer has no parameters, so this instance
# can be shared
self.pool = nn.AdaptiveAvgPool1d(1)
self.relu = nn.ReLU()
# Create multiple one-dimensional convolutional layers
self.convs = nn.ModuleList()
for c, k in zip(num_channels, kernel_sizes):
self.convs.append(nn.Conv1d(2 * embed_size, c, k))
def forward(self, inputs):
# Concatenate two embedding layer outputs with shape (batch size, no.
# of tokens, token vector dimension) along vectors
embeddings = torch.cat((
self.embedding(inputs), self.constant_embedding(inputs)), dim=2)
# Per the input format of one-dimensional convolutional layers,
# rearrange the tensor so that the second dimension stores channels
embeddings = embeddings.permute(0, 2, 1)
# For each one-dimensional convolutional layer, after max-over-time
# pooling, a tensor of shape (batch size, no. of channels, 1) is
# obtained. Remove the last dimension and concatenate along channels
encoding = torch.cat([
torch.squeeze(self.relu(self.pool(conv(embeddings))), dim=-1)
for conv in self.convs], dim=1)
outputs = self.decoder(self.dropout(encoding))
return outputsLet’s create a textCNN instance. It has 3 convolutional layers with kernel widths of 3, 4, and 5, all with 100 output channels.
英語のヒント
textCNNのインスタンスを作ろう。これは、カーネルの幅が3、4、5の三つの畳み込み層をもち、どれも出力チャネルは100である。
embed_size, kernel_sizes, nums_channels = 100, [3, 4, 5], [100, 100, 100]
devices = d2l.try_all_gpus()
net = TextCNN(len(vocab), embed_size, kernel_sizes, nums_channels)
def init_weights(module):
if type(module) in (nn.Linear, nn.Conv1d):
nn.init.xavier_uniform_(module.weight)
net.apply(init_weights);16.3.3.2. Loading Pretrained Word Vectors16.3.3.2 事前学習した単語ベクトルを読み込む
Same as Section 16.2, we load pretrained 100-dimensional GloVe embeddings as the initialized token representations. These token representations (embedding weights) will be trained in
embedding and fixed in constant_embedding.英語のヒント
16.2節と同じように、初期化したトークンの表現として、事前学習した100次元のGloVeの埋め込みを読み込む。これらのトークンの表現(埋め込みの重み)は、
embeddingでは訓練され、constant_embeddingでは固定される。glove_embedding = d2l.TokenEmbedding('glove.6b.100d')
embeds = glove_embedding[vocab.idx_to_token]
net.embedding.weight.data.copy_(embeds)
net.constant_embedding.weight.data.copy_(embeds)
net.constant_embedding.weight.requires_grad = False16.3.3.3. Training and Evaluating the Model16.3.3.3 モデルを訓練し評価する
Now we can train the textCNN model for sentiment analysis.
英語のヒント
これで、感情分析のためにtextCNNモデルを訓練できる。
lr, num_epochs = 0.001, 5
trainer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction="none")
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)loss 0.066, train acc 0.979, test acc 0.868
4354.2 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]Below we use the trained model to predict the sentiment for two simple sentences.
英語のヒント
以下では、訓練したモデルを使って、二つの簡単な文の感情を予測する。
d2l.predict_sentiment(net, vocab, 'this movie is so great')'positive'd2l.predict_sentiment(net, vocab, 'this movie is so bad')'negative'