Multivariate Forecasts: Beijing Multi-Site Air-Quality Data

We’ll demonstrate several features of torchcast using a dataset from the UCI Machine Learning Data Repository. It includes data on air pollutants and weather from 12 sites.

We’ll be building a model to predict total particulate-matter (PM2.5 and PM10). Real-world sensors don’t always report. To make things more realistic, we’ll simulate sensor outages: at each station, the PM2.5 and PM10 sensors are each down about 15% of the time, in runs of a few days, and rarely at the same time.

[4]:
df_aq = load_air_quality_data('daily', outage_prob=.15)

SPLIT_DT = np.datetime64('2014-03-01')
df_aq['dataset'] = np.where(df_aq['date'] > SPLIT_DT, 'val', 'train')
df_aq
[4]:
date station PM2p5 PM10 SO2 NO2 CO O3 TEMP PRES DEWP RAIN WSPM dataset
0 2013-03-01 Aotizhongxin 7.125000 10.750000 11.708333 22.583333 429.166667 63.875000 1.391667 1026.875000 -18.745833 0.0 3.254167 train
1 2013-03-02 Aotizhongxin 30.750000 42.083333 36.625000 66.666667 824.916667 29.750000 0.616667 1026.850000 -15.937500 0.0 1.479167 train
2 2013-03-03 Aotizhongxin 76.916667 120.541667 61.291667 81.000000 1620.625000 19.125000 5.566667 1014.608333 -12.316667 0.0 1.658333 train
3 2013-03-04 Aotizhongxin 22.708333 44.583333 22.869565 46.956522 617.391304 53.750000 9.962500 1017.650000 -11.683333 0.0 2.404167 train
4 2013-03-05 Aotizhongxin 148.875000 183.791667 93.875000 132.833333 2357.958333 68.458333 6.291667 1010.900000 -7.525000 0.0 1.129167 train
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
17527 2017-02-24 Wanshouxigong NaN 48.916667 9.250000 52.041667 887.500000 39.000000 5.166667 1021.012500 -11.141667 0.0 1.595833 val
17528 2017-02-25 Wanshouxigong NaN 15.750000 3.350000 31.050000 400.000000 54.300000 7.245833 1018.812500 -10.754167 0.0 1.825000 val
17529 2017-02-26 Wanshouxigong NaN 45.909091 8.727273 57.909091 545.454545 34.047619 7.208333 1020.337500 -8.258333 0.0 1.566667 val
17530 2017-02-27 Wanshouxigong NaN 88.857143 14.714286 84.571429 1457.142857 19.380952 8.337500 1017.141667 -7.145833 0.0 1.516667 val
17531 2017-02-28 Wanshouxigong 10.958333 21.541667 4.956522 31.391304 530.434783 54.913043 10.958333 1014.887500 -12.783333 0.0 2.058333 val

17532 rows × 14 columns

Univariate Forecasts

First, let’s build a model that trains and forecasts on the total (PM2.5 + PM10).

[5]:
df_aq['PM'] = df_aq['PM10'] + df_aq['PM2p5']
[6]:
# create our dataset:
dataset_pm = TimeSeriesDataset.from_dataframe(
    dataframe=df_aq,
    dt_unit='D',
    measure_colnames=['PM'],
    group_colname='station',
    time_colname='date',
    # throughout we'll log-transform, since it's strictly positive:
    transform=LogTransform()
)
dataset_pm_train, _ = dataset_pm.train_val_split(dt=SPLIT_DT)
[7]:
# specify our model:
from torchcast.process import LocalTrend, Season

kf_pm = KalmanFilter(
    measures=['PM'],
    processes=[
        LocalTrend(id='trend'),
        Season(
            id='day_in_year',
            period=365.25,
            dt_unit='D',
            K=4,
            fixed=True
        ),
        Season(
            id='day_in_week',
            period=7,
            dt_unit='D',
            K=2,
            fixed=True
        )
    ],
)
[8]:
# fit it:
kf_pm.fit(
    dataset_pm_train.tensors[0],
    start_offsets=dataset_pm_train.start_datetimes,
    n_step=5, every_step=False,
)
For measure PM, setting initial value by setting 'trend.position' to 5.0286
[8]:
KalmanFilter(
  (measure_covariance): Covariance()
  (processes): ModuleDict(
    (trend): LocalTrend(id='trend', measure='PM')
    (day_in_year): Season(id='day_in_year', measure='PM')
    (day_in_week): Season(id='day_in_week', measure='PM')
  )
  (process_covariance): Covariance()
  (initial_covariance): Covariance()
)

