第16章自然言語処理:応用
16.2.1. Representing Single Text with RNNs16.2.1 RNNで単一のテキストを表す
In text classifications tasks, such as sentiment analysis, a varying-length text sequence will be transformed into fixed-length categories. In the following
BiRNN class, while each token of a text sequence gets its individual pretrained GloVe representation via the embedding layer (self.embedding), the entire sequence is encoded by a bidirectional RNN (self.encoder). More concretely, the hidden states (at the last layer) of the bidirectional LSTM at both the initial and final time steps are concatenated as the representation of the text sequence. This single text representation is then transformed into output categories by a fully connected layer (self.decoder) with two outputs (“positive” and “negative”).英語のヒント
感情分析のようなテキスト分類のタスクでは、可変長のテキストの系列が固定長のカテゴリに変換される。次の
BiRNNクラスでは、テキストの系列の各トークンが埋め込み層(self.embedding)を通じてそれぞれ事前学習したGloVeの表現を得る一方で、系列全体は双方向RNN(self.encoder)で符号化される。もっと具体的には、最初と最後の時間ステップでの双方向LSTMの(最後の層の)隠れ状態を連結したものを、テキストの系列の表現とする。この単一テキストの表現は、それから、二つの出力(「positive」と「negative」)をもつ全結合層(self.decoder)で出力のカテゴリに変換される。class BiRNN(nn.Module):
def __init__(self, vocab_size, embed_size, num_hiddens,
num_layers, **kwargs):
super(BiRNN, self).__init__(**kwargs)
self.embedding = nn.Embedding(vocab_size, embed_size)
# Set `bidirectional` to True to get a bidirectional RNN
self.encoder = nn.LSTM(embed_size, num_hiddens, num_layers=num_layers,
bidirectional=True)
self.decoder = nn.Linear(4 * num_hiddens, 2)
def forward(self, inputs):
# The shape of `inputs` is (batch size, no. of time steps). Because
# LSTM requires its input's first dimension to be the temporal
# dimension, the input is transposed before obtaining token
# representations. The output shape is (no. of time steps, batch size,
# word vector dimension)
embeddings = self.embedding(inputs.T)
self.encoder.flatten_parameters()
# Returns hidden states of the last hidden layer at different time
# steps. The shape of `outputs` is (no. of time steps, batch size,
# 2 * no. of hidden units)
outputs, _ = self.encoder(embeddings)
# Concatenate the hidden states at the initial and final time steps as
# the input of the fully connected layer. Its shape is (batch size,
# 4 * no. of hidden units)
encoding = torch.cat((outputs[0], outputs[-1]), dim=1)
outs = self.decoder(encoding)
return outsLet’s construct a bidirectional RNN with two hidden layers to represent single text for sentiment analysis.
英語のヒント
感情分析のために単一のテキストを表す、隠れ層が二つの双方向RNNを組み立てよう。
embed_size, num_hiddens, num_layers, devices = 100, 100, 2, d2l.try_all_gpus()
net = BiRNN(len(vocab), embed_size, num_hiddens, num_layers)
def init_weights(module):
if type(module) == nn.Linear:
nn.init.xavier_uniform_(module.weight)
if type(module) == nn.LSTM:
for param in module._flat_weights_names:
if "weight" in param:
nn.init.xavier_uniform_(module._parameters[param])
net.apply(init_weights);