Skip to main content

Chapter 19 demo: Rain in Australia

Read Chapter 19 · Download notebook (.ipynb)

This walkthrough uses Rain in Australia to practise a workflow you can adapt to HW8: identify separate time series, inspect their spacing, understand a future target, establish a persistence baseline, and compare calendar and lag features.

We keep a classification task: predict whether it will rain tomorrow. In HW8, you will adapt these ideas to regression and a weekly forecast horizon.

Run the cells in order. Download the dataset from here and place weatherAUS.csv in a data folder beside this notebook.

Setup and data

Investigate multiple time series, calendar and lag features, and time-aware validation.

Run cells in order with the repository’s Python environment selected as the kernel. From the repository root, start Jupyter with uv run --locked jupyter lab, then open book/demo-chapter-19-time-series.ipynb. Data paths work from either the repository root or book/. If using a downloaded notebook separately, place its required files in a data/ folder beside it.

Use data/weatherAUS.csv. Source: Rain in Australia. The class example predicts tomorrow’s rain; adapting it to a weekly regression task changes the target and forecast horizon.

Class route: Follow the class route through time structure, a persistence baseline, and calendar/lag comparisons. Use the later exploration where time permits.

Pause at prediction and discussion questions before revealing results. Rendered pages show saved outputs; controls that depend on a running Python kernel require Jupyter. General environment and download guidance is on the Demos page.

Show imports and setup
from pathlib import Path

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, balanced_accuracy_score
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

DATA_DIR = Path("data") if Path("data").is_dir() else Path("book") / "data"

Define the prediction task

At the end of each measurement day, predict RainTomorrow at the same location. We assume that day’s listed measurements are available at this time. In deployment, publication delays and the exact observation windows would need checking.

The target is categorical, so we use classification. We predict one day at a time: measurements arrive between predictions, while the fitted model stays fixed during each validation period. This is different from predicting an entire month’s rain at its beginning.

rain = pd.read_csv(DATA_DIR / "weatherAUS.csv", parse_dates=["Date"])
rain = rain.sort_values(["Location", "Date"]).reset_index(drop=True)
assert not rain.duplicated(["Location", "Date"]).any()
display(rain.head())
print("Locations:", rain["Location"].nunique())
print("Date range:", rain["Date"].min(), "to", rain["Date"].max())
display(rain.isna().mean().sort_values(ascending=False).head(8))
Date Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir WindGustSpeed WindDir9am ... Humidity9am Humidity3pm Pressure9am Pressure3pm Cloud9am Cloud3pm Temp9am Temp3pm RainToday RainTomorrow
0 2008-07-01 Adelaide 8.8 15.7 5.0 1.6 2.6 NW 48.0 SW ... 92.0 67.0 1017.4 1017.7 NaN NaN 13.5 14.9 Yes No
1 2008-07-02 Adelaide 12.7 15.8 0.8 1.4 7.8 SW 35.0 SSW ... 75.0 52.0 1022.4 1022.6 NaN NaN 13.7 15.5 No No
2 2008-07-03 Adelaide 6.2 15.1 0.0 1.8 2.1 W 20.0 NNE ... 81.0 56.0 1027.8 1026.5 NaN NaN 9.3 13.9 No No
3 2008-07-04 Adelaide 5.3 15.9 0.0 1.4 8.0 NNE 30.0 NNE ... 71.0 46.0 1028.7 1025.6 NaN NaN 10.2 15.3 No No
4 2008-07-05 Adelaide 9.8 15.4 0.0 NaN 0.9 N 30.0 NNE ... 56.0 67.0 1023.6 1020.2 NaN NaN 11.3 13.8 No NaN

5 rows × 23 columns

Locations: 49
Date range: 2007-11-01 00:00:00 to 2017-06-25 00:00:00
Sunshine       0.480098
Evaporation    0.431665
Cloud3pm       0.408071
Cloud9am       0.384216
Pressure9am    0.103568
Pressure3pm    0.103314
WindDir9am     0.072639
WindGustDir    0.070989
dtype: float64

Identify the separate time series

Several locations can have observations on the same date. Inspect repeated dates, then check whether (Location, Date) uniquely identifies an observation. In another dataset, you may need a combination of categorical columns to identify each series.

