Concepts / Train and Test Splits for Regression

Train and Test Splits for Regression

When you begin a regression problem, a random forest is a natural first choice.

  • Programming

Starting With an Easy Model

When you begin a regression problem, a random forest is a natural first choice. Random forests require very little preprocessing of the data, so you can often hand over raw feature values and get a model that makes sensible predictions without much tuning. That convenience is real, but it hides an assumption: that a model which is easy to set up will also be reliable on new data. This article tests that assumption.

What do you think happens?

Suppose you train a random forest on a time-based feature covering timestamps from earlier in a dataset. You then predict targets for a test set whose timestamps all fall after the last training timestamp. If the model had learned a smooth trend over time, what should the test predictions look like?

  • A line that keeps rising along with the timestamps

  • A flat, constant line

  • Random scatter centered on zero

Reveal answer
Answer:

A flat, constant line. The test-set predictions form a constant line rather than continuing the trend.

The source describes this exact case: strong training-set predictions, but test-set predictions that form a constant line, with a test R2 of -0.03. The reason is covered in the sections below.

The misconception to watch for is that a random forest can extrapolate to feature ranges it never saw during training. The source material shows why that belief fails, and it also shows how a second model can serve as a comparison point, so that you judge the first model's behavior rather than trusting it. The goal of this article is to teach you where to look when a split-based evaluation goes wrong.

Where the Rows Go in a Split

A train and test split divides the dataset into two disjoint parts before any fitting happens. The training subset is the part the model is fitted on. The held-out subset is kept aside and used only for evaluation. Every row lands in exactly one of the two groups, so the test rows are unseen by the model during training. Follow the flow in the diagram below to see what happens at each step.

Full datasetall rowsTrain/test splitrows divided before fittingTraining subsetused for fittingFitted modellearned from training rowsonlyHeld-out subsetused for evaluationTest-set resultsread directlypartitionrowsrowsfitevaluatepredict on held-out rows
What happens to the rows at each step, from the full dataset to the training subset used for fitting and the held-out subset used for evaluation?

The key point of the partition is that the test rows play no part in fitting. Their only role is to measure how the fitted model behaves on data it has not seen. Keeping that role clean is what makes the test-set result informative.

Why Training Accuracy Misleads

The source describes two results that look contradictory at first. The predictions on the training set are quite good, which is typical for random forests. The predictions on the test set, however, form a constant line, and the R2 on the test set is -0.03. A model can fit its own training data closely while failing completely on unseen data. The training result tells you the forest memorized its training rows well; it does not tell you that the forest will generalize.

Predictions tracktargetsclose fit to seen rowsLow erroron rows the model was builtfromConstant-linepredictionsrows outside training rangeR2 of -0.03little useful signallearned
How can the same model show a near-perfect fit on training points but a large error on held-out test points, and where does the gap between the two come from?

The gap between the two columns does not come from careless training. The source states the cause directly: the failure was caused by the combination of the feature and the model, and the test timestamps lie outside the range of the training timestamps. To find that cause, you have to look at the feature values of the test rows, not only at the score.

How a Tree Routes an Input

A random forest is built from many decision trees, and each tree makes a prediction by routing an input to a region that was populated during training. A row enters at the top of the tree, and each split decision sends it down one branch until it reaches a leaf. The leaf's value is what the tree contributes to the prediction. The forest combines the outputs of its trees to produce a single prediction.

This routing works only when there is a trained region to send the input to. When a feature value lands inside the range of training values, the tree has a region to route through. When the value falls outside that range, there is no trained region that covers it, and the tree cannot invent a value for it. That is the mechanism behind the failure described above.

Why Forests Cannot Extrapolate

Trees, and therefore random forests, cannot extrapolate to feature ranges outside the training set. For a feature value beyond the training range, the model predicts the target of the closest training point. The output is simply inherited from the boundary of the training data, which is why a flat line appears where you might have expected a trend to continue. Follow the chain of reasoning in the diagram below; the key change happens at the moment the test value leaves the training range.

Test timestampa feature value from thetest setInside trainingrange?compared with trainingvaluesPopulated leafa trained region to routethroughLeaf target valuea value learned fromtrainingNearest trainingboundaryno trained region covers itBoundary target valueinherited, not extrapolatedcheckyespredictnopredict
For a given input row, which split decisions route it to a leaf, and at which step does the predicted value stop matching what I expected?

The divergence therefore sits at the first decision. Everything below that check is ordinary tree routing. Once the value falls outside the training range, the path leads to the boundary, and the prediction stops responding to the input in the way a trend would require.

python
Walk through it
  1. 1
    Build a training matrix with the feature values 0 through 9.
  2. 2
    Set the target to a clear upward trend, so a learner that extrapolates would be expected to keep climbing.
  3. 3
    Fit a forest with 100 trees and a fixed random state.
  4. 4
    Ask for predictions at feature values beyond anything seen in training.
  5. 5
    Each tree can only return a value built from training targets, so the forest's predictions cannot rise above 18; they stay bounded by the training range rather than following the trend to 40, 60, or 80.
