Concepts / Train and Test Splits for Time-Based Data

Train and Test Splits for Time-Based Data

Predictions on the training data look good, which is typical for random forests.

  • Programming

A Forecast That Looks Right Until Tested

Imagine you want to predict how many bicycles a rental service will rent out on any given day. You have a history of daily rental counts, and you want a model that can predict counts for days it has not seen. To judge the model fairly, the first 184 days go into the training set and the remaining days form the test set. The model is then scored on time periods it never learned from.

A random forest regressor looks like an excellent first choice. Random forests need very little preprocessing, so a raw feature can be fed in with almost no preparation. The feature in this setup is POSIX time, a single number that counts the time elapsed since a fixed reference moment. Because the model accepts it directly, the whole setup looks reasonable on paper.

The surprise comes when you check the results. Predictions on the training data look good, which is typical for random forests. Predictions on the test data do not follow the real rentals at all. The fix is not to tune the forest. The fix is to rethink the feature.

What do you think happens?

POSIX time always increases. If the model was fitted on earlier timestamps, what do you think it predicts for timestamps later than every training value?

  • It keeps extending the upward trend it learned

  • It reuses the target of the closest training point, which is the last observed moment

  • It predicts zero because the timestamps are unseen

Reveal answer
Answer:

It reuses the target of the closest training point, which is the last observed moment.

A tree cannot build a prediction from patterns in a region of feature space that it never saw during training. The forest falls back on training values, so later timestamps get the target of the nearest training point instead of a continued upward trend.

Where the Test Days Sit in Time

Before explaining the forest's behavior, trace what the feature values look like on each side of the split. A chronological split puts the training days first and the test days after them. Nothing is shuffled, so every test timestamp is later than every training timestamp.

Training daysfirst 184 daysLast trainingtimestampmaximum feature value seenTest daysall later daysearlier in timesplit point
Where does the test data sit in time relative to the training data, and why does that put some test feature values outside the training range?

Now the mismatch is visible. The POSIX time values for the test period lie above the largest value the model ever saw. The question is what the model does with a value that sits outside its experience. Follow the feature values step by step through the fit and the prediction, and note the point where the test inputs leave the range the model has seen. That boundary is where predictions stop tracking reality.

Why a Forest Cannot Extrapolate

A random forest makes its prediction by asking each of its trees for an output and then averaging those outputs. Each tree sends an input down to a leaf, and that leaf holds a target value learned from training points. A leaf can only hold values that came from the training data, so the forest cannot output anything beyond the training targets it has actually stored.

Test POSIX timeabove training maximumNearest trainingregioneach treeStored trainingtargetleaf valueAverage of treeoutputsFlat predictionstops risingrouted to closest datareturnscombinedoutput
When a test input falls above the maximum training value, what does each tree output, and why does the forest's prediction stop rising?

Because no leaf holds a value from beyond the training range, every tree that receives a test timestamp above the maximum falls back to values from the end of the training period. Averaging those outputs gives a prediction that stays near the last observed level. This is why the predicted line flattens while the real test curve keeps moving. The forest is not broken. It is doing exactly what its training data allows.

Reading the Negative R-Squared

The regressor's score method reports the coefficient of determination, written $R^{2}$, on whatever data you pass in. Here the call is made on the test set, so the value describes how well the fitted model explains the test targets. A positive value means the model captures some of the variation in those targets. A negative value means the model did worse than the simple baseline of always predicting the mean of the test targets. In that case the model has learned nothing useful.

Model predictionserror on test targetsAlways predict testmeanerror on test targetsNegative R^2 model worse than baselinecompared againstreference
How does the model's test error compare with the error of always predicting the test mean, and why does a negative R2 mean the model adds no value?

A near-zero negative value is not a small disappointment to shrug off. It is a diagnostic signal. Pair the number with a plot of predictions. If the predicted line is flat while the test curve varies, the plot tells the same story as the number, and it also points to the cause. The clue is in the feature, not in the number of trees. Adding trees or adjusting settings will not fix a feature whose test values fall outside the training range.

What you observeWhat it meansWhere to look next
Positive test-set $R^{2}$The model explains some of the variation in the test targetsCheck whether the gain holds across the test period
Negative test-set $R^{2}$The model did worse than always predicting the mean, so it learned nothing usefulExamine the features and how their test values relate to the training range
Flat predicted line against a varying test curveThe model is not responding to the changes in the test inputsLook at the feature, not the number of trees