first_date = rain["Date"].value_counts().idxmax()
display(rain.loc[rain["Date"].eq(first_date), ["Date", "Location", "Rainfall"]].head(10))
series_summary = rain.groupby("Location").agg(
    rows=("Date", "size"), unique_dates=("Date", "nunique"),
    first_date=("Date", "min"), last_date=("Date", "max"))
display(series_summary.head())
assert series_summary["rows"].eq(series_summary["unique_dates"]).all()
Date Location Rainfall
1615 2013-03-01 Adelaide 0.0
4655 2013-03-01 Albany 0.0
7695 2013-03-01 Albury 0.4
10735 2013-03-01 AliceSprings 2.0
13744 2013-03-01 BadgerysCreek 30.6
16784 2013-03-01 Ballarat 0.0
19824 2013-03-01 Bendigo 0.2
23017 2013-03-01 Brisbane 0.0
26057 2013-03-01 Cairns 26.6
29493 2013-03-01 Canberra 11.8
rows unique_dates first_date last_date
Location
Adelaide 3193 3193 2008-07-01 2017-06-25
Albany 3040 3040 2008-12-01 2017-06-25
Albury 3040 3040 2008-12-01 2017-06-25
AliceSprings 3040 3040 2008-12-01 2017-06-25
BadgerysCreek 3009 3009 2009-01-01 2017-06-25

A series identifier does not establish that observations are independent or that geographic categories do not overlap. Nearby weather stations can share weather patterns. In other datasets, labels can mix cities, larger regions, and national totals.

Pause: What evidence would you inspect before adding measurements across geographic labels? Look at the labels and any dataset documentation; where meaningful, compare candidate totals with their components.

Inspect spacing within each series

Sort within each location before taking date differences. A difference across the whole dataframe could cross a location boundary.

spacing = rain.groupby("Location")["Date"].diff()
display(spacing.value_counts().sort_index().rename("Number of gaps"))
gap_summary = rain.assign(gap=spacing).groupby("Location")["gap"].agg(["min", "max"])
display(gap_summary.sort_values("max", ascending=False).head(10))
sydney = rain.loc[rain["Location"].eq("Sydney")]
sydney.plot(x="Date", y="Rainfall", figsize=(10, 3), ylabel="Rainfall (mm)")
plt.show()
Date
1 days     145268
2 days          2
4 days          1
6 days          1
9 days          1
29 days        46
31 days        46
32 days        46
Name: Number of gaps, dtype: int64
min max
Location
Adelaide 1 days 32 days
SalmonGums 1 days 32 days
NorfolkIsland 1 days 32 days
Nuriootpa 1 days 32 days
PearceRAAF 1 days 32 days
Penrith 1 days 32 days
Perth 1 days 32 days
PerthAirport 1 days 32 days
Portland 1 days 32 days
Richmond 1 days 32 days

Understand shifts and the future target

The file supplies RainTomorrow. To understand how a future target can be constructed, take the next row’s RainToday within the same location. Also shift its date so we can check the forecast horizon.

Pandas uses shift(1) for the previous observation and shift(-1) for the next observation. HW8’s create_lag_feature helper uses the opposite sign convention in its lag argument: negative = past, positive = future. Inspect the helper rather than assuming its signs match pandas.

A future value can define a target; it must not enter the predictors.

shift_example = rain[["Location", "Date", "RainToday", "RainTomorrow"]].copy()
by_location = rain.groupby("Location", sort=False)
shift_example["PreviousRainToday"] = by_location["RainToday"].shift(1)
shift_example["NextRainToday"] = by_location["RainToday"].shift(-1)
shift_example["NextDate"] = by_location["Date"].shift(-1)
is_next_day = shift_example["NextDate"].sub(shift_example["Date"]).eq(np.timedelta64(1, "D"))
shift_example["ConstructedRainTomorrow"] = shift_example["NextRainToday"].where(is_next_day)
display(shift_example.loc[shift_example["Location"].eq("Sydney")].head(8))
comparable = shift_example.loc[
    is_next_day & shift_example["RainTomorrow"].notna()
    & shift_example["ConstructedRainTomorrow"].notna()]
print("Comparable next-day observations:", len(comparable))
print("Agreement with supplied target:",
      comparable["RainTomorrow"].eq(comparable["ConstructedRainTomorrow"]).mean())
