# Neural Networks for Time Series
::: {.hero}
**Part VI. Deep Learning for Time Series and Sequence Data**
**Chapter goal:** build the first deep-learning forecasting model for time series by converting ordered observations into supervised learning examples. We study sliding windows, neural-network maps, loss functions, backpropagation, regularization, leakage-aware validation, and AI-assisted model critique.
:::
## Learning objectives
After studying this chapter, you should be able to:
1. convert a univariate or multivariate time series into input-label windows;
2. distinguish sequence-to-one, sequence-to-sequence, recursive, direct, and multi-output neural forecasts;
3. define a neural forecasting model as a nonlinear map $f_\theta$ from a history window to a future horizon;
4. formulate empirical risk minimization for time-series forecasting;
5. explain how backpropagation computes gradients through a computational graph;
6. train a window-based multilayer perceptron while avoiding time leakage;
7. compare a neural forecast with naive and linear baselines;
8. diagnose overfitting using training and validation loss curves;
9. explain why scaling, chronological splitting, and baselines are essential;
10. use AI tools to critique the modeling workflow while verifying the mathematics and code independently.
## 19.1 From classical forecasts to neural sequence maps
Classical models in earlier chapters describe the current observation using explicit stochastic structure. For example, an AR($p$) model has the form
$$
Y_t = \phi_1Y_{t-1}+\cdots+\phi_pY_{t-p}+W_t.
$$
The one-step conditional mean is linear in the past:
$$
\mathbb E[Y_t\mid Y_{t-1},\ldots,Y_{t-p}]
=
\phi_1Y_{t-1}+\cdots+\phi_pY_{t-p}.
$$
A neural time-series model keeps the forecasting viewpoint but replaces the explicit linear map by a learned nonlinear map. Given a history window
$$
\mathbf x_t=(Y_{t-L+1},Y_{t-L+2},\ldots,Y_t)\in\mathbb R^L,
$$
and a forecasting horizon $H$, the target vector is
$$
\mathbf y_t=(Y_{t+1},Y_{t+2},\ldots,Y_{t+H})\in\mathbb R^H.
$$
A neural forecasting model is a parameterized function
$$
f_\theta:\mathbb R^L\to\mathbb R^H,
\qquad
\widehat{\mathbf y}_t=f_\theta(\mathbf x_t).
$$
This framework generalizes the AR model. If $H=1$ and $f_\theta$ is linear, then the model is essentially an autoregression estimated by supervised learning. If $f_\theta$ is a multilayer neural network, it can learn nonlinear interactions among lags.
::: {.callout-note}
## Neural forecasting is still forecasting
Deep learning does not remove the need for time-series thinking. We still need baselines, chronological validation, horizon-specific error analysis, and diagnostics for failures.
:::
## 19.2 Time-series windows as supervised learning data
Suppose we observe a sequence
$$
Y_1,Y_2,\ldots,Y_T.
$$
Choose an input length $L$ and forecast horizon $H$. For each feasible forecast origin $t$, construct
$$
\mathbf x_t=(Y_{t-L+1},\ldots,Y_t)
$$
and
$$
\mathbf y_t=(Y_{t+1},\ldots,Y_{t+H}).
$$
The resulting supervised data set is
$$
\mathcal D
=
\{(\mathbf x_t,\mathbf y_t):L\le t\le T-H\}.
$$
Equivalently, the design matrix has rows
$$
X=
\begin{bmatrix}
Y_1 & Y_2 & \cdots & Y_L\\
Y_2 & Y_3 & \cdots & Y_{L+1}\\
\vdots & \vdots & \ddots & \vdots\\
Y_{T-L-H+1} & Y_{T-L-H+2} & \cdots & Y_{T-H}
\end{bmatrix},
$$
and the target matrix is
$$
Z=
\begin{bmatrix}
Y_{L+1} & Y_{L+2} & \cdots & Y_{L+H}\\
Y_{L+2} & Y_{L+3} & \cdots & Y_{L+H+1}\\
\vdots & \vdots & \ddots & \vdots\\
Y_{T-H+1} & Y_{T-H+2} & \cdots & Y_T
\end{bmatrix}.
$$
Each row is one supervised example. The row order is temporal and must be respected during validation.
### Sequence-to-one and sequence-to-sequence
A **sequence-to-one** model uses a history window to forecast one future value:
$$
f_\theta:\mathbb R^L\to\mathbb R,
\qquad
\widehat Y_{t+1}=f_\theta(Y_{t-L+1},\ldots,Y_t).
$$
A **sequence-to-sequence** or **multi-output** model forecasts several future values at once:
$$
f_\theta:\mathbb R^L\to\mathbb R^H,
\qquad
(\widehat Y_{t+1},\ldots,\widehat Y_{t+H})=f_\theta(\mathbf x_t).
$$
For multivariate time series $\mathbf Y_t\in\mathbb R^d$, the input window is a matrix
$$
\mathbf X_t=
\begin{bmatrix}
\mathbf Y_{t-L+1}^\top\\
\mathbf Y_{t-L+2}^\top\\
\vdots\\
\mathbf Y_t^\top
\end{bmatrix}
\in\mathbb R^{L\times d}.
$$
An MLP usually flattens this matrix into a vector in $\mathbb R^{Ld}$. Later chapters will preserve the temporal geometry using convolutional, recurrent, and attention-based architectures.
## 19.3 Direct, recursive, and multi-output neural forecasts
There are several ways to forecast multiple steps ahead.
### Recursive one-step strategy
Train a one-step model
$$
\widehat Y_{t+1}=f_\theta(Y_{t-L+1},\ldots,Y_t),
$$
then feed its own forecast back into the input window:
$$
\widehat Y_{t+2}=f_\theta(Y_{t-L+2},\ldots,Y_t,\widehat Y_{t+1}).
$$
This is simple, but errors can accumulate.
### Direct strategy
Train a separate model for each horizon:
$$
\widehat Y_{t+h}=f_{\theta_h}^{(h)}(Y_{t-L+1},\ldots,Y_t),
\qquad h=1,\ldots,H.
$$
This avoids recursive error propagation but requires fitting $H$ models.
### Multi-output strategy
Train one model that outputs all horizons simultaneously:
$$
(\widehat Y_{t+1},\ldots,\widehat Y_{t+H})
=
f_\theta(Y_{t-L+1},\ldots,Y_t).
$$
This is the strategy used in the main Python example below. It encourages the model to learn a coherent future path.
::: {.theorem-box}
## Neural networks as nonlinear autoregressions
A window-based neural forecast can be viewed as a nonlinear autoregressive model:
$$
Y_{t+1}=f_\theta(Y_t,Y_{t-1},\ldots,Y_{t-L+1})+\varepsilon_{t+1}.
$$
The model is not automatically better than ARIMA or SARIMA. Its advantage appears when nonlinear lag interactions, many covariates, or complex regime-dependent effects are important and enough data are available.
:::
## 19.4 Mathematical form of a multilayer perceptron
A feedforward neural network is a composition of affine maps and nonlinear activation functions. Let
$$
\mathbf h^{(0)}=\mathbf x.
$$
For layers $\ell=1,\ldots,m$, define
$$
\mathbf a^{(\ell)}=W^{(\ell)}\mathbf h^{(\ell-1)}+\mathbf b^{(\ell)},
$$
and
$$
\mathbf h^{(\ell)}=\sigma_\ell(\mathbf a^{(\ell)}).
$$
For a regression forecast, the final layer is often linear:
$$
f_\theta(\mathbf x)
=
W^{(m+1)}\mathbf h^{(m)}+\mathbf b^{(m+1)}.
$$
The full parameter vector is
$$
\theta=
\{W^{(1)},\mathbf b^{(1)},\ldots,W^{(m+1)},\mathbf b^{(m+1)}\}.
$$
Common activations include:
$$
\operatorname{ReLU}(z)=\max\{0,z\},
$$
$$
\tanh(z)=\frac{e^z-e^{-z}}{e^z+e^{-z}},
$$
and
$$
\sigma(z)=\frac{1}{1+e^{-z}}.
$$
The activation function is what makes the model nonlinear. Without nonlinear activations, a composition of affine transformations collapses to a single affine transformation.
## 19.5 Loss functions and empirical risk
Let $\mathcal I_{\text{train}}$ be the set of training forecast origins. For a multi-output forecast with horizon $H$, the mean squared error objective is
$$
J(\theta)
=
\frac{1}{|\mathcal I_{\text{train}}|H}
\sum_{t\in\mathcal I_{\text{train}}}
\sum_{h=1}^H
\left(Y_{t+h}-\widehat Y_{t+h|t}\right)^2,
$$
where
$$
(\widehat Y_{t+1|t},\ldots,\widehat Y_{t+H|t})=f_\theta(\mathbf x_t).
$$
Other losses may be better for different goals:
- mean absolute error for robustness;
- Huber loss for a compromise between MSE and MAE;
- quantile loss for probabilistic forecasting;
- cross-entropy for sequence classification;
- custom decision loss when underprediction and overprediction have different costs.
With $L_2$ regularization, the training problem becomes
$$
\widehat\theta
=
\arg\min_\theta
\left\{
J(\theta)+\lambda\|\theta\|_2^2
\right\}.
$$
In neural-network terminology, $\lambda\|\theta\|_2^2$ is often implemented as **weight decay**.
## 19.6 Backpropagation as the chain rule on a computational graph
Training requires gradients of the loss with respect to all parameters:
$$
\nabla_\theta J(\theta).
$$
For a one-hidden-layer network,
$$
\widehat y
=
\mathbf v^\top \sigma(W\mathbf x+\mathbf b)+c,
$$
and squared loss
$$
L(\theta)=\frac12(\widehat y-y)^2,
$$
we can write the computation as
$$
\mathbf a=W\mathbf x+\mathbf b,
\qquad
\mathbf h=\sigma(\mathbf a),
\qquad
\widehat y=\mathbf v^\top\mathbf h+c,
\qquad
L=\frac12(\widehat y-y)^2.
$$
The chain rule gives
$$
\frac{\partial L}{\partial \widehat y}=\widehat y-y,
$$
$$
\frac{\partial L}{\partial \mathbf v}
=(\widehat y-y)\mathbf h,
\qquad
\frac{\partial L}{\partial c}=\widehat y-y,
$$
and
$$
\frac{\partial L}{\partial W}
=
\left[(\widehat y-y)\mathbf v\odot \sigma'(\mathbf a)\right]\mathbf x^\top,
$$
$$
\frac{\partial L}{\partial \mathbf b}
=(\widehat y-y)\mathbf v\odot \sigma'(\mathbf a).
$$
Backpropagation is an efficient algorithmic procedure for applying these chain-rule calculations through a large computational graph. It is not finite-difference differentiation, and it is not symbolic simplification. It stores intermediate quantities from the forward pass and reuses them in the backward pass.
Gradient descent updates parameters by
$$
\theta_{k+1}=\theta_k-\alpha\nabla_\theta J(\theta_k),
$$
or, in practice, by a stochastic or mini-batch variant such as Adam or AdamW.
::: {.callout-note}
## Why this matters for time series
For a time-series neural network, the inputs are not independent in time. But once windows are constructed, the training objective is still an empirical risk over many overlapping examples. The validation design must remember where those windows came from.
:::
## 19.7 Interactive demonstration: input and label windows
The module below shows how a single observed series is transformed into supervised examples. The blue points form the input window and the orange points form the label window.
<div class="interactive-card">
<h3>Interactive Module: Sliding Window Builder</h3>
<p class="small-note">Change the input length, forecast horizon, and window start. The maximum start value is adjusted automatically so the input and label windows always fit inside the simulated series.</p>
<div class="controls">
<label for="ch19_input"><strong>Input length $L$:</strong> <span id="ch19_input_value">24</span></label>
<input id="ch19_input" type="range" min="6" max="36" step="1" value="24">
<label for="ch19_horizon"><strong>Forecast horizon $H$:</strong> <span id="ch19_horizon_value">12</span></label>
<input id="ch19_horizon" type="range" min="1" max="24" step="1" value="12">
<label for="ch19_start"><strong>Window start:</strong> <span id="ch19_start_value">10</span></label>
<input id="ch19_start" type="range" min="0" max="84" step="1" value="10">
</div>
<p id="ch19_window_summary" class="small-note"></p>
<div id="ch19_window_plot" style="height:430px;"></div>
</div>
## 19.8 Interactive demonstration: activation functions
Neural networks become nonlinear because of activation functions. The module below compares three common choices.
<div class="interactive-card">
<h3>Interactive Module: Activation Function Explorer</h3>
<p class="small-note">The activation is applied after an affine transformation. Without it, stacking layers would still produce only an affine map.</p>
<label for="ch19-activation-scale"><strong>Input scale:</strong> <span id="ch19-activation-scale-value">1.00</span></label>
<input id="ch19-activation-scale" type="range" min="0.25" max="3.00" step="0.05" value="1.00" style="width:100%;">
<label for="ch19-activation-bias"><strong>Bias shift:</strong> <span id="ch19-activation-bias-value">0.00</span></label>
<input id="ch19-activation-bias" type="range" min="-3.00" max="3.00" step="0.05" value="0.00" style="width:100%;">
<div id="ch19-activation-plot" style="height:430px;"></div>
</div>
<script>
(function () {
function initCh19ActivationExplorer() {
const plot = document.getElementById("ch19-activation-plot");
const scaleSlider = document.getElementById("ch19-activation-scale");
const biasSlider = document.getElementById("ch19-activation-bias");
const scaleValue = document.getElementById("ch19-activation-scale-value");
const biasValue = document.getElementById("ch19-activation-bias-value");
if (!plot || !scaleSlider || !biasSlider || !scaleValue || !biasValue) return;
const x = Array.from({length:241}, (_, i) => -6 + 12 * i / 240);
function relu(z) { return Math.max(0, z); }
function sigmoid(z) { return 1 / (1 + Math.exp(-z)); }
function update() {
const a = parseFloat(scaleSlider.value);
const b = parseFloat(biasSlider.value);
scaleValue.textContent = a.toFixed(2);
biasValue.textContent = b.toFixed(2);
const z = x.map(v => a * v + b);
const traces = [
{x:x, y:z.map(relu), mode:"lines", name:"ReLU"},
{x:x, y:z.map(Math.tanh), mode:"lines", name:"tanh"},
{x:x, y:z.map(sigmoid), mode:"lines", name:"sigmoid"}
];
const layout = {
title:"Activation Functions Applied to $a x + b$",
xaxis:{title:"input x"},
yaxis:{title:"activation output"},
margin:{t:70, r:30, b:50, l:60},
legend:{orientation:"h", y:-0.2}
};
Plotly.react(
plot,
traces,
layout,
window.TSInteractives ? window.TSInteractives.plotlyConfig : {responsive:true, displayModeBar:true}
);
}
scaleSlider.addEventListener("input", update);
biasSlider.addEventListener("input", update);
update();
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initCh19ActivationExplorer);
} else {
initCh19ActivationExplorer();
}
})();
</script>
## 19.9 Python example: simulate a nonlinear seasonal time series
The following synthetic series contains autoregressive dependence, nonlinear dependence, seasonality, and noise. It is simple enough to understand but nonlinear enough to motivate a neural model.
```{python}
#| label: ch19-simulate-nonlinear-series
#| fig-cap: "Synthetic nonlinear seasonal time series for neural forecasting."
#| warning: false
#| message: false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(7339)
n = 650
y = np.zeros(n)
for t in range(2, n):
seasonal = 0.45 * np.sin(2 * np.pi * t / 24)
nonlinear = 0.25 * np.tanh(1.5 * y[t - 1])
y[t] = (
0.62 * y[t - 1]
- 0.22 * y[t - 2]
+ seasonal
+ nonlinear
+ rng.normal(0, 0.28)
)
time = np.arange(n)
plt.figure(figsize=(9, 4))
plt.plot(time, y)
plt.xlabel("time")
plt.ylabel("value")
plt.title("Synthetic nonlinear seasonal time series")
plt.show()
```
## 19.10 Python example: construct input and label windows
The function below transforms a single series into a supervised learning data set. This is the most important preprocessing step for neural forecasting.
```{python}
#| label: ch19-window-function
#| warning: false
#| message: false
def make_windows(series, input_length, horizon):
"""Return input windows X, target windows Y, and forecast origins.
X[i] contains observations used as input.
Y[i] contains the next horizon observations used as labels.
origins[i] is the last time index included in X[i].
"""
series = np.asarray(series, dtype=float)
X, Y, origins = [], [], []
last_start = len(series) - input_length - horizon + 1
for start in range(last_start):
end = start + input_length
X.append(series[start:end])
Y.append(series[end:end + horizon])
origins.append(end - 1)
return np.asarray(X), np.asarray(Y), np.asarray(origins)
L = 36
H = 12
X, Y, origins = make_windows(y, input_length=L, horizon=H)
print("X shape:", X.shape)
print("Y shape:", Y.shape)
print("First forecast origin:", origins[0])
```
```{python}
#| label: ch19-window-visualization
#| fig-cap: "One input window and its corresponding label window."
#| warning: false
#| message: false
example = 120
input_index = np.arange(example, example + L)
label_index = np.arange(example + L, example + L + H)
plt.figure(figsize=(9, 4))
plt.plot(time, y, linewidth=1, label="full series")
plt.scatter(input_index, y[input_index], label="input window", zorder=3)
plt.scatter(label_index, y[label_index], marker="x", s=70, label="label window", zorder=3)
plt.xlabel("time")
plt.ylabel("value")
plt.title("A supervised example produced from a time series")
plt.legend()
plt.show()
```
## 19.11 Chronological splitting and scaling
A random split is usually invalid for forecasting because it lets future patterns leak into the training set. We split the windowed examples chronologically:
$$
\text{train} \; \longrightarrow \; \text{validation} \; \longrightarrow \; \text{test}.
$$
Scaling must also be fit on the training period only. If the test period is used to compute the mean or standard deviation, the model has already seen information from the future.
```{python}
#| label: ch19-split-scale
#| warning: false
#| message: false
from sklearn.preprocessing import StandardScaler
train_end = int(0.70 * len(X))
val_end = int(0.85 * len(X))
X_train, Y_train = X[:train_end], Y[:train_end]
X_val, Y_val = X[train_end:val_end], Y[train_end:val_end]
X_test, Y_test = X[val_end:], Y[val_end:]
x_scaler = StandardScaler().fit(X_train)
y_scaler = StandardScaler().fit(Y_train)
Xs_train = x_scaler.transform(X_train)
Xs_val = x_scaler.transform(X_val)
Xs_test = x_scaler.transform(X_test)
Ys_train = y_scaler.transform(Y_train)
Ys_val = y_scaler.transform(Y_val)
Ys_test = y_scaler.transform(Y_test)
print("Number of training windows:", len(X_train))
print("Number of validation windows:", len(X_val))
print("Number of test windows:", len(X_test))
```
::: {.callout-warning}
## Scaling leakage
Do not call `fit_transform` on the full data set before splitting. For forecasting, preprocessing parameters should be learned from the training period and then applied to validation and test periods.
:::
## 19.12 Python example: baseline and linear window models
Before training a neural network, always build baselines. A useful naive multi-step forecast repeats the most recent observed value:
$$
\widehat Y_{t+h|t}=Y_t,
\qquad h=1,\ldots,H.
$$
We also fit a ridge regression model on the same input windows. This is a linear benchmark for the neural network.
```{python}
#| label: ch19-baselines
#| warning: false
#| message: false
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error, mean_squared_error
naive_pred = np.repeat(X_test[:, -1:], H, axis=1)
ridge = Ridge(alpha=3.0)
ridge.fit(Xs_train, Ys_train)
ridge_pred_scaled = ridge.predict(Xs_test)
ridge_pred = y_scaler.inverse_transform(ridge_pred_scaled)
def forecast_metrics(name, truth, pred):
truth_flat = truth.ravel()
pred_flat = pred.ravel()
rmse = np.sqrt(mean_squared_error(truth_flat, pred_flat))
mae = mean_absolute_error(truth_flat, pred_flat)
return {"model": name, "RMSE": rmse, "MAE": mae}
baseline_results = [
forecast_metrics("naive repeat-last", Y_test, naive_pred),
forecast_metrics("ridge window model", Y_test, ridge_pred),
]
pd.DataFrame(baseline_results)
```
## 19.13 Python example: train a window-based MLP in PyTorch
The MLP below maps an input window of length $L=36$ to a forecast path of length $H=12$:
$$
f_\theta:\mathbb R^{36}\to\mathbb R^{12}.
$$
The architecture is intentionally small. In a course project, model size should be chosen by validation performance, not by excitement about deep learning.
```{python}
#| label: ch19-pytorch-mlp-training
#| fig-cap: "Training and validation loss curves for the window-based MLP."
#| warning: false
#| message: false
import torch
from torch import nn
torch.manual_seed(7339)
torch.set_num_threads(1)
Xtr = torch.tensor(Xs_train, dtype=torch.float32)
Ytr = torch.tensor(Ys_train, dtype=torch.float32)
Xva = torch.tensor(Xs_val, dtype=torch.float32)
Yva = torch.tensor(Ys_val, dtype=torch.float32)
class WindowMLP(nn.Module):
def __init__(self, input_length, horizon):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_length, 64),
nn.ReLU(),
nn.Dropout(0.10),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, horizon),
)
def forward(self, x):
return self.net(x)
model = WindowMLP(input_length=L, horizon=H)
loss_fn = nn.MSELoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-3)
train_losses = []
val_losses = []
best_state = None
best_val = float("inf")
patience = 30
wait = 0
for epoch in range(300):
model.train()
optimizer.zero_grad()
pred = model(Xtr)
loss = loss_fn(pred, Ytr)
loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(Xva), Yva).item()
train_losses.append(loss.item())
val_losses.append(val_loss)
if val_loss < best_val - 1e-5:
best_val = val_loss
best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
wait = 0
else:
wait += 1
if wait >= patience:
break
if best_state is not None:
model.load_state_dict(best_state)
plt.figure(figsize=(8, 4))
plt.plot(train_losses, label="training loss")
plt.plot(val_losses, label="validation loss")
plt.xlabel("epoch")
plt.ylabel("scaled MSE")
plt.title("MLP training history")
plt.legend()
plt.show()
```
## 19.14 Python example: evaluate the neural forecast
We now evaluate on the held-out test period. The test set was not used to fit preprocessing parameters, train the model, or choose the best epoch.
```{python}
#| label: ch19-mlp-test-evaluation
#| warning: false
#| message: false
model.eval()
with torch.no_grad():
mlp_pred_scaled = model(torch.tensor(Xs_test, dtype=torch.float32)).numpy()
mlp_pred = y_scaler.inverse_transform(mlp_pred_scaled)
all_results = baseline_results + [
forecast_metrics("MLP window model", Y_test, mlp_pred)
]
pd.DataFrame(all_results).sort_values("RMSE")
```
A neural model does not have to win every comparison. A strong linear baseline may be difficult to beat when the data-generating mechanism is mostly linear, the sample size is small, or the neural architecture is not tuned. The correct conclusion is not always "use a larger neural network." The correct conclusion is to inspect the error by horizon, validation design, and residual structure.
```{python}
#| label: ch19-horizon-errors
#| fig-cap: "Forecast error by horizon for baseline, linear, and neural models."
#| warning: false
#| message: false
def rmse_by_horizon(truth, pred):
return np.sqrt(np.mean((truth - pred) ** 2, axis=0))
horizons = np.arange(1, H + 1)
plt.figure(figsize=(8, 4))
plt.plot(horizons, rmse_by_horizon(Y_test, naive_pred), marker="o", label="naive")
plt.plot(horizons, rmse_by_horizon(Y_test, ridge_pred), marker="o", label="ridge")
plt.plot(horizons, rmse_by_horizon(Y_test, mlp_pred), marker="o", label="MLP")
plt.xlabel("forecast horizon")
plt.ylabel("RMSE")
plt.title("Horizon-wise forecast error")
plt.legend()
plt.show()
```
```{python}
#| label: ch19-forecast-path-example
#| fig-cap: "One test-window forecast path from the MLP and benchmark models."
#| warning: false
#| message: false
case = 20
origin = origins[val_end + case]
future_index = np.arange(origin + 1, origin + H + 1)
history_index = np.arange(origin - L + 1, origin + 1)
plt.figure(figsize=(9, 4))
plt.plot(history_index, y[history_index], label="history")
plt.plot(future_index, Y_test[case], marker="o", label="future observed")
plt.plot(future_index, naive_pred[case], marker="o", label="naive")
plt.plot(future_index, ridge_pred[case], marker="o", label="ridge")
plt.plot(future_index, mlp_pred[case], marker="o", label="MLP")
plt.axvline(origin, linestyle="--", linewidth=1)
plt.xlabel("time")
plt.ylabel("value")
plt.title("One multi-step forecast from a held-out test window")
plt.legend()
plt.show()
```
## 19.15 Mini-batches and stochastic optimization
The code above used the full training set each epoch. Large neural forecasting problems use mini-batches. If the training windows are
$$
\{(\mathbf x_i,\mathbf y_i):i=1,\ldots,N\},
$$
then a mini-batch $B\subset\{1,\ldots,N\}$ gives the stochastic gradient approximation
$$
\nabla_\theta J_B(\theta)
=
\frac{1}{|B|H}\sum_{i\in B}\sum_{h=1}^H
\nabla_\theta
\left(y_{i,h}-f_\theta(\mathbf x_i)_h\right)^2.
$$
The mini-batch examples can often be shuffled **within the training period** because the model is trained on windows, not by updating a hidden state through the original sequence. However, the train-validation-test split itself should remain chronological.
```{python}
#| label: ch19-dataloader-sketch
#| warning: false
#| message: false
from torch.utils.data import TensorDataset, DataLoader
train_loader = DataLoader(
TensorDataset(Xtr, Ytr),
batch_size=64,
shuffle=True,
)
batch_X, batch_Y = next(iter(train_loader))
print("mini-batch X shape:", tuple(batch_X.shape))
print("mini-batch Y shape:", tuple(batch_Y.shape))
```
## 19.16 Regularization and early stopping
Neural time-series models can overfit badly because overlapping windows create many similar training examples. Common regularization tools include:
- small architectures;
- weight decay;
- dropout;
- early stopping based on validation loss;
- noise injection or data augmentation when justified;
- limiting the input window length;
- comparing against simple baselines.
Early stopping uses validation loss to choose a training epoch:
$$
\widehat k
=
\arg\min_k J_{\text{val}}(\theta_k).
$$
The test set should be used only once at the end.
::: {.callout-warning}
## Many windows do not mean many independent examples
If $L=36$ and two adjacent training examples differ by only one time step, the examples are highly overlapping. Neural networks may appear to have a large training set, but the effective amount of independent information may be much smaller.
:::
## 19.17 Neural forecasting workflow
A responsible neural forecasting workflow is:
1. plot the data and build naive baselines;
2. define the forecast horizon and decision metric;
3. construct windows without using future information;
4. split chronologically into training, validation, and test periods;
5. fit scaling transformations on training data only;
6. train a small model first;
7. monitor training and validation losses;
8. compare against naive and linear baselines;
9. inspect horizon-wise errors;
10. write a diagnostic report describing where the model succeeds and fails.
The model is only one part of the forecasting system. The validation design often matters more than the architecture.
## 19.18 AI-assisted modeling activity
::: {.callout-ai}
## AI-assisted study box
Ask an AI assistant:
> I am training a neural network to forecast a time series using sliding windows. Give me a checklist of possible time leakage sources. For each item, explain how I can test for it in code.
Then verify the answer manually. In particular, check whether the assistant remembers that scaling, feature construction, rolling statistics, hyperparameter selection, and validation splits can all introduce leakage.
:::
::: {.callout-ai}
## AI-assisted debugging prompt
Use the following prompt when your neural model performs too well:
> My neural forecasting model has surprisingly low test error. Here is my splitting code, scaling code, and feature construction code. Identify any place where future information may enter the training process. Do not suggest a new architecture until leakage has been ruled out.
A suspiciously good forecast is often more dangerous than a bad forecast.
:::
::: {.callout-ai}
## AI-assisted mathematical explanation
Ask an AI assistant to explain why a linear neural network with no nonlinear activations is equivalent to one linear layer. Then write the proof yourself by composing two affine maps:
$$
W_2(W_1\mathbf x+\mathbf b_1)+\mathbf b_2
=
(W_2W_1)\mathbf x+(W_2\mathbf b_1+\mathbf b_2).
$$
:::
## 19.19 Common mistakes
1. **Using random train-test splits.** Random splits leak future regimes into the training set.
2. **Scaling before splitting.** The future test mean and variance should not be used during training.
3. **Skipping baselines.** A neural network that cannot beat a naive seasonal forecast is not useful.
4. **Confusing many windows with much information.** Overlapping windows are strongly dependent.
5. **Using too large a network.** Large networks can memorize local patterns in small time-series data sets.
6. **Evaluating only one-step forecasts.** Many applications require horizon-wise multi-step evaluation.
7. **Ignoring prediction uncertainty.** A point forecast alone may not support decision-making.
8. **Assuming deep learning removes feature thinking.** Calendar effects, known future covariates, and transformations often matter.
## 19.20 Exercises
1. Let $f_\theta:\mathbb R^L\to\mathbb R$ be a one-step neural forecast. Write the empirical MSE objective for forecast origins $t=L,\ldots,T-1$.
2. Show that if every activation function is the identity, then a multilayer feedforward network represents an affine function.
3. For $L=24$, $H=6$, and $T=500$, how many supervised windows can be constructed from a univariate series?
4. Explain why a random split of sliding windows may produce leakage even if no test target appears explicitly in the training set.
5. Modify the Python example so that $H=1$. Compare the MLP with an AR-style ridge model.
6. Modify the Python example so that $L=12,24,48$. Which input length gives the best validation loss?
7. Replace MSE loss with MAE or Huber loss. How do the forecasts change?
8. Add a known seasonal feature, such as $\sin(2\pi t/24)$ and $\cos(2\pi t/24)$, to the input. Compare performance.
9. Use recursive one-step forecasting instead of multi-output forecasting. Compare horizon-wise error curves.
10. Write a diagnostic report for the MLP model using a time plot, loss curve, horizon-wise RMSE, and one forecast-path example.
## 19.21 Mini project
Choose one real time series and build a neural forecasting pipeline.
Your report should include:
1. a clear forecasting question and horizon;
2. an exploratory plot and at least one seasonality or dependence diagnostic;
3. naive and linear baselines;
4. a window-based neural network;
5. chronological train-validation-test splitting;
6. scaling fit on the training period only;
7. horizon-wise error analysis;
8. a discussion of whether the neural network is justified;
9. an AI-assisted critique section where you ask an AI assistant to find weaknesses in your workflow and then verify or reject its suggestions.
## 19.22 Checklist
Before moving to CNNs, RNNs, LSTMs, and transformers, make sure you can answer the following questions.
- What are $L$ and $H$ in a windowed forecasting problem?
- What is the difference between sequence-to-one and sequence-to-sequence forecasting?
- Why should time-series validation be chronological?
- Why should scaling be fit on the training period only?
- What baseline did your neural model beat?
- Does your model's error increase with horizon?
- Does the validation loss suggest overfitting?
- Can you explain the model as a nonlinear autoregression?
- Can you describe the loss function mathematically?
- Can you identify at least three possible leakage sources?