Train and test splits for temporal data
Today let's understand train and test splits for temporal data, using simple and practical examples.
Here is the running example for the whole lesson: quarterly beer production in Australia, from 1992 Q1 to 2010 Q2, in megalitres (a megalitre is a million litres). That's 74 quarters, published by the Australian Bureau of Statistics.
Look at the line. To check how good a forecasting model actually is, you need to hold some quarters back and compare the model's forecast against them, the same way you would hold back rows to test any other model. So here's the question this lesson answers: can you just grab any random 20 to 30% of these 74 quarters and call it the test set, the way you would with a table of unrelated rows? Or does the fact that this data moves through time change the rule?
What an ordinary train/test split assumes about your rows
Before getting to the beer series, it helps to see the ordinary rule first, the one you would use on a table of unrelated rows like customers or transactions, where the order of the rows means nothing at all.
A plain train/test split usually sets aside a random slice of the rows for testing and trains the model on the rest. The reason a random subset is fine there comes down to one specific assumption: every row is exchangeable with every other row. Shuffle the order of a customer table and nothing about it changes, so any random 30% you pick is just as representative of the whole table as any other random 30% would be.
The widget below is not the beer series. It's 200 made-up, unrelated rows, split into 60% train, 20% validation and 20% test, purely by row position, picked at random.
The coloured strip splits those 200 rows by role. Underneath it, the runnable R code shows the same idea in its simplest two-way form: idx <- sample(n, 0.7 * n) picks 70% of the row positions at random for training, and the rest becomes test. Flip the leak checkbox and watch what happens to the test accuracy: it jumps from an honest 0.78 to a suspicious 0.99, because a column that was secretly built from the answer snuck into training. That is a different kind of mistake from the one this lesson is about, but it shares the same root: touching or including information you would not really have at prediction time is what breaks a test set's honesty, whether that information leaks in through a planted column or through the order of the dates.
So remember, none of this used the beer series. But the same sample() idea is exactly what you would reach for by habit on the beer series too: pick 70% of the 74 quarters at random for training, and use the rest to test. The next step does precisely that, and shows you why it goes wrong.