display(shift_example.loc[shift_example["NextDate"].notna() & ~is_next_day].head())
Location Date RainToday RainTomorrow PreviousRainToday NextRainToday NextDate ConstructedRainTomorrow
110359 Sydney 2008-02-01 Yes Yes NaN Yes 2008-02-02 Yes
110360 Sydney 2008-02-02 Yes Yes Yes Yes 2008-02-03 Yes
110361 Sydney 2008-02-03 Yes Yes Yes Yes 2008-02-04 Yes
110362 Sydney 2008-02-04 Yes Yes Yes Yes 2008-02-05 Yes
110363 Sydney 2008-02-05 Yes Yes Yes Yes 2008-02-06 Yes
110364 Sydney 2008-02-06 Yes Yes Yes Yes 2008-02-07 Yes
110365 Sydney 2008-02-07 Yes Yes Yes Yes 2008-02-08 Yes
110366 Sydney 2008-02-08 Yes Yes Yes Yes 2008-02-09 Yes
Comparable next-day observations: 142017
Agreement with supplied target: 1.0
Location Date RainToday RainTomorrow PreviousRainToday NextRainToday NextDate ConstructedRainTomorrow
1003 Adelaide 2011-03-31 No Yes No Yes 2011-05-01 NaN
1583 Adelaide 2012-11-30 Yes No No No 2013-01-01 NaN
1614 Adelaide 2013-01-31 Yes No No No 2013-03-01 NaN
4043 Albany 2011-03-31 No Yes No Yes 2011-05-01 NaN
4623 Albany 2012-11-30 Yes NaN Yes NaN 2013-01-01 NaN

The date check prevents calling a later observation “tomorrow” when days are missing. Any disagreement with the supplied target warrants investigating the dataset’s definitions and missing-value handling. This is an illustration only: we retain the supplied RainTomorrow for modeling and keep these demonstration columns out of the model data.

A previous observation is not always yesterday’s observation. We will construct yesterday’s measurement by matching the exact date and location. We do this before removing missing targets: a row without a target can still contain an observed measurement useful for the next day’s prediction.

yesterday = rain[["Location", "Date", "Rainfall", "Humidity3pm"]].copy()
yesterday["Date"] = yesterday["Date"] + pd.Timedelta(1, unit="D")
yesterday = yesterday.rename(columns={
    "Rainfall": "Rainfall_lag1day", "Humidity3pm": "Humidity3pm_lag1day"
})
rain = rain.merge(yesterday, on=["Location", "Date"], how="left", validate="one_to_one")
rain["MonthNumeric"] = rain["Date"].dt.month
rain["Month"] = rain["Date"].dt.month_name()
rain = rain.dropna(subset=["RainTomorrow"]).copy()
display(rain[["Location", "Date", "Rainfall", "Rainfall_lag1day"]].head(10))
Location Date Rainfall Rainfall_lag1day
0 Adelaide 2008-07-01 5.0 NaN
1 Adelaide 2008-07-02 0.8 5.0
2 Adelaide 2008-07-03 0.0 0.8
3 Adelaide 2008-07-04 0.0 0.0
5 Adelaide 2008-07-06 NaN 0.0
6 Adelaide 2008-07-07 16.2 NaN
7 Adelaide 2008-07-08 17.0 16.2
8 Adelaide 2008-07-09 1.8 17.0
9 Adelaide 2008-07-10 9.0 1.8
12 Adelaide 2008-07-13 NaN NaN

The merge uses only past measurements. If yesterday is missing, the lag remains missing; it does not silently substitute a measurement from several days ago. We will impute missing predictors inside each training fold.

Establish a holdout and validation folds

Use the first 80% of observed dates for development and the remaining dates for a final holdout. This adapts to the date range in the local CSV. How would ordinary TimeSeriesSplit behave if several rows share the same date?

Splitting rows can place different locations from the same date on opposite sides of a boundary. Instead, split unique dates, then map each date window back to rows. All locations on a date stay together. This evaluates future predictions at the locations represented in our data; it does not evaluate transfer to unseen locations.

