プリンキピア

第9章リカレントニューラルネットワーク

9.5.1. RNN Model9.5.1 RNNモデル

We begin by defining a class to implement the RNN model (Section 9.4.2). Note that the number of hidden units num_hiddens is a tunable hyperparameter.
英語のヒント
まず、RNNのモデル(9.4.2節)を実装するクラスを定義する。隠れユニットの数num_hiddensは調整できるハイパーパラメータであることに注意してほしい。
class RNNScratch(d2l.Module):  #@save
    """The RNN model implemented from scratch."""
    def __init__(self, num_inputs, num_hiddens, sigma=0.01):
        super().__init__()
        self.save_hyperparameters()
        self.W_xh = nn.Parameter(
            torch.randn(num_inputs, num_hiddens) * sigma)
        self.W_hh = nn.Parameter(
            torch.randn(num_hiddens, num_hiddens) * sigma)
        self.b_h = nn.Parameter(torch.zeros(num_hiddens))
The forward method below defines how to compute the output and hidden state at any time step, given the current input and the state of the model at the previous time step. Note that the RNN model loops through the outermost dimension of inputs, updating the hidden state one time step at a time. The model here uses a tanh activation function (Section 5.1.2.3).
英語のヒント
以下のforwardメソッドは、現在の入力と前の時間ステップのモデルの状態が与えられたときに、任意の時間ステップの出力と隠れ状態をどう計算するかを定める。RNNのモデルはinputsの一番外側の次元をループでたどり、隠れ状態を一度に1時間ステップずつ更新することに注意してほしい。ここでのモデルは、tanh活性化関数(5.1.2.3節)を使う。
@d2l.add_to_class(RNNScratch)  #@save
def forward(self, inputs, state=None):
    if state is None:
        # Initial state with shape: (batch_size, num_hiddens)
        state = torch.zeros((inputs.shape[1], self.num_hiddens),
                          device=inputs.device)
    else:
        state, = state
    outputs = []
    for X in inputs:  # Shape of inputs: (num_steps, batch_size, num_inputs)
        state = torch.tanh(torch.matmul(X, self.W_xh) +
                         torch.matmul(state, self.W_hh) + self.b_h)
        outputs.append(state)
    return outputs, state
We can feed a minibatch of input sequences into an RNN model as follows.
英語のヒント
入力系列のミニバッチを、次のようにRNNのモデルに入れられる。
batch_size, num_inputs, num_hiddens, num_steps = 2, 16, 32, 100
rnn = RNNScratch(num_inputs, num_hiddens)
X = torch.ones((num_steps, batch_size, num_inputs))
outputs, state = rnn(X)
Let’s check whether the RNN model produces results of the correct shapes to ensure that the dimensionality of the hidden state remains unchanged.
英語のヒント
隠れ状態の次元が変わらないことを確かめるため、RNNのモデルが正しい形状の結果を出すかどうかを確認しよう。
def check_len(a, n):  #@save
    """Check the length of a list."""
    assert len(a) == n, f'list\'s length {len(a)} != expected length {n}'

def check_shape(a, shape):  #@save
    """Check the shape of a tensor."""
    assert a.shape == shape, \
            f'tensor\'s shape {a.shape} != expected shape {shape}'

check_len(outputs, num_steps)
check_shape(outputs[0], (batch_size, num_hiddens))
check_shape(state, (batch_size, num_hiddens))