The n_step argument

When fitting our model, we use the n_step argument to improve longer-range forecasts. We know we will be using our model to forecast weeks/months into the future, so we ‘encourage’ the model to get good at this task by optimizing for 5-step-ahead forecasts (rather than the traditional 1-step-ahead forecasts) in training.

This simple strategy can often dramatically improve the quality of long-range forecasts; and paired with the every_step=False setting, does not cause an increase in training-time.

Let’s see how our forecasts look:

Our model’s predictions are on the log scale, since we passed transform=LogTransform() above. There, it didn’t buy us much relative to a quick df_aq.assign(PM_log=lambda df: np.log(df['PM'])). However, where torchcast’s transform API really pays off is when we want to bring our model and its predictions back to the original (not log) scale. Below, forecast.to_dataframe(transform=LogTransform()) correctly back-transforms the mean (i.e. \(E[e^{Y}]\), not to be confused with \(e^{E[Y]}\)) as well as providing prediction intervals.

[9]:
# generate forecasts:
forecast = kf_pm(
        dataset_pm_train.tensors[0],
        start_offsets=dataset_pm_train.start_datetimes,
        out_timesteps=dataset_pm.tensors[0].shape[1]
)

# convert to dataframe, back-transform:
df_uv_pred = (forecast
             .set_metadata(group_colname='station', time_colname='date')
             .to_dataframe(dataset_pm, transform=LogTransform()))

# plot:
forecast.plot(
    df_uv_pred.query("date>'2013-04-01'").query("station.isin(['Aotizhongxin', 'Dingling'])"),
    max_num_groups=2,
    split_dt=SPLIT_DT,
    figure_size=(6,5)
) #+ scale_y_log10()
../_images/examples_air_quality_12_0.png

Multivariate Forecasts

Can we improve our model by splitting the pollutant we are forecasting into its two types (2.5 and 10), and modeling them in a multivariate manner?

There are a few reasons to hope so:

  • The univariate model loses the total whenever either sensor is down. A multivariate model can still learn from whichever sensor is reporting. Since the two pollutants are strongly correlated, an observation of one is informative about the other.

  • We are only forecasting from a year of training data, which means the signal-to-noise ratio–especially for annual seasonal cycles–is quite poor. Every bit of additional information may help.

[10]:
# create a dataset:
dataset_pm_mv = TimeSeriesDataset.from_dataframe(
    dataframe=df_aq,
    dt_unit='D',
    measure_colnames=['PM10','PM2p5'],
    group_colname='station',
    time_colname='date',
    transform=LogTransform()
)
dataset_pm_mv_train, _ = dataset_pm_mv.train_val_split(dt=SPLIT_DT)

# create a model:
_processes = []
for m in dataset_pm_mv.measures[0]:
    _processes.extend([

        LocalTrend(id=f'{m}_trend', measure=m),

        Season(
            id=f'{m}_day_in_year',
            period=365.25,
            dt_unit='D',
            K=4,
            measure=m,
            fixed=True
        ),

        Season(
            id=f'{m}_day_in_week',
            period=7,
            dt_unit='D',
            K=2,
            measure=m,
            fixed=True
        )

    ])
kf_pm_mv = KalmanFilter(
    measures=dataset_pm_mv.measures[0],
    processes=_processes,
)

# fit:
kf_pm_mv.fit(
    dataset_pm_mv_train.tensors[0],
    start_offsets=dataset_pm_mv_train.start_datetimes,
    n_step=5, every_step=False,
)
For measure PM10, setting initial value by setting 'PM10_trend.position' to 4.4608
For measure PM2p5, setting initial value by setting 'PM2p5_trend.position' to 4.1396
[10]:
KalmanFilter(
  (measure_covariance): Covariance()
  (processes): ModuleDict(
    (PM10_trend): LocalTrend(id='PM10_trend', measure='PM10')
    (PM10_day_in_year): Season(id='PM10_day_in_year', measure='PM10')
    (PM10_day_in_week): Season(id='PM10_day_in_week', measure='PM10')
    (PM2p5_trend): LocalTrend(id='PM2p5_trend', measure='PM2p5')
    (PM2p5_day_in_year): Season(id='PM2p5_day_in_year', measure='PM2p5')
    (PM2p5_day_in_week): Season(id='PM2p5_day_in_week', measure='PM2p5')
  )
  (process_covariance): Covariance()
  (initial_covariance): Covariance()
)

Generate our forecasts as before:

