プリンキピア

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

9.1.3. Training9.1.3 訓練

Before we focus our attention on text data, let’s first try this out with some continuous-valued synthetic data.
英語のヒント
テキストデータに注意を向ける前に、まず連続値の合成データでこれを試してみよう。
Here, our 1000 synthetic data will follow the trigonometric sin function, applied to 0.01 times the time step. To make the problem a little more interesting, we corrupt each sample with additive noise. From this sequence we extract training examples, each consisting of features and a label.
英語のヒント
ここでは、1000個の合成データは、時間ステップの0.01倍に当てはめた三角関数のsin関数に従う。問題を少しおもしろくするため、各標本を加法的なノイズで汚す。この系列から、特徴量とラベルからなる訓練事例を抽出する。
class Data(d2l.DataModule):
    def __init__(self, batch_size=16, T=1000, num_train=600, tau=4):
        self.save_hyperparameters()
        self.time = torch.arange(1, T + 1, dtype=torch.float32)
        self.x = torch.sin(0.01 * self.time) + torch.randn(T) * 0.2

data = Data()
d2l.plot(data.time, data.x, 'time', 'x', xlim=[1, 1000], figsize=(6, 3))
To begin, we try a model that acts as if the data satisfied a τth-order Markov condition, and thus predicts xt using only the past τ observations. Thus for each time step we have an example with label y=xt and features 𝐱t=[xt−τ,…,xt−1]. The astute reader might have noticed that this results in 1000−τ examples, since we lack sufficient history for y1,…,yτ. While we could pad the first τ sequences with zeros, to keep things simple, we drop them for now. The resulting dataset contains T−τ examples, where each input to the model has sequence length τ. We create a data iterator on the first 600 examples, covering a period of the sin function.
英語のヒント
まず、データがτth次のマルコフ条件を満たすかのようにふるまい、したがって過去のτ個の観測だけを使ってxtを予測するモデルを試す。そのため、各時間ステップについて、ラベルy=xtと特徴量𝐱t=[xt−τ,…,xt−1]をもつ事例がある。注意深い読者なら、y1,…,yτには十分な履歴がないので、これで1000−τ個の事例になることに気づいたかもしれない。最初のτ個の系列を0で埋めることもできるが、簡単にするため、今はそれらを捨てる。得られるデータセットにはT−τ個の事例が含まれ、モデルへの各入力の系列の長さはτである。最初の600個の事例で、sin関数の一周期をカバーするデータイテレータを作る。
@d2l.add_to_class(Data)
def get_dataloader(self, train):
    features = [self.x[i : self.T-self.tau+i] for i in range(self.tau)]
    self.features = torch.stack(features, 1)
    self.labels = self.x[self.tau:].reshape((-1, 1))
    i = slice(0, self.num_train) if train else slice(self.num_train, None)
    return self.get_tensorloader([self.features, self.labels], train, i)
In this example our model will be a standard linear regression.
英語のヒント
この例では、モデルは標準的な線形回帰である。
model = d2l.LinearRegression(lr=0.01)
trainer = d2l.Trainer(max_epochs=5)
trainer.fit(model, data)