Machine Learning Forecasting with modeltime

Today let's use machine learning models to forecast a time series, and check whether they really do better than a seasonal naive forecast and an ARIMA.

Say you plan capacity for an airline. You need the number of international passengers for each of the next 12 months, and you have 144 months of history behind you, from January 1949 to December 1960.

A machine learning model does not read a series directly. It learns from a table with one row per month, where one column is the value to predict and the other columns are the predictors. So the first job is to turn the series into that kind of table.

After that, we fit four models on the same rows and score all four on the same 12 months, in one accuracy table.

That is the whole flow, and we start at the first box.

The airline passengers series and what a model needs to learn from it

The series is the AirPassengers dataset that ships with base R. It holds the monthly totals of international airline passengers, in thousands, from January 1949 to December 1960.

We put it in a table with one row per month: the date and the passengers. Then we add up each year, pick out its busiest month, and draw the whole series.

Press Run.

RInteractive R
# Build the monthly passengers series, then total and peak it by year library(dplyr) library(ggplot2) air <- tibble( date = seq(as.Date("1949-01-01"), by = "month", length.out = 144), passengers = as.numeric(AirPassengers) ) dim(air) #> [1] 144 2 yearly <- air |> mutate(year = format(date, "%Y")) |> group_by(year) |> summarise(total = sum(passengers), peak = max(passengers)) as.data.frame(yearly[c(1, 12), ]) #> year total peak #> 1 1949 1520 148 #> 2 1960 5714 622 ggplot(air, aes(date, passengers)) + geom_line(color = "#1f7a55") + labs(x = NULL, y = "Passengers (thousands)")

  

There are 144 rows. In 1949 the airline carried 1,520 thousand passengers, and its busiest month had 148 thousand. In 1960 it carried 5,714 thousand, and its busiest month had 622 thousand.

The chart shows the same thing. The level of the series rises every year, and the peak in the middle of each year rises with it.

Now think about what a machine learning model needs. It learns a mapping from predictor columns to one target column, and here the target is passengers. But this table has no predictors. A date is a single number that keeps growing, and it says nothing about what passengers were a year ago or which time of the year the row belongs to.

So we derive the predictors from the series itself.