%matplotlib inline
from d2l import tensorflow as d2l
import tensorflow as tfText, audio, time series, and video can all be represented as ordered data. When earlier entries change the distribution of later ones, conditioning on the past improves prediction.
A fixed window discards observations beyond lag \tau; a recurrent state keeps fixed memory while updating a learned function of the entire prefix.
Fixed window = the n-gram (and, later, an attention context window). Latent state = the RNN and the state space models of the next chapters.
A noisy sine wave, 1000 time steps:
Each example predicts x_t from the last \tau values, \mathbf{x}_t = (x_{t-\tau}, \ldots, x_{t-1}). Fit a linear model on the first 600 windows:
def get_dataloader(self, train):
features = [self.x[i : self.T-self.tau+i] for i in range(self.tau)]
self.features = d2l.stack(features, 1)
self.labels = d2l.reshape(self.x[self.tau:], (-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)Predict \hat{x}_t from the true previous \tau values. Tracks the series closely:
Forecasting many steps ahead means feeding predicted values back as inputs, so errors compound:
def k_step_pred(k):
features = []
for i in range(data.tau):
features.append(data.x[i : i+data.T-data.tau-k+1])
# The (i+tau)-th element stores the (i+1)-step-ahead predictions
for i in range(k):
preds = model(d2l.stack(features[i : i+data.tau], 1))
features.append(d2l.reshape(preds, -1))
return features[data.tau:]1- and 4-step curves track the truth; longer horizons are increasingly damped, and a full rollout collapses to a near-constant. Long-horizon forecasting is hard.