Concepts / Scaling Features for Linear Models

Scaling Features for Linear Models

Single-feature functions such as log and exp help linear models and neural networks by adjusting relative scales, while sin and cos suit periodic patterns; tree-based models are much less affected by these transformations.

  • Programming

A Score That Goes the Wrong Way

Imagine you have followed a familiar recipe for improving a model. You scale the original features, then add interaction and polynomial columns to the training data, and you expect every model to do better. Then you check the Random Forest and its test score has dropped slightly. Nothing crashed, and the arithmetic is not broken. The result simply disagrees with an expectation carried over from linear models.

This article uses that situation as a worked case. You will see how a controlled comparison isolates the effect of the features, how to read a small score change without over-reading it, and why a linear model and a tree-based model respond so differently to the same added columns. The article ends with the single-feature transformations (log, exp, and sin) that also appear in this chapter.

Tracing the Comparison Workflow

A side-by-side comparison has a fixed order of steps. First, a model is trained on the scaled original features. Second, the same kind of model is trained on a training set that has been expanded with interaction and polynomial columns. Each fitted model is then scored on the matching test set, and finally the two scores are compared. The diagram below traces that order and marks the step where the surprise first shows up.

Scaled originalfeaturesstarting arraysTrain withoutinteractionsoriginal columns onlyScore each model onits test setRandom Forest score dipsCompare the twoscoresdirection and sizeTrain withinteractionsexpanded columnsfitfitscorescorereport
In what order do the steps run, and at which step does the surprising Random Forest score first show up?

The unexpected number first appears at the scoring step, not at the training step. Both models were fitted without errors, and the scoring method is the same for both. The surprise becomes visible only when the two test scores are placed next to each other. That is why the comparison step should be read carefully: the question is which change produced the number, and whether it came from the model or from the features.

Keeping the Comparison Controlled

A comparison is informative only when a single thing changes. In this one, the training and test feature matrices are the only difference between the two runs. The model class, the number of trees, and the scoring method stay the same. If the score moves, the change can be attributed to the features, and the remaining question is how that particular model responds to those particular features.

python
Notes on the code
  • PolynomialFeatures with degree 2 adds squared terms and pairwise product columns, the same kind of expansion the source describes.
  • poly is fitted on the training data only and then applied to the test data, so no test information leaks into the transformation.
  • Each model is scored on the test matrix that matches its training matrix.

Reading Two Scores Correctly

The source makes a point that is easy to skip: a drop of a small size does not show that interaction features are harmful in general. It shows only that for this model, on this data, the extra columns did not help and slightly hurt. A fair report therefore states both the direction of the change and its size, and avoids turning one small difference into a sweeping conclusion.

Worked example

Reading a hypothetical pair of scores

Suppose a Random Forest scores 0.850 on its original test features and 0.845 after interaction columns are added. How should this result be reported?

  1. 1
    Identify the direction

    The score went down, from 0.850 to 0.845, so the direction of the change is negative.

  2. 2
    Measure the size

    The change is 0.005. That is small, so it should be described as a slight decrease rather than a failure of the method.

  3. 3
    Check what was controlled

    Only the feature matrices changed. The model class, number of trees, and scoring method were the same, so the change is attributable to the features.

  4. 4
    State the limit of the claim

    The result applies to this model on this data. It does not show that interaction features hurt Random Forests in general.

Result

Report: on this data, adding interaction columns lowered the Random Forest test score slightly (0.850 to 0.845). The change is small and specific to this comparison.

Why a Product Column Helps a Straight-Line Model

A linear model can only combine features additively. With two features, it can represent a contribution from $x_1$ and a separate contribution from $x_2$, and nothing else. It cannot express the idea that the effect of $x_1$ depends on the level of $x_2$. An interaction feature supplies that missing signal as a new column whose value is the product $x_1 x_2$. Once that column exists, the linear model has a new term it can weight, and the combined effect becomes available to it.

x1 termadditive contributionx1 termadditive contributionx2 termadditive contributionx2 termadditive contributionx1 times x2combined signal
How does adding a product column change the set of terms a straight-line model can use?

The diagram shows the change in the set of terms. Before the expansion, the model has two additive terms. After it, a third term exists that carries the product of the two features. The model's fitted line is still linear in its weights, but the new column lets it respond to a combined effect that the original columns could not express. This is why the source reports that interaction and polynomial features can give a linear model like Ridge a clear boost.

Ridge and Random Forest Respond Differently

