Build and Validate a Multi-Step Sequence Forecaster in PyTorch
Machine LearningModel answerLast updated
Design an end-to-end forecasting pipeline for a noisy time series: frame the target, avoid leakage, choose a model, write a PyTorch training loop, and evaluate it with time-aware validation.
You are handed a historical time-series dataset (for example, minute-level data with several input features) and asked to produce a model that predicts its future values.
Describe and implement a complete solution:
- Problem framing. Which clarifying questions would you ask, and what working assumptions would you state? Consider the target (level versus change), the forecast horizon, how the forecast will be used, data volume, and latency or retraining constraints.
- Data preparation. Explain how you build input windows, construct the target, scale features, and split the data so that no future information reaches the model.
- Model choice. Pick an architecture, justify it against simpler alternatives, and say which baselines it must beat.
- Training code. Write a PyTorch training loop covering the dataset, model, loss, optimizer, regularization, and model selection.
- Evaluation. Describe how you would validate the model offline, which metrics you would report, and how you would monitor it after deployment.
Be explicit about your assumptions, the trade-offs behind your choices, and the failure modes you would watch for.
Hints
Hint 1
Before choosing a model, decide what exactly is being predicted: a raw level or a stationary quantity such as a return or difference, and one step ahead or several. This choice drives the loss, the metric and the baseline.
Hint 2
Most forecasting bugs are leakage bugs. Split chronologically, fit scalers on training data only, make sure features at time t use only information available at t, and leave a gap of at least lookback plus horizon between splits.
Hint 3
Start with naive and linear baselines before any neural network. If you do use a sequence model, a direct multi-horizon output head avoids compounding errors, and early stopping plus weight decay guard against overfitting noisy data.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Frame the problem
Ask first, then state assumptions:
- Target and horizon. Next value or a multi-step horizon H (say 1, 5, 30 steps)? Predict a level, or a return/difference? Forecasting raw levels often looks good on RMSE simply because the series is persistent, while adding nothing useful.
- Scale and structure. One series or many related ones? Are exogenous features available? Roughly 500k rows (1-minute bars over several years) is enough for small neural nets but not for huge ones.
- Use. A point forecast, quantiles, or a signal feeding a decision? This sets the loss and the headline metric.
- Operations. Online inference with tight latency, or batch? How often do we retrain?
Working assumptions: multivariate inputs, univariate target, predict the change over the next H steps, Huber or MSE loss, and a correlation-type metric alongside error.
2. Data pipeline and leakage control
- Stationary target. Use returns or differences rather than raw levels.
- Causal alignment. Features at time t use only information available at t. Check timestamp semantics (bar open versus close, delayed publication). The target for a window ending at t is y[t+1 : t+H].
- Scaling. Fit normalization statistics on the training segment only, or use rolling past-only statistics.
- Chronological splits with an embargo. Train, validation and test occur in time order, separated by a gap of at least lookback + horizon so overlapping windows cannot leak labels.
- Features. Lags, rolling means and volatilities, calendar features, and cross-sectional features if there are many series.
3. Model ladder
- Naive baselines: last value, seasonal naive, or zero change. Anything we build must beat these out of sample.
- Ridge/linear on lags: fast, interpretable, surprisingly strong on noisy data.
- Gradient-boosted trees on engineered features: often the best tabular choice.
- Neural sequence models (LSTM/GRU, temporal CNN, small Transformer): justified when there is lots of data, many related series, or raw-sequence structure the hand-built features miss.
For the neural option I use an LSTM encoder with a direct multi-horizon head: it emits all H outputs at once, avoiding the error accumulation of feeding predictions back recursively. The cost is that the horizons are predicted independently of each other, which is usually acceptable.
4. Implementation
import copy
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
class WindowDataset(Dataset):
"""Sample i: X[i:i+L] -> y[i+L : i+L+H]."""
def __init__(self, X, y, lookback, horizon):
self.X = torch.as_tensor(X, dtype=torch.float32)
self.y = torch.as_tensor(y, dtype=torch.float32)
self.L, self.H = lookback, horizon
def __len__(self):
return max(len(self.X) - self.L - self.H + 1, 0)
def __getitem__(self, i):
return self.X[i:i + self.L], self.y[i + self.L:i + self.L + self.H]
class LSTMForecaster(nn.Module):
def __init__(self, n_features, horizon, hidden=64, layers=2, dropout=0.1):
super().__init__()
self.lstm = nn.LSTM(n_features, hidden, layers, batch_first=True,
dropout=dropout if layers > 1 else 0.0)
self.head = nn.Sequential(nn.LayerNorm(hidden), nn.Linear(hidden, horizon))
def forward(self, x): # (B, L, F)
out, _ = self.lstm(x)
return self.head(out[:, -1]) # (B, H)
def chrono_split(X, y, train_frac=0.7, val_frac=0.15, gap=0):
n = len(X)
a, b = int(n * train_frac), int(n * (train_frac + val_frac))
mu, sd = X[:a].mean(0), X[:a].std(0) + 1e-8 # train-only scaler
Xs = (X - mu) / sd
return ((Xs[:a], y[:a]),
(Xs[a + gap:b], y[a + gap:b]),
(Xs[b + gap:], y[b + gap:]))
def evaluate(model, loader, loss_fn, device):
model.eval()
total, n = 0.0, 0
with torch.no_grad():
for xb, yb in loader:
xb, yb = xb.to(device), yb.to(device)
total += loss_fn(model(xb), yb).item() * len(xb)
n += len(xb)
return total / max(n, 1)
def train(X, y, lookback=64, horizon=5, epochs=50, batch_size=256,
lr=1e-3, patience=5, device="cpu"):
gap = lookback + horizon
(Xtr, ytr), (Xva, yva), (Xte, yte) = chrono_split(X, y, gap=gap)
tr = DataLoader(WindowDataset(Xtr, ytr, lookback, horizon), batch_size, shuffle=True)
va = DataLoader(WindowDataset(Xva, yva, lookback, horizon), batch_size)
te = DataLoader(WindowDataset(Xte, yte, lookback, horizon), batch_size)
model = LSTMForecaster(X.shape[1], horizon).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4)
loss_fn = nn.HuberLoss()
best, best_state, bad = float("inf"), None, 0
for _ in range(epochs):
model.train()
for xb, yb in tr:
xb, yb = xb.to(device), yb.to(device)
opt.zero_grad()
loss_fn(model(xb), yb).backward()
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
val = evaluate(model, va, loss_fn, device)
if val < best:
best, best_state, bad = val, copy.deepcopy(model.state_dict()), 0
else:
bad += 1
if bad >= patience:
break
model.load_state_dict(best_state)
return model, evaluate(model, te, loss_fn, device)
Design notes worth stating:
- Shuffling windows in training is fine. Each window is self-contained; what must stay chronological is the split between sets.
- Huber loss is robust to fat-tailed targets.
- Gradient clipping stabilizes recurrent training.
- Early stopping and weight decay matter because overfitting is the default on low-signal data.
- The test set is used once, at the end.
Complexity: each epoch costs O(N · L · hidden²) for the LSTM; memory is dominated by the batch of windows, not the whole dataset, since windows are sliced lazily.
5. Evaluation
- Walk-forward validation. Use expanding or rolling training windows, each followed by an embargo gap and a test fold. This mimics deployment and reveals whether performance is stable across regimes; a single split can be lucky.
- Metrics matched to use. Report MAE/RMSE per horizon, plus rank or Pearson correlation between prediction and realized target if the output feeds decisions. For quantile forecasts, use pinball loss and calibration/coverage. Always report each metric relative to the naive baseline.
- Error analysis. Slice by volatility regime, time of day, and horizon. Check that the gain is not concentrated in a few outlier periods.
- Ablations. Compare against ridge and gradient boosting; if the LSTM does not clearly win, ship the simpler model.
6. Deployment and monitoring
- Compute features with the same code online and offline to prevent train/serve skew.
- Track live error and correlation against the walk-forward expectation, feature distribution drift, and data freshness.
- Retrain on a schedule or when drift alarms fire, and keep the previous model as a fallback.
Common mistakes
- Random train/test splits, or no embargo between overlapping windows.
- Fitting scalers on the full dataset.
- Predicting raw levels and celebrating a low RMSE that a "no change" baseline matches.
- Tuning repeatedly against the test set.
- Skipping baselines, or choosing a deep model by default when ridge or trees would do.
- Recursive multi-step forecasts without acknowledging compounding error.
- Reporting one lucky split instead of a distribution across folds.