Sequences & Time-Series Learning
Learn how order changes prediction. Decompose temporal signals, build leakage-safe forecasting experiments and trace how recurrent networks carry useful memory through time.
hₜ = f(xₜ, hₜ₋₁)By the End of This Level, You Can
Six Building Blocks of Temporal Learning
A sequence model must respect what was known, when it was known and what must be predicted.
Changing position can change meaning, causality and the valid prediction target.
Regular or irregular spacing determines valid lags, windows and evaluation.
A lag-k feature uses the observation recorded k steps before the prediction time.
A window converts recent observations into one supervised-learning input.
One-step and multi-step forecasts solve different uncertainty problems.
A recurrent state carries selected information from earlier sequence positions.
Sequence Order Is Part of the Data
Tabular rows may be exchangeable; temporal rows usually are not.
xₜ₋w … xₜPast observations form the information available now.
f(history, covariates)The model extracts temporal relationships and external effects.
ŷₜ₊₁ … ŷₜ₊HThe output covers the required future decision window.
A sequence is any ordered collection—sensor readings, transactions, words, clicks or medical measurements. A time series additionally associates observations with time. The model input must include only evidence available before the forecast origin. Static features describe the entity, known-future features such as calendar events may be used across the horizon, and observed covariates must stop at the forecast origin. This information boundary is the foundation of trustworthy temporal learning.
To predict tomorrow’s demand tonight, tomorrow’s weekday is known, but tomorrow’s actual temperature is not unless a separate weather forecast is supplied.
Begin every forecasting answer by defining frequency, context window, horizon and available covariates.
Randomly shuffling time-series rows can allow future patterns to influence training and create unrealistic validation scores.
Trend, Seasonality and Noise Explain Different Temporal Structure
Decomposition separates persistent movement from repeating patterns and unexplained variation.
ℓₜLocal baselineThe current average magnitude around which observations move.
TₜLong-term directionPersistent growth or decline across a substantial interval.
Sₜ₋ₘ = SₜFixed-period repetitionDaily, weekly, monthly or annual patterns tied to a known period.
RₜUnexplained variationNoise, shocks, anomalies and structure not captured elsewhere.
An additive model writes yₜ = Tₜ + Sₜ + Rₜ and suits roughly constant seasonal amplitude. A multiplicative model writes yₜ = Tₜ × Sₜ × Rₜ and suits seasonal swings that grow with the series level. Cycles differ from seasonality because their duration is not fixed. Decomposition is diagnostic: it reveals transformations, baseline candidates, anomalies and whether a seasonal period is plausible.
Sales rising by about 20 units every festival season suggest additive seasonality; sales rising by about 20% suggest multiplicative seasonality.
Explain why seasonality must be established from domain frequency rather than selected only from a visually attractive plot.
A smooth upward segment is not proof of a permanent trend; it may be one phase of a longer cycle or structural break.
Stationarity and Autocorrelation Describe Temporal Dependence
Classical models work best when the probabilistic behaviour is stable enough to learn from the past.
The expected level should not drift continuously after required transformation or differencing.
Volatility should remain comparable; logarithms can stabilize scale-dependent variation.
ACF measures correlation between a series and lagged copies of itself.
PACF measures a lag’s remaining relationship after shorter lags are controlled.
Use Δyₜ = yₜ − yₜ₋₁ to remove a changing level when justified.
A policy, product or environment change can make older relationships less relevant.
Weak stationarity requires stable mean and variance with covariance determined by lag rather than absolute time. It is an approximation, not a visual checkbox. Plot the series, inspect rolling statistics, analyze ACF/PACF and use tests such as ADF together with domain evidence. Difference only enough to stabilize the series; excessive differencing amplifies noise and destroys useful long-run information.
If y = [10, 13, 16, 19], first differences are [3, 3, 3], turning a deterministic linear trend into a constant sequence.
State the null hypothesis when discussing ADF or KPSS instead of saying only that a p-value proves stationarity.
Stationarity does not mean every observation is equal; it means the generating behaviour is stable in specified statistical properties.
📈 Forecast Origin & Baseline Workbench
Run chronological backtesting on a real numerical series. Change the signal, method, seasonal period and horizon; inspect every forecast and calculated error metric.
Baselines Reveal Whether Complexity Adds Value
A model is useful only when it beats a credible simple forecast under the same test protocol.
- Select history available at the origin.
- Calculate the historical or rolling mean.
- Repeat it across the required horizon.
- Update only when new actual data arrives.
- Compare against other baselines.
- Read the latest observed value.
- Use it as the next prediction.
- For walk-forward testing, reveal the next actual.
- Move the origin forward by one step.
- Repeat without peeking ahead.
- Confirm a meaningful seasonal period m.
- Find the value recorded m steps earlier.
- Copy it to the matching future position.
- Repeat for every horizon step.
- Evaluate across multiple seasons.
- Estimate change across historical time.
- Project the slope beyond the origin.
- Generate each horizon value separately.
- Check for unrealistic extrapolation.
- Compare errors and residual bias.
Baselines are diagnostic tools, not weak formalities. A last-value forecast is strong for slowly changing signals, seasonal naive is strong for stable periodic behaviour, and a drift baseline handles a persistent linear direction. Backtesting should reproduce deployment: fixed-origin evaluation tests one decision time, while rolling-origin evaluation repeatedly advances time and summarizes errors across origins.
For weekly demand [20, 30, 22, 35, 21, 31, 23, 36], seasonal naive with period 4 predicts the next values from [21, 31, 23, 36].
Interviewers expect a baseline, chronological split and business-relevant horizon before an advanced architecture.
Low training error does not show forecasting ability because deployment requires prediction beyond the observed boundary.
AR, MA, ARIMA and Exponential Smoothing Encode Different Assumptions
Classical forecasting remains powerful when structure, data volume and interpretability favour compact models.
yₜ = c + Σφᵢyₜ₋ᵢ + εₜPast values predict nowAR(p) learns linear dependence on p earlier observations.
yₜ = μ + Σθⱼεₜ₋ⱼ + εₜPast shocks predict nowMA(q) models serial structure in earlier forecast errors.
ARIMA(p,d,q)Difference, then modeld controls differencing while p and q control AR and MA orders.
ℓₜ = αyₜ + (1−α)ℓₜ₋₁Recent values receive more weightHolt and Holt–Winters extend smoothing with trend and seasonality.
ARIMA describes a univariate linear process after differencing; seasonal ARIMA adds seasonal AR, differencing and MA components. Exponential-smoothing state-space methods update level, trend and seasonal states directly. Select orders using domain evidence, diagnostics and validated performance—not ACF/PACF alone. Residuals should be centered, approximately uncorrelated and free of systematic patterns that the model should have learned.
With α=0.4, observation 20 and previous level 15, the new smoothed level is 0.4×20 + 0.6×15 = 17.
Compare ARIMA’s interpretable linear lag structure with neural models’ flexible nonlinear representations and higher data needs.
The MA in ARIMA models past errors; it is not the same operation as a simple rolling average of observations.
Windowing Converts Temporal Prediction into Supervised Learning
The window, horizon and feature-availability rules define every training example.
Select time t without crossing the split.
Use values xₜ₋w₊₁ … xₜ.
Use yₜ₊₁ … yₜ₊H.
Fit transformations on training history.
Advance origins chronologically.
A sliding window creates overlapping samples, but those samples remain strongly related. Split the original timeline before constructing train and validation windows or explicitly prevent overlap across boundaries. For multiple entities, decide whether the model is local, global or hierarchical. Scaling parameters, missing-value rules, lag features and rolling aggregates must all be fitted or calculated without future observations.
For [4, 7, 9, 12, 13] with window 3 and horizon 1, samples are [4,7,9]→12 and [7,9,12]→13.
Explain direct, recursive and multi-output forecasting for horizon H, including error accumulation and model count.
Fitting a scaler on the full series leaks future distribution information even when the labels themselves are hidden.
🧠 RNN, LSTM & GRU Memory Laboratory
Feed one sequence value at a time. Inspect candidate memory, gates, hidden state and prediction instead of viewing a static architecture diagram.
RNNs Reuse One Transition Across Every Time Step
A simple recurrent network combines the current input with its previous hidden state.
hₜ = tanh(Wₓxₜ + Wₕhₜ₋₁ + b)Compressed sequence historyThe same transition parameters are reused at every position.
ŷₜ = g(Wᵧhₜ + bᵧ)Prediction from current stateOutputs may be produced at every step or only after the final step.
∂L/∂W = Σₜ contributionsBackpropagation through timeThe recurrent graph is unrolled and differentiated across time.
g ← g·τ/||g||Control exploding gradientsScale overly large gradient norms before the optimizer update.
An RNN shares parameters through time, allowing variable-length inputs and position-aware computation. During backpropagation, repeated multiplication by recurrent Jacobians can shrink gradients toward zero or grow them rapidly. Truncated BPTT limits the number of unrolled steps for efficiency but also limits how directly gradients connect distant events. Padding masks must prevent artificial padded positions from changing state or loss.
If the recurrent derivative is repeatedly about 0.5, a signal propagated through ten steps is scaled by roughly 0.5¹⁰ ≈ 0.001.
Explain parameter sharing, many-to-one versus many-to-many outputs and why long dependencies challenge simple RNNs.
The hidden state is not guaranteed to remember everything; it is a limited learned summary that can overwrite older information.
LSTM and GRU Use Gates to Control Memory
Gated cells create shorter paths for important information and gradients.
- Read xₜ and hₜ₋₁.
- Calculate fₜ with a sigmoid.
- Scale the previous cell state fₜ⊙cₜ₋₁.
- Retain values near one.
- Remove values near zero.
- Calculate input gate iₜ.
- Calculate candidate memory c̃ₜ.
- Write iₜ⊙c̃ₜ into the cell.
- Add retained earlier memory.
- Produce hₜ through output gate oₜ.
- Calculate reset gate rₜ.
- Build candidate using reset history.
- Calculate update gate zₜ.
- Blend previous and candidate state.
- Use one state instead of separate h and c.
- Start with a validated baseline.
- Match capacity to data size and latency.
- Use masks for variable lengths.
- Compare RNN, GRU and LSTM fairly.
- Prefer evidence over architectural habit.
An LSTM maintains a cell state cₜ and hidden output hₜ. Forget, input and output gates separately regulate retention, writing and exposure. A GRU merges cell and hidden state and uses reset and update gates, often reducing parameters. Gates are continuous values learned from data—not manual switches. Bidirectional recurrence can use both directions for classification or labelling, but it is invalid for causal forecasting when future values would be unavailable.
If f=0.9, previous c=2, i=0.2 and candidate=0.5, the new cell is 0.9×2 + 0.2×0.5 = 1.9.
Derive LSTM equations, state tensor shapes and parameter count for input size d and hidden size h.
LSTM reduces vanishing-gradient difficulty but does not guarantee unlimited memory or superior performance on every dataset.
Forecast Metrics Must Match Scale and Decision Cost
One metric rarely describes every operational consequence.
mean(|y−ŷ|)Average absolute missReadable in target units and less dominated by large errors than RMSE.
√mean((y−ŷ)²)Emphasizes large missesUseful when large deviations carry disproportionate cost.
mean(|(y−ŷ)/y|)×100Percentage errorEasy to communicate but unstable near zero and asymmetric.
MAE / naive-training-MAEScale-free baseline ratioValues below one beat the chosen in-sample naive benchmark.
Report metrics per horizon as well as aggregated, because distant forecasts usually degrade. Prediction intervals express uncertainty and should be checked for coverage and useful width. Residual analysis searches for bias, remaining autocorrelation, changing variance and failure during important segments. For inventory, under-forecast and over-forecast may have different costs, requiring asymmetric loss or decision simulation.
Actual [10,20], predictions [12,16] give absolute errors [2,4], MAE 3 and RMSE √10 ≈ 3.16.
Connect offline forecast error to downstream decisions such as staffing, stockouts, energy reserve or alert capacity.
MAPE should not be used blindly when actual values can be zero, negative or very small.
Reliable Temporal Systems Reproduce the Deployment Clock
Training, backtesting and serving must share the same feature-availability contract.
Model features using their real arrival time, not only the timestamp they describe.
Historical tables may contain corrected values that were not available originally.
Relationships may change after policy, product, market or sensor changes.
Choose expanding or rolling windows and validate the schedule chronologically.
Serve uncertainty estimates when decisions depend on worst-case demand.
Track freshness, missingness, residuals, bias, coverage and horizon-specific error.
A timestamped feature can still leak if it arrives after the prediction must be made. Point-in-time correct joins reconstruct the information actually available at every historical origin. Production evaluation should include delayed labels, missing periods, cold-start entities, unexpected events and retraining cost. Champion–challenger deployment compares a new model against the current system under the same clock and decision rules.
A monthly revenue value finalized ten days after month end cannot be used for a forecast issued on the first day of the next month.
Describe a feature store or data pipeline using event time, processing time, cutoff time and label availability.
A chronological split alone does not prevent leakage when features were backfilled or published after the forecast origin.
📡 Time-Series Modelling — Visual Flow
Preserve the temporal reasoning chain from raw events to an operationally valid forecast.
Fix frequency, origin and horizon.
Inspect trend, seasonality and breaks.
Create lags and windows without leakage.
Beat credible baselines across origins.
Track residuals, intervals and drift.
Trace Rolling-Window Forecasting from First Principles
Follow each forecast origin, every value inside its historical window, the mean prediction and the accumulated absolute error. The cursor returns through both loops exactly as Python executes.
—Waiting for print(...)
Temporal Learning Logic Before Framework Calls
Use these procedure maps for revision, coding rounds and interviews.
- Choose chronological training and test boundaries.
- Fit all transformations on current history.
- Generate the required horizon forecast.
- Record errors before revealing later actuals.
- Advance the origin and summarize all folds.
- Plot and transform the training series.
- Difference only when justified.
- Propose p and q from evidence.
- Fit candidates and inspect residuals.
- Select using backtesting and stable diagnostics.
- Initialize hidden and optional cell state.
- Read one time-step input.
- Calculate gates or recurrent candidate.
- Update state and produce required output.
- Repeat with padding masks where necessary.
- Compare against naive and seasonal baselines.
- Plot error by horizon and segment.
- Inspect residual bias and autocorrelation.
- Check intervals, missingness and structural breaks.
- Change data or model using observed evidence.
💻 Time-Series & Sequence Challenges
Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.
Test Your Temporal Reasoning
Select one answer per question. Results show your choice, the correct answer and a clear explanation.
Diagnose Forecasting Systems Like an ML Engineer
Use temporal evidence and operational constraints before changing the architecture.
Check random splitting, overlapping windows, future-filled features, full-data scaling and backfilled values.
Verify frequency, seasonal period, missing timestamps, calendar effects and seasonal baseline.
Compare recursive and direct strategies, trend assumptions, covariates and interval width.
Inspect missing lags, seasonal structure and model underfitting.
Detect structural breaks, reweight recent history and reconsider retraining cadence.
Audit point-in-time joins, arrival delays, scaling state, missing-value policy and forecast origin.
🎤 Sequences & Time Series — Interview Questions
Answer aloud before selecting Show Answer for each explanation.
A Forecast Is a Decision Made at a Specific Time
Preserve temporal sequence.
Use only available evidence.
Measure simple forecasts first.
Model useful temporal state.
Backtest and monitor decisions.
Time-series learning becomes trustworthy when every forecast origin, lag, window, state update, horizon and error can be explained without using future information.
Eight Practical Time-Series Habits
Plot raw data with timestamps and missing intervals before building features.
Write the forecast origin and horizon beside every experiment.
Keep naive and seasonal-naive results visible throughout model development.
Fit scalers and imputers only on history available at each backtest fold.
Report error by horizon, entity, season and operationally important segment.
Plot residuals and their autocorrelation; do not rely only on one score.
Validate prediction-interval coverage as well as point forecasts.
Store frequency, cutoff, feature availability and preprocessing with the model.
Strengthen Temporal Learning Reasoning
Calculate intermediate values and defend every experimental decision.
- 01
Separate level, trend, seasonality and remainder in a business series.
- 02
Create lag-1, lag-2 and rolling-mean features without leakage.
- 03
Construct windows for context 4 and horizon 2.
- 04
Calculate naive and seasonal-naive forecasts by hand.
- 05
Calculate MAE, RMSE, MAPE and MASE for one forecast.
- 06
Difference a trending series and reconstruct its forecast.
- 07
Interpret an ACF/PACF pair cautiously.
- 08
Compare ARIMA, exponential smoothing and gradient boosting.
- 09
Trace a simple RNN through three time steps.
- 10
Calculate one LSTM cell-state update.
- 11
Compare LSTM and GRU parameterization.
- 12
Design rolling-origin backtesting for monthly demand.
- 13
Identify five forms of temporal leakage in a feature pipeline.
- 14
Design monitoring for horizon-specific error and interval coverage.
