Sub topic 1
What Makes Time Series Data Different
Prerequisites
This chapter assumes Python and pandas basics, supervised learning, and scikit-learn’s fit and predict pattern.
Time Order Changes the Problem
A time series is a sequence of observations indexed by time. Examples include daily sales, hourly temperature, and monthly revenue.
Time order matters because nearby observations are often related. This relationship is called autocorrelation. A series may also contain:
- Trend: a long-term rise or fall.
- Seasonality: a repeating pattern, such as higher sales every weekend.
- Frequency: the spacing between observations, such as hourly or daily.
A random train/test split can place future observations in the training set. That gives the model information it would not have when making a real forecast.
Turning a Series into a Supervised Learning Table
Forecasting can be framed as tabular regression. Each row contains information available at a prediction time, and the target is a later value.
For example, yesterday’s value can predict today’s value:
| time | lag_1 | target |
|---|---|---|
| Tuesday | 120 | 125 |
This framing assumes that useful patterns in the past can help predict the future and that the feature definitions will also be available when forecasting.
Measuring Forecast Error
For actual values \(y\) and predictions \(\hat y\):
- MAE is the average absolute error. It is easy to interpret in the target’s units.
- RMSE is the square root of average squared error. It penalizes large errors more strongly.
- Scaled errors, such as MASE, compare errors with a simple reference forecast and help compare different series.
Always calculate metrics on rows that were not used for fitting.
Baselines You Must Beat
A naive forecast uses the previous value:
\[ \hat yt = y{t-1} \]
A seasonal-naive forecast uses the value from the previous season, such as seven days earlier for daily data with weekly seasonality:
\[ \hat yt = y{t-7} \]
A complex model that cannot beat these baselines has not demonstrated value.
Building Lag Features
A lag feature shifts known observations into earlier columns. Rolling features summarize recent history, but the window must exclude the current target.
import pandas as pd
def make_features(series):
df = pd.DataFrame({"y": series})
df["lag_1"] = series.shift(1)
df["lag_7"] = series.shift(7)
past = series.shift(1)
df["rolling_mean_7"] = past.rolling(7).mean()
return df.dropna()Shifting before rolling prevents target leakage, where the feature accidentally uses the value it is supposed to predict.
Exercise
Why should a daily forecasting model compare itself with a lag-7 baseline?
Show answer
A lag-7 baseline captures weekly seasonality. The model should beat it to show that its additional features provide useful information.