第10章現代のリカレントニューラルネットワーク
10.2.4. Implementation from Scratch10.2.4 ゼロからの実装
To gain a better understanding of the GRU model, let’s implement it from scratch.
英語のヒント
GRUのモデルをよりよく理解するため、ゼロから実装してみよう。
10.2.4.1. Initializing Model Parameters10.2.4.1 モデルパラメータを初期化する
The first step is to initialize the model parameters. We draw the weights from a Gaussian distribution with standard deviation to be
sigma and set the bias to 0. The hyperparameter num_hiddens defines the number of hidden units. We instantiate all weights and biases relating to the update gate, the reset gate, and the candidate hidden state.英語のヒント
最初の手順は、モデルパラメータを初期化することである。重みは標準偏差が
sigmaのガウス分布から引き、バイアスは0に設定する。ハイパーパラメータnum_hiddensは隠れユニットの数を定める。更新ゲート、リセットゲート、候補の隠れ状態に関わるすべての重みとバイアスをインスタンス化する。class GRUScratch(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_xz, self.W_hz, self.b_z = triple() # Update gate
self.W_xr, self.W_hr, self.b_r = triple() # Reset gate
self.W_xh, self.W_hh, self.b_h = triple() # Candidate hidden state10.2.4.2. Defining the Model10.2.4.2 モデルを定義する
Now we are ready to define the GRU forward computation. Its structure is the same as that of the basic RNN cell, except that the update equations are more complex.
英語のヒント
これで、GRUの順方向の計算を定義する準備が整った。その構造は、更新式がもっと複雑な点を除けば、基本的なRNNのセルのものと同じである。
@d2l.add_to_class(GRUScratch)
def forward(self, inputs, H=None):
if H is None:
# Initial state with shape: (batch_size, num_hiddens)
H = torch.zeros((inputs.shape[1], self.num_hiddens),
device=inputs.device)
outputs = []
for X in inputs:
Z = torch.sigmoid(torch.matmul(X, self.W_xz) +
torch.matmul(H, self.W_hz) + self.b_z)
R = torch.sigmoid(torch.matmul(X, self.W_xr) +
torch.matmul(H, self.W_hr) + self.b_r)
H_tilde = torch.tanh(torch.matmul(X, self.W_xh) +
torch.matmul(R * H, self.W_hh) + self.b_h)
H = Z * H + (1 - Z) * H_tilde
outputs.append(H)
return outputs, H10.2.4.3. Training10.2.4.3 訓練
Training a language model on The Time Machine dataset works in exactly the same manner as in Section 9.5.
英語のヒント
『タイム・マシン』のデータセットで言語モデルを訓練するのは、9.5節とまったく同じやり方で行う。
data = d2l.TimeMachine(batch_size=1024, num_steps=32)
gru = GRUScratch(num_inputs=len(data.vocab), num_hiddens=32)
model = d2l.RNNLMScratch(gru, vocab_size=len(data.vocab), lr=4)
trainer = d2l.Trainer(max_epochs=50, gradient_clip_val=1, num_gpus=1)
trainer.fit(model, data)