Reading the test-set score together with the prediction plot

Replacing the Timestamp with Domain Features

Once the cause is clear, the remedy comes from domain knowledge. Looking at the rental figures in the training data, two factors appear to matter a great deal: the time of day and the day of the week. Rentals rise and fall with the hour, and they follow a weekly rhythm. Both patterns repeat. A repeating feature has values that recur inside the training range, so the forest can learn from them and apply the learned pattern to test days.

POSIX timealways increasingTest values outsidetraining rangeHour of dayrepeats every dayDay of weekrepeats every weekTest values seen intraining
How does a raw timestamp that keeps increasing differ from hour-of-day and day-of-week features that repeat, and which new times map onto values the model has already seen?
Worked example

Mapping new timestamps onto repeating features

Suppose training covered several weeks of daily data. A test day falls after the last training day. Its POSIX time is larger than any training value. Which feature values can the model use, and what do they look like?

  1. 1
    Check the raw timestamp

    The POSIX time for the test day is larger than every training value, so the forest has no leaf that covers it.

  2. 2
    Extract the hour of day

    A test timestamp at 9 in the morning gives the hour value 9. The training data already contains many days with an hour value of 9, so the forest has learned from this value.

  3. 3
    Extract the day of the week

    If the test day is a Tuesday, its weekday value matches the Tuesdays in the training data. The forest has seen that value many times before.

  4. 4
    Decide what to keep

    Keep the hour and weekday features, which recur inside the training range. Drop POSIX time, whose test values never occur in the training period.

Result

The model now receives inputs it has already learned from, so it can apply the learned hourly and weekly patterns to the new days.

The plan has two parts. First, add the new features. Second, drop POSIX time, because in this setting it cannot teach the model anything useful. Starting with the hour of the day alone already changes the picture. The predictions now take on the same pattern for each day of the week instead of a flat line, because the model responds to a feature whose values the test set shares.

Mistakes That Hide the Extrapolation Problem

  • Common mistake

    Assuming a rising feature will keep rising in predictions

    What it looks like

    A model trained on earlier POSIX timestamps is expected to extend its upward trend to later dates.

    Why it fails

    A random forest only outputs training targets it has stored, so it cannot extend a trend beyond the training range.

    Do this instead

    Check whether the test feature values fall inside the training range before expecting any extension of a trend.

  • Common mistake

    Tuning the forest when the feature is the problem

    What it looks like

    Changing the number of trees after a negative test-set $R^{2}$ and expecting the score to turn positive.

    Why it fails

    The divergence sits at the boundary between training and test feature values, so better forest settings cannot recover values it never saw.

    Do this instead

    Rethink the feature first, for example by replacing a raw timestamp with time of day and day of the week.

  • Common mistake

    Trusting the training predictions

    What it looks like

    Seeing good predictions on the training data and concluding the model is ready.

    Why it fails

    Random forests usually fit training data well, so training predictions do not reveal a failure on unseen feature ranges.

    Do this instead

    Evaluate on a held-out test period and inspect the predicted line against the real test curve.

  • Common mistake

    Reading a negative R-squared as a small error

Checking Your Understanding of the Split

MEDIUM

A colleague trains a random forest regressor on daily sales from the first half of a year, using the raw timestamp as the only feature. The test set is the second half of the year. The test-set $R^{2}$ is negative, and the predicted line is flat while the real sales vary. Explain which feature is the likely cause, why the forest cannot predict test values above the training range, and which features you would propose instead.

Hints
  • Ask what range of raw timestamp values the model saw during training.
  • Consider whether the test timestamps fall inside or outside that range.
  • Think about which calendar features repeat across the year.

Key Takeaways

  • A chronological split places every test timestamp after the training period, so test feature values can fall outside the range the model has seen.
  • A random forest regressor cannot extrapolate. For feature values beyond the training range it predicts the target of the closest training point, which produces a flat prediction.
  • A negative test-set $R^{2}$ means the model did worse than always predicting the mean, so it learned nothing useful. Read it alongside the prediction plot to find the cause.
  • Domain features such as hour of day and day of week repeat inside the training range, and dropping a raw feature like POSIX time can improve the model.

Related concepts

More concepts starting with T