Concepts / Feature Scaling and Normalization

Feature Scaling and Normalization

Linear models can struggle with skewed features that have many small values and a few very large ones, and transforming such features often improves the fit.

  • Programming

A Model That Struggles With One Column

Many real datasets contain a column whose values are mostly small, with a handful of extremely large values sitting far to the right. Counts, prices, and durations often look like this. Such a column can carry useful information about the target, yet a linear model can still struggle with it.

Before reading on, make a prediction. Suppose you fit a ridge regression on these raw columns. Will the fit be good, or will the very large values get in the way? The fastest way to answer is to run the model on the raw data and look at the score on the test set. The rest of this article explains what you are likely to see and why, and how a transformation can change the result.

Why a Few Huge Values Hurt

A linear model fits a straight-line relationship between each feature and the target. When a few values are enormous, they dominate the fit. The many small values are squeezed into a tiny region of the scale, where the model cannot tell them apart well.

Picture a feature whose values cluster near zero while a few sit far above the rest. Plotted, it shows a long tail stretching to the right. Statisticians call this a skewed distribution. The source describes this pattern as many small values together with a few very large ones, and notes that it is very common in practice.

What the Logarithm Does to Spread

A transformation that compresses large values makes the feature easier for a straight-line relationship to describe. A logarithm is one such transformation. After it is applied, the very large values move much closer to the bulk of the data, while the small values, which were crowded together, occupy a wider stretch of the scale. The feature becomes more evenly spread.

The transformation changes the scale of the feature rather than discarding any of its values. Every row keeps its value; only the distances between values change.

0raw0.00log(x+1)3raw1.39log(x+1)8raw2.20log(x+1)120raw4.80log(x+1)2000raw7.60log(x+1)log1plog1plog1plog1plog1p
How does applying log(x + 1) change the distribution, so that many small values and a few very large values end up closer together?

In the diagram, the raw values run from 0 to 2000, a gap of 2000 units between the smallest and largest. After the transformation the same five values run from 0.00 to 7.60. The large value no longer towers over the rest, and the small values are spread more evenly across the scale.

The form log(x + 1) is used because many count values are zero, and the logarithm of zero is undefined. Adding 1 moves every value of zero or more into a range where the logarithm is defined. In Python this is usually written with NumPy's np.log1p, which computes the logarithm of one plus the input directly.

Formula

What do you think happens?

What does np.log1p return when its input is 0?

  • 0

  • 1

  • negative infinity

  • an error

Reveal answer
Answer:

0

log(0 + 1) equals log(1), which is 0. This is why adding 1 before the logarithm makes zero values safe to transform.

Choosing What to Transform

There is no single transformation that always works. The source notes that finding the best transformation for each combination of dataset and model is somewhat of an art. Usually only a subset of the features should be transformed, and sometimes each feature needs its own transformation.

The model family matters. Tree-based models are generally unaffected by these transforms, while linear models often depend on them. Binning, polynomials, and interactions can also have a large influence on less complex models such as linear models and naive Bayes models. Other models, including SVMs, nearest neighbors, and neural networks, may sometimes benefit, but the effect is usually less predictable.

Linear model?Strongly skewed?Apply log(x + 1)Leave unchangedUsually skipyesno, tree-basedyesno
What sequence of checks determines whether a feature or target should be transformed, and when should this step be skipped?

Read the flowchart as a set of questions rather than a fixed rule. The first check is the model family, because tree-based models usually do not need this step. For a linear model, the second check is whether the feature is skewed in the way described above. The flowchart is a practical guide; the source is explicit that the choice of which features to transform is an empirical one, so the test score remains the final judge.

Keeping Fewer Features with SelectPercentile

Transformations change the values of existing features. A second lever changes how many features the model sees. The source warns that it is tempting to create many new features, but adding features makes all models more complex and raises the chance of overfitting. When the feature count is high, it can be wise to keep only the most useful features and discard the rest, which can produce simpler models that generalize better.

The source describes three basic strategies for feature selection: univariate statistics, model-based selection, and iterative selection. All three are supervised, meaning they use the target. This article focuses on univariate selection, where each feature is scored on its own against the target and only the top-scoring share is kept. SelectPercentile implements this by keeping a chosen percentage of the features.

All featuresScore each featureagainst the targetKeep top percentileTrain modelon kept featuresScore on test setheld out
What happens to the full set of features when each one is scored independently and only the top percentile is kept for the model?
python
Notes on the code
  • np.log1p applies the log(x + 1) form to a skewed column.
  • The same transformation is applied to the test data so both sets are on the same scale.
  • SelectPercentile scores features with f_regression and keeps the top 50 percent.
  • fit is called on training data only; the test set is used only for transform and scoring.

After selection, compare the held-out test score with and without the reduction. The source's point is that a simpler model may generalize better, so a score that holds steady or improves on the test set with fewer features is evidence that the reduction helped. A drop in test score means the discarded features contained useful information.

Mistakes When Transforming Data

  • Common mistake

    Applying a logarithm to zero values without adding 1

    What it looks like

    np.log(0) for a count column that contains zeros

    Why it fails

    The logarithm of zero is undefined, so the result is not a usable number.

    Do this instead

    Use log(x + 1), written as np.log1p(x), which keeps zero values in a defined range.

  • Common mistake

    Transforming every feature by default

    Why it fails

    The source states that usually only a subset of the features should be transformed, and that each feature may need its own transformation.

    Do this instead

    Check each skewed feature individually and confirm the change with a test score.

  • Common mistake

    Transforming tree-based models out of habit

    Why it fails

    Tree-based models are generally unaffected by these transforms, so the step usually adds no benefit for them.

    Do this instead

    Skip the step for tree-based models unless an experiment shows a reason to keep it.

  • Common mistake

    Transforming training and test data differently

    Why it fails

    A model trained on one scale and evaluated on another gives a misleading test score.

    Do this instead

    Apply the same transformation to both sets, as the code example does.

  • Common mistake

    Choosing features using the test set

    Why it fails

    Selection is supervised, so using the test target leaks information and inflates the score.

    Do this instead

    Fit SelectPercentile on the training data only and touch the test set just once for final scoring.

Practice: Judging a Transformation

MEDIUM

A dataset has a column of household incomes, mostly between 20 and 90 thousand with a few values above 2 million. You plan to fit a linear regression and then a random forest on the same data. For each model, decide whether to apply log(x + 1) to the income column, and explain the reasoning in terms of skew and model family. Then describe how you would check the decision using a held-out test score.

Hints
  • Ask first whether the column is skewed in the way the article describes.
  • Recall which model family the source says is generally unaffected by these transforms.
  • Think about whether selection or transformation should be fitted on training data only.

Key Takeaways

  • A feature with many small values and a few very large ones is skewed, and a linear model can struggle to fit it because the large values dominate the fit.
  • The form log(x + 1), written in NumPy as np.log1p, compresses large values, handles zeros safely, and changes the spread of values without discarding any of them.
  • Whether to transform is an empirical choice: usually only some features need it, linear models often benefit, and tree-based models usually do not need the step.
  • Univariate selection with SelectPercentile keeps the top-scoring share of features and can yield a simpler model that generalizes better, but it must be fitted on training data only and checked against a held-out test score.

Related concepts

More concepts starting with F