The source states two facts that together explain the pattern. First, even without any added features, the Random Forest already beats Ridge on this data. Second, adding interactions and polynomial terms raises Ridge's performance, while the Random Forest's performance decreases slightly. The two models start from different positions and draw their decisions in different ways, so the same added columns can push their scores in opposite directions.

Ridgelinear combination ofcolumnsScore risesafter interaction columnsRandom Forestsplits on given columnsScore dips slightlyafter interaction columnsexpanded featuresexpanded features
Why does the same added feature raise the linear model's score while lowering the Random Forest's score?

The lesson is that a feature engineering step has no fixed effect. A Random Forest builds its splits from the features it is given, and the expanded set can make the same signal harder to use well on this data. A linear model, by contrast, gains a new kind of signal it could not use before. The same column is therefore useful to one model and neutral or slightly harmful to the other.

Single-Feature Transformations: log, exp, and sin

Squared and cubed features are one way to give a linear model curved behavior. A different group of tools applies one mathematical function to one feature at a time. The source names three: log, exp, and sin. Linear models and neural networks are closely tied to the scale and distribution of each feature, so when the relation between a feature and the target is nonlinear, that relation is hard for them to model, especially in regression. Transforming the single feature can make the pattern easier to capture.

The log and exp functions help by adjusting relative scales in the data, so that a linear model or neural network can capture the pattern more easily. The source points to the memory price data from Chapter 2 as an earlier application of this idea. The sin and cos functions suit data that encodes periodic patterns, such as repeating cycles over time, because they map a repeating pattern onto a smooth curve.

Why Tree Models Are Less Affected

Tree-based models depend only on the ordering of a feature's values. A split asks whether a value falls above or below a threshold, so a monotonic transformation that keeps the order intact produces the same partitions of the data. A linear model's fitted line, however, depends on the actual numeric spacing of the values, so the same transformation changes what the line looks like. This is the reason tree-based models are much less affected by how a feature is scaled or distributed.

Predicting the Effect Before Comparing

MEDIUM

You run the same comparison on a new dataset. Before you look at the scores, write down three things: which step you expect the surprise to appear at, whether you expect Ridge's score to rise or fall after the expansion, and what you would have to change in the comparison to attribute a score change to the features.

Hints
  • Compare the workflow order against the diagram: the surprise appears when the two test scores are read, not during training.
  • Ridge gained a new kind of signal from the product column, while the Random Forest must split on the expanded set.
  • The only thing that should differ between the two runs is the feature matrices.
MEDIUM

Explain, in two or three sentences, why a log transformation of a skewed feature could help a linear model even though it would leave a Random Forest's splits essentially unchanged.

Hints
  • Think about whether a log transform preserves the order of the values.
  • Think about whether a linear fit depends on the numeric spacing between values.

Mistakes When Comparing Feature Sets

  • Common mistake

    Assuming every added feature must improve every model

    What it looks like

    Expecting the Random Forest score to rise after interaction columns are added, then reading a small drop as a bug.

    Why it fails

    The effect of a feature depends on the model that consumes it. A linear model gains a new combined signal, while a Random Forest must split on the expanded set.

    Do this instead

    Treat the direction of a score change as an empirical result for that model and dataset.

  • Common mistake

    Over-reading a small score difference

    What it looks like

    Concluding that interaction features are harmful in general because one Random Forest score dipped slightly.

    Why it fails

    A drop of this size shows only that the extra columns did not help this model on this data.

    Do this instead

    Report both the direction and the size of the change, and limit the conclusion to the comparison that was run.

  • Common mistake

    Changing more than the features between runs

    What it looks like

    Using a different number of trees or a different scoring method for the expanded run.

    Why it fails

    Once several things change, a score movement can no longer be attributed to the features alone.

    Do this instead

    Keep the model class, the number of trees, and the scoring method identical, so only the feature matrices differ.

  • Common mistake

    Fitting the polynomial transform on the test data

    What it looks like

    Calling fit_transform on the test matrix instead of transform.

    Why it fails

    The transformation then uses information from the test set, which makes the comparison unfair.

    Do this instead

    Fit the transformer on training data only, then apply transform to the test data.

Key Takeaways

  • A controlled comparison changes only the feature matrices, so any score change can be attributed to the features; report its direction and size.
  • Interaction and polynomial features give a linear model like Ridge a new kind of signal, which can raise its score, while a Random Forest may see a slight decrease on the same added columns.
  • The unexpected score first appears at the scoring step of the comparison workflow, when the two test scores are read side by side.
  • Single-feature functions such as log and exp adjust relative scales to help linear models and neural networks, sin and cos suit periodic patterns, and tree-based models are much less affected by these transformations.

Related concepts

More concepts starting with S