第10章現代のリカレントニューラルネットワーク
10.1.2. Implementation from Scratch10.1.2 ゼロからの実装
Now let’s implement an LSTM from scratch. As same as the experiments in Section 9.5, we first load The Time Machine dataset.
英語のヒント
では、LSTMをゼロから実装しよう。9.5節の実験と同じように、まず『タイム・マシン』のデータセットを読み込む。
10.1.2.1. Initializing Model Parameters10.1.2.1 モデルパラメータを初期化する
Next, we need to define and initialize the model parameters. As previously, the hyperparameter
num_hiddens dictates the number of hidden units. We initialize weights following a Gaussian distribution with 0.01 standard deviation, and we set the biases to 0.英語のヒント
次に、モデルパラメータを定義して初期化する必要がある。前と同じように、ハイパーパラメータ
num_hiddensは隠れユニットの数を決める。重みは標準偏差0.01のガウス分布に従って初期化し、バイアスは0に設定する。class LSTMScratch(d2l.Module):
def __init__(self, num_inputs, num_hiddens, sigma=0.01):
super().__init__()
self.save_hyperparameters()
init_weight = lambda *shape: nn.Parameter(torch.randn(*shape) * sigma)
triple = lambda: (init_weight(num_inputs, num_hiddens),
init_weight(num_hiddens, num_hiddens),
nn.Parameter(torch.zeros(num_hiddens)))
self.W_xi, self.W_hi, self.b_i = triple() # Input gate
self.W_xf, self.W_hf, self.b_f = triple() # Forget gate
self.W_xo, self.W_ho, self.b_o = triple() # Output gate
self.W_xc, self.W_hc, self.b_c = triple() # Input nodeThe actual model is defined as described above, consisting of three gates and an input node. Note that only the hidden state is passed to the output layer.
英語のヒント
実際のモデルは上で説明したとおりに定義され、三つのゲートと一つの入力ノードからなる。出力層に渡されるのは隠れ状態だけであることに注意してほしい。
@d2l.add_to_class(LSTMScratch)
def forward(self, inputs, H_C=None):
if H_C is None:
# Initial state with shape: (batch_size, num_hiddens)
H = torch.zeros((inputs.shape[1], self.num_hiddens),
device=inputs.device)
C = torch.zeros((inputs.shape[1], self.num_hiddens),
device=inputs.device)
else:
H, C = H_C
outputs = []
for X in inputs:
I = torch.sigmoid(torch.matmul(X, self.W_xi) +
torch.matmul(H, self.W_hi) + self.b_i)
F = torch.sigmoid(torch.matmul(X, self.W_xf) +
torch.matmul(H, self.W_hf) + self.b_f)
O = torch.sigmoid(torch.matmul(X, self.W_xo) +
torch.matmul(H, self.W_ho) + self.b_o)
C_tilde = torch.tanh(torch.matmul(X, self.W_xc) +
torch.matmul(H, self.W_hc) + self.b_c)
C = F * C + I * C_tilde
H = O * torch.tanh(C)
outputs.append(H)
return outputs, (H, C)10.1.2.2. Training and Prediction10.1.2.2 訓練と予測
Let’s train an LSTM model by instantiating the
RNNLMScratch class from Section 9.5.英語のヒント
9.5節の
RNNLMScratchクラスをインスタンス化して、LSTMモデルを訓練しよう。data = d2l.TimeMachine(batch_size=1024, num_steps=32)
lstm = LSTMScratch(num_inputs=len(data.vocab), num_hiddens=32)
model = d2l.RNNLMScratch(lstm, vocab_size=len(data.vocab), lr=4)
trainer = d2l.Trainer(max_epochs=50, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)