プリンキピア

第10章現代のリカレントニューラルネットワーク

10.7.2. Encoder10.7.2 エンコーダ

Recall that the encoder transforms an input sequence of variable length into a fixed-shape context variable 𝐜 (see Fig. 10.7.1).
英語のヒント
エンコーダは、可変長の入力系列を、固定された形状の文脈変数𝐜に変換することを思い出そう(図10.7.1を参照)。
Consider a single sequence example (batch size 1). Suppose the input sequence is x1,…,xT, such that xt is the tth token. At time step t, the RNN transforms the input feature vector 𝐱t for xt and the hidden state 𝐡t−1 from the previous time step into the current hidden state 𝐡t. We can use a function f to express the transformation of the RNN’s recurrent layer:
英語のヒント
一つの系列の事例(バッチサイズ1)を考えよう。入力系列がx1,…,xTで、xtがtthのトークンだとする。時間ステップtで、RNNは、xtの入力特徴ベクトル𝐱tと前の時間ステップの隠れ状態𝐡t−1を、現在の隠れ状態𝐡tに変換する。RNNの再帰的な層の変換を表すのに、関数fを使える。
𝐡t=f(𝐱t,𝐡t−1).(10.7.1)
In general, the encoder transforms the hidden states at all time steps into a context variable through a customized function q:
英語のヒント
一般に、エンコーダは、すべての時間ステップの隠れ状態を、独自の関数qによって文脈変数に変換する。
𝐜=q(𝐡1,…,𝐡T).(10.7.2)
For example, in Fig. 10.7.1, the context variable is just the hidden state 𝐡T corresponding to the encoder RNN’s representation after processing the final token of the input sequence.
英語のヒント
たとえば、図10.7.1では、文脈変数は、入力系列の最後のトークンを処理した後のエンコーダのRNNの表現にあたる隠れ状態𝐡Tにすぎない。
In this example, we have used a unidirectional RNN to design the encoder, where the hidden state only depends on the input subsequence at and before the time step of the hidden state. We can also construct encoders using bidirectional RNNs. In this case, a hidden state depends on the subsequence before and after the time step (including the input at the current time step), which encodes the information of the entire sequence.
英語のヒント
この例では、一方向のRNNを使ってエンコーダを設計した。そこでは、隠れ状態は、その隠れ状態の時間ステップとそれより前の入力の部分系列にだけ依存する。双方向のRNNを使ってエンコーダを組み立てることもできる。この場合、隠れ状態は、その時間ステップの前と後の部分系列(現在の時間ステップの入力を含む)に依存し、系列全体の情報を符号化する。
Now let’s implement the RNN encoder. Note that we use an embedding layer to obtain the feature vector for each token in the input sequence. The weight of an embedding layer is a matrix, where the number of rows corresponds to the size of the input vocabulary (vocab_size) and number of columns corresponds to the feature vector’s dimension (embed_size). For any input token index i, the embedding layer fetches the ith row (starting from 0) of the weight matrix to return its feature vector. Here we implement the encoder with a multilayer GRU.
英語のヒント
では、RNNのエンコーダを実装しよう。入力系列の各トークンの特徴ベクトルを得るために、埋め込み層を使うことに注意してほしい。埋め込み層の重みは行列であり、その行数は入力の語彙の大きさ(vocab_size)に、列数は特徴ベクトルの次元(embed_size)に対応する。任意の入力トークンのインデックスiについて、埋め込み層は重み行列の(0から数えて)ithの行を取り出し、その特徴ベクトルを返す。ここでは、多層のGRUでエンコーダを実装する。
def init_seq2seq(module):  #@save
    """Initialize weights for sequence-to-sequence learning."""
    if type(module) == nn.Linear:
         nn.init.xavier_uniform_(module.weight)
    if type(module) == nn.GRU:
        for param in module._flat_weights_names:
            if "weight" in param:
                nn.init.xavier_uniform_(module._parameters[param])

class Seq2SeqEncoder(d2l.Encoder):  #@save
    """The RNN encoder for sequence-to-sequence learning."""
    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
                 dropout=0):
        super().__init__()
        self.embedding = nn.Embedding(vocab_size, embed_size)
        self.rnn = d2l.GRU(embed_size, num_hiddens, num_layers, dropout)
        self.apply(init_seq2seq)

    def forward(self, X, *args):
        # X shape: (batch_size, num_steps)
        embs = self.embedding(X.t().type(torch.int64))
        # embs shape: (num_steps, batch_size, embed_size)
        outputs, state = self.rnn(embs)
        # outputs shape: (num_steps, batch_size, num_hiddens)
        # state shape: (num_layers, batch_size, num_hiddens)
        return outputs, state
Let’s use a concrete example to illustrate the above encoder implementation. Below, we instantiate a two-layer GRU encoder whose number of hidden units is 16. Given a minibatch of sequence inputs X (batch size =4; number of time steps =9), the hidden states of the final layer at all the time steps (enc_outputs returned by the encoder’s recurrent layers) are a tensor of shape (number of time steps, batch size, number of hidden units).
英語のヒント
具体的な例を使って、上のエンコーダの実装を示そう。以下では、隠れユニットの数が16の2層のGRUエンコーダをインスタンス化する。系列の入力のミニバッチX(バッチサイズ=4、時間ステップの数=9)が与えられると、すべての時間ステップでの最後の層の隠れ状態(エンコーダの再帰的な層が返すenc_outputs)は、(時間ステップの数、バッチサイズ、隠れユニットの数)という形状のテンソルになる。
vocab_size, embed_size, num_hiddens, num_layers = 10, 8, 16, 2
batch_size, num_steps = 4, 9
encoder = Seq2SeqEncoder(vocab_size, embed_size, num_hiddens, num_layers)
X = torch.zeros((batch_size, num_steps))
enc_outputs, enc_state = encoder(X)
d2l.check_shape(enc_outputs, (num_steps, batch_size, num_hiddens))
Since we are using a GRU here, the shape of the multilayer hidden states at the final time step is (number of hidden layers, batch size, number of hidden units).
英語のヒント
ここではGRUを使っているので、最後の時間ステップでの多層の隠れ状態の形状は、(隠れ層の数、バッチサイズ、隠れユニットの数)である。
d2l.check_shape(enc_state, (num_layers, batch_size, num_hiddens))