Concepts / Feature Engineering with Domain Knowledge

Feature Engineering with Domain Knowledge

A random forest regressor is easy to use because it needs little preprocessing, but ease of use does not guarantee it can predict new feature ranges.

  • Programming

A Model That Looks Ready to Ship

A random forest regressor is one of the easiest models to reach for. It needs very little preprocessing, so a raw feature can often be fed in without much preparation. That ease of use is appealing, but it does not guarantee that the model can predict feature values it has never seen. This article uses a bicycle rental example to show how a model can look sound on paper and still fail on new data, and why the fix lies in the feature rather than in the forest's settings.

What do you think happens?

Suppose a model was trained on POSIX time values that were steadily increasing with the rental counts. When you give it later POSIX time values it never saw, what do you expect its predictions to do?

  • Keep rising in step with the trend

  • Stay flat at a value taken from the training data

  • Drop to zero because the values are unfamiliar

Reveal answer
Answer:

The predictions stay flat at a value taken from the training data.

Trees and random forests cannot extrapolate. For feature values beyond the training range, the forest predicts the target of the closest training point, which here is the last observed moment in the training data.

Setting Up the Rental Problem

Imagine predicting 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. The first 184 days go into the training set, and the remaining days form the test set. The model is therefore judged on time periods it never learned from, which is exactly the situation that makes the feature's range important.

The first feature used is POSIX time, a single number that counts the time elapsed since a fixed reference moment. Because it is a plain number, the random forest accepts it directly, and the setup looks reasonable. On the training data the predictions look good, which is typical for random forests. The surprise appears when the test predictions are checked against the real rentals.

Why the Forest Stops Following the Trend

Many learners assume that a model trained on a rising trend will keep rising when asked about later dates. POSIX time always increases, so it seems natural that a model fitted on earlier timestamps should extend the pattern forward. This belief is wrong for tree-based models, and the reason is specific to how they handle feature values.

The timestamps in the test set are later than every timestamp in the training set. When the forest receives one of those values, it has no training examples in that region of feature space to draw on. It cannot build a prediction from the patterns it learned. Instead, it reuses the target value of whichever training point sits closest, and in this case that is the last moment of observed data. The prediction therefore stops rising at the boundary of the training range.

Tracks rentals intraining periodRising and falling intraining periodFlat beyond thetraining rangeVarying repeatingpattern in testperiod
When test POSIX time values lie beyond every training value, what does the forest predict compared with the actual rental pattern?

The divergence is located at the boundary between training and test feature values. The training predictions are not where the problem lies. Following the fit and evaluation step by step, the point where the test inputs leave the range the model has actually seen is the point where its predictions stop tracking reality.

Reading a Negative R-squared Score

The regressor's score method reports the coefficient of determination, written $R^{2}$, on whatever data you pass in. In this setup 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 the target. A negative value means the model did worse than a simple baseline that always predicts the mean of the target. The source summarizes this as the model having learned nothing useful.

A near-zero negative $R^{2}$, like the value in the rental example, is therefore a diagnostic signal rather than a small disappointment. Read it alongside a plot of predictions. A flat predicted line against a varying test curve tells the same story as the number. It also points to the cause: the feature, not the number of trees.

Choosing Features That Repeat

Once the cause is clear, the remedy is to bring in 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 with the weekly rhythm, and both of those 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.

This is the key contrast. A raw timestamp keeps producing new values, while a time-of-day feature cycles through the same values again and again. Hour 9 on a test day is the same hour 9 the model saw during training, so the forest has something it can actually use. Day of the week works the same way: Monday in the test period matches Monday in the training period.

Worked example

Measuring Distance Between Hours

How far apart are hour 23 and hour 0 when hours are stored as plain numbers, and how far apart are they on a 24-hour cycle?

  1. 1
    Raw numeric difference

    Subtract the two stored numbers: 23 minus 0 gives 23. Taken as plain integers, the two hours look 23 units apart.

  2. 2
    Cycle difference

    On a 24-hour clock, hour 0 comes right after hour 23 at midnight. Going forward from 23 to 0 takes 1 step, so the two hours are adjacent.

  3. 3
    What the forest sees

    If the feature is the raw hour number, the forest treats late evening and midnight as far apart, even though rentals at those times are similar. A feature that captures the cycle keeps them close.