[11]:
with torch.no_grad():
    forecast_mv = kf_pm_mv(
        dataset_pm_mv_train.tensors[0],
        start_offsets=dataset_pm_mv_train.start_datetimes,
        out_timesteps=dataset_pm_mv.num_timesteps # <--- how we ask it to forecast past original times
    )

forecast_mv.plot(
    forecast_mv
    .set_metadata(group_colname='station', time_colname='date')
    .to_dataframe(dataset_pm_mv, transform=LogTransform())
    .query("date>'2013-04-01'"),
    max_num_groups=2,
    split_dt=SPLIT_DT,
)
Subsetting to groups: ['Aotizhongxin', 'Dingling']
../_images/examples_air_quality_16_1.png

Now our forecast -> plot code gives us the individual values, but we’re ultimately interested in the total PM values across both types.

We could take the sum of our forecasts to get the forecast of the sum, since means can be summed. But the prediction-intervals would be wrong (unless the two were completely uncorrelated which is false), so let’s do better. We can use the derived argument to to_dataframe(). This lets us specify a quantity computed from multiple measures: here, the sum of PM10 and PM2.5 on the original scale.

Under the hood, torchcast draws samples from the joint forecast distribution – accounting for the correlation between the two measures – back-transforms them (via transform), sums them, and then summarizes across samples to get the mean and prediction intervals. (The same function is applied to the actuals, giving the actual total.)

[12]:
df_mv_pred = (forecast_mv
              .to_dataframe(
                  dataset_pm_mv,
                  transform=LogTransform(),
                  derived={'PM': lambda s: s['PM10'] + s['PM2p5']}
              )
              .query("measure == 'PM'"))
df_mv_pred.head()
[12]:
mean lower upper actual station date measure
0 629.013367 3.729140 4124.258301 17.875000 Aotizhongxin 2013-03-01 PM
1 714.027039 81.093719 2825.856934 72.833328 Aotizhongxin 2013-03-02 PM
2 592.589294 73.263680 2239.791504 197.458328 Aotizhongxin 2013-03-03 PM
3 425.703461 47.242283 1594.383911 67.291672 Aotizhongxin 2013-03-04 PM
4 262.384827 19.633688 1197.623901 332.666656 Aotizhongxin 2013-03-05 PM

Evaluating Performance

We evaluate on the days where the total was observed.

[13]:
def get_station_error(df: pd.DataFrame, pred_colname: str = 'mean', actual_colname: str = 'actual') -> pd.DataFrame:
    return (df
             .assign(sq_error=lambda df: (df[pred_colname] - df[actual_colname]) ** 2)
             .groupby(['station'])
             ['sq_error'].mean()
             .reset_index()
             .assign(rmse= lambda df: df['sq_error'] ** .5))

def agg_within_group_err(df: pd.DataFrame, error_col : str = 'rmse', group_col: str = 'station') -> pd.DataFrame:
    df = df.copy(deep=False)
    df['error_norm'] = df[error_col] - df.groupby(group_col)[error_col].transform('mean')
    return df.groupby('model').agg(**{error_col : (error_col, 'mean'), 'sem' : ('error_norm', 'sem')})
[14]:
df_fct_err = pd.concat([
            df_uv_pred
             .loc[lambda df: df['date'] > SPLIT_DT,:]
             .pipe(get_station_error)
             .assign(model='univariate')
            ,
            df_mv_pred
             .loc[lambda df: df['date'] > SPLIT_DT,:]
             .pipe(get_station_error)
             .assign(model='multivariate')
]).reset_index(drop=True)
df_fct_err.sort_values('station').tail(6)
[14]:
station sq_error rmse model
21 Tiantan 22498.703125 149.995682 multivariate
9 Tiantan 23666.714844 153.839905 univariate
22 Wanliu 23991.802734 154.892868 multivariate
10 Wanliu 23881.294922 154.535736 univariate
11 Wanshouxigong 27744.376953 166.566437 univariate
23 Wanshouxigong 26530.140625 162.880753 multivariate

Below we aggregate the performance across stations (controlling for within-station variation to reduce noise).

Here, the multivariate model comes out slightly ahead: summing its two forecasts beats forecasting the total directly. But a comparison like this one – a single forecast per station, all from the same date – is noisy, since it depends on how things happened to go after that one date.

[15]:
df_fct_err_agg = agg_within_group_err(df_fct_err)

# https://chris-said.io/2014/12/01/independent-t-tests-and-the-83-confidence-interval-a-useful-trick-for-eyeballing-your-data/
from scipy import stats
sem_multi = -stats.norm.ppf((1 - .83) / 2)