Show chronological holdout and date-based validation folds
all_dates = np.sort(rain["Date"].unique())
cutoff = pd.Timestamp(all_dates[int(0.8 * len(all_dates)) - 1])
train = rain.loc[rain["Date"] <= cutoff].sort_values(["Date", "Location"]).reset_index(drop=True)
test = rain.loc[rain["Date"] > cutoff].sort_values(["Date", "Location"]).reset_index(drop=True)
# Apply the target-availability gap before constructing positional fold indices.
train = train.loc[train["Date"] < test["Date"].min() - pd.Timedelta(1, unit="D")].reset_index(drop=True)
assert not train.empty and not test.empty
y_train, y_test = train["RainTomorrow"], test["RainTomorrow"]
dates = np.sort(train["Date"].unique())
folds = []
for fit_dates, valid_dates in TimeSeriesSplit(n_splits=3).split(dates):
    fit_rows = np.flatnonzero(train["Date"].isin(dates[fit_dates]))
    valid_rows = np.flatnonzero(train["Date"].isin(dates[valid_dates]))
    # RainTomorrow for date d is not known until the following day.
    # Leave a day between the last training feature date and validation origin.
    first_validation_date = train.iloc[valid_rows]["Date"].min()
    fit_rows = fit_rows[(train.iloc[fit_rows]["Date"] < first_validation_date - pd.Timedelta(1, unit="D")).to_numpy()]
    assert len(fit_rows) > 0 and len(valid_rows) > 0
    assert train.iloc[fit_rows]["Date"].max() < first_validation_date - pd.Timedelta(1, unit="D")
    folds.append((fit_rows, valid_rows))
    print(train.iloc[fit_rows]["Date"].max().date(), "→", first_validation_date.date())
2009-09-18 → 2009-09-20
2011-09-04 → 2011-09-06
2013-09-18 → 2013-09-20

The extra gap conservatively allows the next day’s outcome to become available before fitting. The exact gap should reflect the observation and publication schedule in the real application.

Establish two baselines

A majority baseline always predicts the most frequent training class. A persistence baseline predicts tomorrow’s rain using today’s RainToday. If today’s value is missing, we use the most frequent training value.

For a numeric target, persistence means predicting the next value with the current value, then evaluating with a regression metric such as r2_score(y_next, y_current). Here we use classification metrics: accuracy and balanced accuracy. Balanced accuracy averages recall across the classes and helps reveal how a majority baseline performs on an imbalanced target.

class PersistenceClassifier(ClassifierMixin, BaseEstimator):
    """Predict tomorrow's class using today's observed class."""
    def fit(self, X, y):
        self.classes_ = np.unique(y)
        self.fill_value_ = X["RainToday"].mode().iloc[0]
        return self

    def predict(self, X):
        return X["RainToday"].fillna(self.fill_value_).to_numpy()

baselines = {
    "Majority baseline": DummyClassifier(strategy="most_frequent"),
    "Persistence baseline": PersistenceClassifier(),
}
results = {}
for name, model in baselines.items():
    results[name] = cross_val_score(
        model, train[["RainToday"]], y_train, cv=folds, scoring="balanced_accuracy")
display(pd.DataFrame(results, index=["Fold 1", "Fold 2", "Fold 3"]).T)
Fold 1 Fold 2 Fold 3
Majority baseline 0.500000 0.500000 0.500000
Persistence baseline 0.658726 0.656555 0.645534

Compare calendar encodings and historical features

Keep the classifier and validation folds fixed while changing the features:

  1. Current measurements only.
  2. Current measurements plus numeric month.
  3. Current measurements plus one-hot month.
  4. Current measurements plus one-hot month and yesterday’s measurements.

For logistic regression, numeric month contributes a linear term to the log odds: moving from January to February has the same modeled increment as moving from November to December. It also fails to represent December and January as neighbors in a seasonal cycle. One-hot encoding lets each month have a separate effect. The same limitation applies to numeric time of day in a linear regression model. Sine/cosine encoding is another possible approach, beyond this comparison.

The ColumnTransformer below selects predictors explicitly. The target and any other columns are excluded; in particular, if the local CSV includes RISK_MM (next-day rainfall), it must never be a predictor.

numeric = [
    "MinTemp", "MaxTemp", "Rainfall", "Evaporation", "Sunshine",
    "WindGustSpeed", "WindSpeed9am", "WindSpeed3pm", "Humidity9am",
    "Humidity3pm", "Pressure9am", "Pressure3pm", "Cloud9am", "Cloud3pm",
    "Temp9am", "Temp3pm",
]
categorical = ["Location", "WindGustDir", "WindDir9am", "WindDir3pm", "RainToday"]

def make_rain_model(extra_numeric=(), extra_categorical=()):
    preprocessing = ColumnTransformer([
        ("numeric", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
         numeric + list(extra_numeric)),
        ("categorical", make_pipeline(
            SimpleImputer(strategy="constant", fill_value="missing"),
            OneHotEncoder(handle_unknown="ignore")),
         categorical + list(extra_categorical)),
    ])
    return make_pipeline(preprocessing, LogisticRegression(max_iter=1000))