Result

The raw difference is 23 but the cycle difference is 1, so a plain hour number misrepresents how close the two times are.

Hour 22late eveningHour 23late eveningHour 0midnightHour 1after midnightnext hourwraps past midnightnext hour
Why is hour 23 numerically far from hour 0 in a raw count, yet adjacent on a 24-hour cycle?

From Raw Records to the Forest

The plan has two parts. First, add the new domain features. Second, drop POSIX time, because it cannot teach the model anything useful in this setting: its values for the test period never occur in the training period. The source begins with only the hour of the day. With that feature alone, the predictions take on the same pattern for each day of the week. This is an improvement over the flat line, because the model now responds to a feature whose values the test set shares.

Raw rental recordsExtract hour of dayExtract day of weekDrop POSIX timeRandom forestregressorPredictions on testdays
How does raw rental data flow through domain-driven feature construction before it reaches the random forest?

Notice that the forest itself does not change. The model settings stay the same, and only the representation of time changes. This is the core lesson of the topic: when a model fails to generalize, examine what each feature lets it learn before adjusting the algorithm.

Common Mistakes With Time Features

  • Common mistake

    Trusting a good training score as proof that the model works

    What it looks like

    The forest's predictions on the training days look accurate, so the model is assumed ready.

    Why it fails

    Random forests usually fit their training data well. That fit says nothing about how the model handles feature values outside that data.

    Do this instead

    Always evaluate on a test set whose feature values come from a period the model has not seen, and check the test score.

  • Common mistake

    Assuming a rising feature will produce a rising prediction

    What it looks like

    POSIX time increases every day, so the team expects the forecast to keep climbing into the test period.

    Why it fails

    Trees cannot extrapolate. Beyond the training range, the forest reuses the target of the closest training point.

    Do this instead

    Use features whose values recur inside the training range, such as hour of day or day of the week.

  • Common mistake

    Tuning the forest when the feature is the problem

    What it looks like

    The team adds more trees and changes depth, but the negative test R^2 barely moves.

    Why it fails

    A negative score with a flat prediction line points to the feature. Changing the model settings does not give it values it has never learned from.

    Do this instead

    Rethink the feature first, then adjust the model if needed.

  • Common mistake

    Keeping a timestamp-based feature alongside new domain features after it has been shown to be useless

Practice Choosing the Right Features

MEDIUM

A colleague is forecasting hourly electricity demand for a city. The raw data includes a timestamp, and the model uses POSIX time as its only feature. The test set covers dates after the training period. Explain whether the forest can predict the test period well with POSIX time alone, and propose two domain features that would give the forest values it has seen before.

Hints
  • Ask whether the test-period POSIX values occur anywhere in the training period.
  • Think about which parts of a timestamp repeat, such as the hour or the day of the week.
  • A good answer names the features and explains why each recurs inside the training range.
EASY

Your model's test-set score is negative. Before changing any hyperparameters, what plot would you draw, and what pattern would tell you the feature is the problem?

Hints
  • Compare predicted values against the actual test values over time.
  • A flat predicted line next to a varying actual curve is the pattern to look for.

Takeaways for Choosing Features

  1. 1
    A random forest regressor needs little preprocessing, but it cannot predict feature values outside its training range; beyond that range it reuses the target of the closest training point.
  2. 2
    A negative test-set R2 means the model did worse than predicting the mean and learned nothing useful, and a flat prediction line against a varying test curve points to the feature.
  3. 3
    Domain features such as hour of day and day of the week recur inside the training range, so the forest can learn their patterns and apply them to test days.
  4. 4
    Dropping a feature like POSIX time whose test values never occur in training can improve the model, and the fix is to rethink the feature rather than tune the forest.

At a glance

  • A random forest regressor cannot extrapolate: for feature values beyond the training range it predicts the target of the closest training point.
  • A negative test-set R2 signals that the model did worse than predicting the mean, and a flat prediction line points to the feature rather than the model settings.
  • Domain features such as time of day and day of the week have values that repeat inside the training range, so the forest can learn and apply their patterns.
  • Dropping a feature like POSIX time whose test values never appear in training can improve the model, so rethink the feature before tuning the forest.

Related concepts

More concepts starting with F