df_fct_err_agg['rmse'].plot(
    kind='bar',
    yerr=df_fct_err_agg['sem'] * sem_multi,
    ylabel="Root Sq. Err\n(lower is better)",
    title="Forecasting Error",
    ylim=(145,160)
)
plt.show()
../_images/examples_air_quality_23_0.png

Expanding Window Approach

One limitation to evaluating performance with a single train/val split-date is we run the risk that our results are sensitive to that particular split.

An alternative approach is an “expanding window”: we loop over the series, training on increasingly long sections, and forecasting on a fixed period beyond this. For short series, it might make sense to retrain on each iteration.

However for longer series, to speed up the process, we might want to simply use a particular date-range for training, then do our expanding window procedure on the held out remainder. (This is challenging in many forecasting APIs because they do not allow passing new series – or extensions of the trained series – at inference time, but instead require retraining.)

In torchcast, it’s easy to apply an expanding-window method with the n_step argument, avoiding the need for any refit -> forecast external loop.

[16]:
with torch.no_grad():
    one_mo_uv = kf_pm(
        dataset_pm.tensors[0],
        start_offsets=dataset_pm.start_datetimes,
        n_step=30
    )
    one_mo_mv = kf_pm_mv(
        dataset_pm_mv.tensors[0],
        start_offsets=dataset_pm_mv.start_datetimes,
        n_step=30
    )

df_backtest_err1mo = pd.concat([

    one_mo_uv
    .to_dataframe(dataset_pm, time_colname='date', group_colname='station', transform=LogTransform())
    .loc[lambda df: df['date'] > SPLIT_DT, :]
    .pipe(get_station_error)
    .assign(model='univariate')
    ,

    one_mo_mv
    .to_dataframe(
        dataset_pm_mv,
        time_colname='date',
        group_colname='station',
        transform=LogTransform(),
        derived={'PM': lambda s: s['PM10'] + s['PM2p5']}
    )
    .query("measure == 'PM'")
    .loc[lambda df: df['date'] > SPLIT_DT,:]
    .pipe(get_station_error)
    .assign(model='multivariate')
])

df_backtest1mo_err_agg = agg_within_group_err(df_backtest_err1mo)

df_backtest1mo_err_agg['rmse'].plot(
    kind='bar',
    yerr=df_backtest1mo_err_agg['sem'],
    ylabel="Root Sq. Err\n(lower is better)",
    title="Expanding-Window (1-Month-Ahead) Error",
    ylim=(140,155)
)
plt.show()
../_images/examples_air_quality_25_0.png

Averaged over many forecast-dates, the multivariate model is clearly better. Why? The univariate model loses the total whenever either sensor is down. The multivariate model not only keeps learning from whichever sensor is reporting, but – since the two pollutants are strongly correlated – uses it to fill in for the one that’s down.

The advantage comes from the sensor outages: without them (try above), the two approaches perform about the same. The model here also performs better than summing two individual models (i.e. one model for PM2.5, one for PM10). While the gain here is limited (and diminishes with more data – try moving SPLIT_DT to a later date), the lesson remains: with noisy, partial data, a multivariate model is generally worth a shot.

Adding Predictors

In many settings we have external (a.k.a. exogenous) predictors we’d like to incorporate. Here we’ll use four predictors corresponding to weather conditions. Of course, in a forecasting context, we run into the problem of needing to fill in values for these predictors for future dates. For an arbitrary forecast horizon this can be a complex issue; for simplicity here we’ll focus on the 4-week-ahead predictions we used above, and simply lag our weather predictors by 4.

[17]:
from torchcast.process import LinearModel

# prepare external predictors:
predictors_raw = ['TEMP', 'PRES', 'DEWP']
predictors = [p.lower() + '_lag30' for p in predictors_raw]
# standardize:
predictor_means = df_aq.query("dataset=='train'")[predictors_raw].mean()
predictor_stds = df_aq.query("dataset=='train'")[predictors_raw].std()
df_aq[predictors] = (df_aq[predictors_raw] - predictor_means) / predictor_stds
# lag:
df_aq[predictors] = df_aq.groupby('station')[predictors].shift(30, fill_value=0)