Notes on the code
  • The training feature runs from 0 to 9 and the target is twice the feature, so the target's largest training value is 18.
  • random_state=0 makes the forest reproducible, as in the source's comparison.
  • The inputs 20, 30, and 40 lie outside the training range.

Reading an R2 Near Zero

The R2 score summarizes how well a model's predictions match the targets, compared with a simple baseline. The baseline is a model that always predicts the mean of the target. A model with an R2 near 0 has done about as well as that baseline, which means it has learned little useful signal. A negative R2 means the model does worse than always predicting the mean. The source's test-set value of -0.03 is in this range, and the source reads it as evidence that the model learned nothing.

Test-set R2Meaning relative to the mean baselineWhat to check next
Well above 0The model explains variation in the target that the mean does notConfirm the test rows resemble the training rows
Near 0Little better than always predicting the mean; little useful signalCheck feature ranges of the test rows against training
Below 0Worse than always predicting the meanTreat the model as not yet usable; trace the failing rows

Reading R2 on a held-out test set

Separating the Model From the Features

The source runs the same evaluation helper, eval_on_features, twice. The helper takes a feature matrix, a target, and a model. In the first call, the feature is the POSIX time and the model is a RandomForestRegressor with n_estimators set to 100 and random_state set to 0. In the second call, the source changes two things at once: it uses a LinearRegression model, imported from the linear model module, and passes different input features, namely day of week and hour of day. Linear regression here is a comparison point, not a claim that one model is always better.

Worked example

Diagnosing the forest's comparison result

A random forest trained on POSIX time gives a flat test-set prediction and a test R2 of -0.03. A linear regression trained on day of week and hour of day is compared on the same evaluation helper. Decide where the trouble lies.

  1. 1
    Trace the test values first

    Compare the test timestamps with the range of the training timestamps. The source states the test timestamps all lie after the last training timestamp.

  2. 2
    Locate the divergence

    The divergence sits in the test-set predictions, not the training-set predictions. The forest's training fit was good, so the failure appears only when inputs leave the trained range.

  3. 3
    Account for the changed features

    The comparison changes the model and the features together, so the difference cannot be credited to the model type alone.

  4. 4
    Read the comparison output directly

    Judge the linear regression by its own test-set results on day of week and hour of day, not by assuming its quality from the forest's result.

  5. 5
    Attribute the failure

    The forest's failure is a diagnosable event: the only feature was a time value that ran past the training data. The comparison shows whether the trouble lay with the forest, the feature, or both.

Result

The forest's failure is located in the out-of-range test timestamps. The comparison model provides a reference point, but its own held-out results must be read directly before any conclusion is drawn.

Mistakes When Reading Split Results

  • Common mistake

    Judging a model by its training-set predictions

    What it looks like

    A forest's training predictions track the targets closely, so the model is assumed to be ready.

    Why it fails

    Training predictions are made on rows the model was built from. They do not show how the model behaves on unseen rows.

    Do this instead

    Evaluate on the held-out subset and read those test-set results directly.

  • Common mistake

    Assuming a forest extrapolates a trend

    What it looks like

    Training timestamps run up to a certain date, and the test timestamps fall later. The forest is expected to keep rising.

    Why it fails

    A tree can only route an input to a trained region. Values outside the training range are inherited from the nearest training boundary.

    Do this instead

    Compare test feature values with the training range before trusting predictions for out-of-range inputs.

  • Common mistake

    Treating a near-zero R2 as a minor flaw

    What it looks like

    A test R2 of -0.03 is read as a slightly imperfect model.

    Why it fails

    An R2 near zero or below zero means the model has learned little useful signal relative to predicting the mean.

    Do this instead

    Read near-zero and negative R2 as evidence that the model needs diagnosis, not tuning alone.

  • Common mistake

    Attributing a comparison difference to one cause

    What it looks like

    A linear regression beats a forest, so linear regression is declared the better model.

    Why it fails

    If the model and the features both changed, the difference cannot be credited to the model type alone.

    Do this instead

    Hold the features fixed when you want to isolate the model, or hold the model fixed to isolate the features.

  • Common mistake

    Skipping the check of test feature ranges before reading predictions

Practice: Tracing an Out-of-Range Row

MEDIUM

A forest is trained on timestamps from January through June. A test row has a timestamp in August, and the forest predicts a value that equals the prediction for the June boundary. Trace the routing: at which decision does the prediction stop following the input, and what should you check before judging the model?

Hints
  • Start with the test timestamp and ask whether it lies inside the training range.
  • Recall what happens when no trained region covers the input.
  • The source's guidance is to trace the test values against the training range first.

Summary of the Split Lesson

A forest's good training fit and poor test fit can coexist, and the divergence is usually located in the test-set feature values. Trace those values against the training range before judging the model.

At a glance

  • A train and test split partitions rows before fitting, so the held-out rows measure behavior on unseen data.
  • Trees and random forests cannot extrapolate: for feature values beyond the training range, the prediction inherits the target of the closest training boundary.
  • A strong training fit can coexist with a test R2 near zero or below zero, which indicates the model learned little useful signal.
  • When comparing models, separate the effect of the model from the effect of the features, and read test-set results directly.
  • Trace test feature values against the training range first, then judge the predictions.

Related concepts

More concepts starting with T