models = {
    **baselines,
    "Measurements": make_rain_model(),
    "Measurements + numeric month": make_rain_model(extra_numeric=["MonthNumeric"]),
    "Measurements + month": make_rain_model(extra_categorical=["Month"]),
    "Measurements + month + lags": make_rain_model(
        extra_numeric=["Rainfall_lag1day", "Humidity3pm_lag1day"],
        extra_categorical=["Month"]),
}
for name, model in models.items():
    if name in baselines:
        continue
    X = train
    results[name] = cross_val_score(
        model, X, y_train, cv=folds, scoring="balanced_accuracy"
    )
validation = pd.DataFrame(results, index=["Fold 1", "Fold 2", "Fold 3"]).T
validation["Mean"] = validation.mean(axis=1)
display(validation)
Fold 1 Fold 2 Fold 3 Mean
Majority baseline 0.500000 0.500000 0.500000 0.500000
Persistence baseline 0.658726 0.656555 0.645534 0.653605
Measurements 0.735711 0.724348 0.726031 0.728696
Measurements + numeric month 0.740709 0.724609 0.727704 0.731007
Measurements + month 0.740814 0.725420 0.727878 0.731371
Measurements + month + lags 0.742189 0.726692 0.730206 0.733029

Interpret the feature comparisons

Month is known in advance and may capture seasonal differences. We encode it categorically rather than imposing a linear increase from January to December. Location lets one model use data across stations, although this additive logistic model does not automatically learn location-specific seasonal effects.

Lag features provide yesterday’s measurements, while today’s rainfall and humidity are already present. The lags may add little once current measurements are included. Their usefulness is an empirical question, not a guarantee.

NotePause and discuss
  • Do the feature additions improve every validation fold, or only the average?
  • Would yesterday’s observed humidity remain available if we forecast an entire month in advance?
  • Why would grouping by location before shift(1) still be insufficient to guarantee a one-day lag?

Grouping prevents crossing locations, but only a date check or an exact date match establishes the elapsed interval. Observed future-period measurements are available in this repeated one-day setup, not for a whole month forecast at once.

History at the train/test boundary

We created historical predictors before splitting. That lets the first test date use an earlier observed measurement from the training period. It also lets later test dates use measurements that have arrived since the test period began, consistent with our repeated one-day prediction task.

Creating lags separately within train and test would discard available history at the boundary. Using future measurements would leak information. Imputation, scaling, and model fitting remain inside the pipeline and use only each fold’s training rows.

Evaluate the selected approach

Select using validation balanced accuracy, then inspect the final holdout once. Small validation differences may be unstable; simplicity and consistency across periods matter too.

best_name = validation["Mean"].idxmax()
selected = models[best_name]
X_train = train[["RainToday"]] if best_name in baselines else train
X_test = test[["RainToday"]] if best_name in baselines else test
selected.fit(X_train, y_train)
predictions = selected.predict(X_test)
print("Selected:", best_name)
print(f"Holdout accuracy: {accuracy_score(y_test, predictions):.3f}")
print(f"Holdout balanced accuracy: {balanced_accuracy_score(y_test, predictions):.3f}")
Selected: Measurements + month + lags
Holdout accuracy: 0.847
Holdout balanced accuracy: 0.712

This estimate describes future dates at the observed locations under our information-availability assumptions. A different forecast horizon, a new location, or a change in measurement practices would require a different evaluation design.

The main adaptations were to define the prediction timing, split by dates, account for target availability, and match lag measurements within location by elapsed time. The classification pipeline itself remained familiar.

Transfer this workflow to HW8

Before modeling a new time-series dataset, explain:

  • Series: Which column or combination of columns identifies one sequence? Can geographic labels overlap?
  • Spacing: Are dates unique and equally spaced within each sequence? What does one row shift mean?
  • Task: What is the forecast horizon, how is the future target constructed, and which measurements are available when predicting?
  • Baseline: What does “the next value equals the current value” predict? Which metric fits the target type?
  • Features: How will you compare date encodings and past measurements using the same evaluation periods?
  • Evaluation: Do training dates precede validation dates, are training targets available at fitting time, and is the final holdout reserved for the selected approach?

A useful feature need not improve every dataset. Report the comparisons and justify the choices using evidence.