# create dataset:
dataset_pm_lm = TimeSeriesDataset.from_dataframe(
    dataframe=df_aq,
    dt_unit='D',
    y_colnames=['PM10','PM2p5'],
    X_colnames=predictors,
    group_colname='station',
    time_colname='date',
    transform=LogTransform()
)
dataset_pm_lm_train, _ = dataset_pm_lm.train_val_split(dt=SPLIT_DT)
dataset_pm_lm_train
[17]:
TimeSeriesDataset(sizes=[torch.Size([12, 365, 2]), torch.Size([12, 365, 3])], measures=(('PM10', 'PM2p5'), ('temp_lag30', 'pres_lag30', 'dewp_lag30')))
[18]:
_processes = []
for m in dataset_pm_lm.measures[0]:
    _processes.extend([
        LocalTrend(id=f'{m}_trend', measure=m),

        Season(
            id=f'{m}_day_in_year',
            period=365.25,
            dt_unit='D',
            K=4,
            measure=m,
            fixed=True
        ),

        Season(
            id=f'{m}_day_in_week',
            period=7,
            dt_unit='D',
            K=2,
            measure=m,
            fixed=True
        ),


        LinearModel(
            id=f'{m}_lm',
            predictors=predictors,
            measure=m
        )
    ])
kf_pm_lm = KalmanFilter(
    measures=dataset_pm_lm.measures[0], processes=_processes
)
[19]:
# fit:
y, X = dataset_pm_lm_train.tensors
kf_pm_lm.fit(
    y,
    X=X, # if you want to supply different predictors to different processes, you can use `{process_name}__X`
    start_offsets=dataset_pm_lm_train.start_datetimes,
    n_step=5,
    every_step=False
)
For measure PM10, setting initial value by setting 'PM10_trend.position' to 4.4608
For measure PM2p5, setting initial value by setting 'PM2p5_trend.position' to 4.1396
[19]:
KalmanFilter(
  (measure_covariance): Covariance()
  (processes): ModuleDict(
    (PM10_trend): LocalTrend(id='PM10_trend', measure='PM10')
    (PM10_day_in_year): Season(id='PM10_day_in_year', measure='PM10')
    (PM10_day_in_week): Season(id='PM10_day_in_week', measure='PM10')
    (PM10_lm): LinearModel(id='PM10_lm', measure='PM10')
    (PM2p5_trend): LocalTrend(id='PM2p5_trend', measure='PM2p5')
    (PM2p5_day_in_year): Season(id='PM2p5_day_in_year', measure='PM2p5')
    (PM2p5_day_in_week): Season(id='PM2p5_day_in_week', measure='PM2p5')
    (PM2p5_lm): LinearModel(id='PM2p5_lm', measure='PM2p5')
  )
  (process_covariance): Covariance()
  (initial_covariance): Covariance()
)

Here we show how to inspect the influence of each predictor:

[20]:
# inspect components:
with torch.no_grad():
    y, X = dataset_pm_lm.tensors
    one_mo_lm = kf_pm_lm(
        y,
        X=X,
        start_offsets=dataset_pm_lm.start_datetimes,
        n_step=30
    )
one_mo_lm.plot(
    one_mo_lm
    .to_dataframe(dataset_pm_lm, type='observed_states')
    .query("process.str.contains('lm')")
    .query("time>'2013-04-01'")
    ,
    split_dt=SPLIT_DT,
    figure_size=(6,5)
) + facet_wrap('measure', ncol=1)
Subsetting to groups: ['Wanliu']
../_images/examples_air_quality_32_1.png

Re-Evaluate Performance

Now let’s look at the change in error from our earlier multivariate model vs. one that includes predictors.

We can’t compare the forecasts, since we have a fixed lag on our predictors. But we can easily compare the expanding-window results:

[21]:
df_backtest1mo_err_agg2 = agg_within_group_err(
    pd.concat([
        # old ones:
        df_backtest_err1mo,
        # new one:
        one_mo_lm
        .to_dataframe(
            dataset_pm_lm,
            time_colname='date',
            group_colname='station',
            transform=LogTransform(),
            derived={'PM': lambda s: s['PM10'] + s['PM2p5']}
        )
        .query("measure == 'PM'")
        .loc[lambda df: df['date'] > SPLIT_DT,:]
        .pipe(get_station_error)
        .assign(model='mv_with_preds')
    ])
)

df_backtest1mo_err_agg2['rmse'].plot(
    kind='bar',
    yerr=df_backtest1mo_err_agg2['sem'] * sem_multi,
    ylabel="Root Sq. Err\n(lower is better)",
    title="Backtesting (1-Month-Ahead) Error",
    ylim=(140,155)
)
plt.show()
../_images/examples_air_quality_35_0.png

We see that, in this context, the lagged predictors actually hurt our 1-month-ahead forecasts.