Asiman Data School

Module 3, topic 24, week 12, Thursday

Feature engineering: scaling numerical values

The work on the columns before a model is trained: dropping columns that carry no information, creating new features with logic, selecting features with correlation, and scaling numbers in four ways without letting the test data leak into the training. Every example works with one data file.

Introduction: the work on the columns

The fourth lesson of Module 3. In Topic 22 you built a model, and in Topic 23 you learned to judge it fairly on test data. Both lessons took the columns of the data as they came. This lesson is about the columns themselves. A model can only learn from what its features show it, so the work on the features often changes the score more than any change of the model.

The lesson has three steps, in the order in which they are done in a project. First, cleaning the list of columns: dropping the ones that carry no information, such as an identification number or a name. Second, creating and selecting features: building new columns from the ones you have, and choosing which columns go into the model, with the help of correlation. Third, scaling: bringing numerical features to a comparable size, with four methods, and doing it without letting the test data leak into the training.

Everything is explained on one data file, cars.csv, with the tools you know: pandas, train_test_split and LinearRegression.

You need: reading and changing a DataFrame (Topics 10 and 11), the mean, the median, the standard deviation and the quartiles (Topic 18), covariance and correlation (Topic 20), linear regression and gradient descent (Topic 22), and the train/test split (Topic 23).

What you will learn

  1. 1.Why some columns must be dropped before modelling, and how to recognise them
  2. 2.How to create new features from existing columns with logic, and how to check whether they help
  3. 3.How covariance and correlation help to select features, and what multicollinearity is
  4. 4.Why numerical features are scaled, and which models need it
  5. 5.Four ways of scaling: min-max, standard, robust and the logarithm, and when each is used
  6. 6.The difference between fit, transform and fit_transform
  7. 7.Why the data is split before it is scaled, and what is done with the training data and with the test data
The words of this lesson
WordMeaning
feature engineeringthe work on the input columns: dropping, creating, selecting and transforming them
feature creationbuilding a new column from existing ones: an age from a year, a ratio from two columns
feature selectionchoosing which columns go into the model
multicollinearitytwo or more features that say almost the same
scalingchanging the numbers of a column to a comparable size, without changing what they say
min-max scalingsqueezing a column into the range from 0 to 1
standard scaling (standardisation)giving a column the mean 0 and the standard deviation 1: the z-score
robust scalingscaling with the median and the quartiles, which outliers hardly move
log transformreplacing a value by its logarithm, to pull in a long tail of large values
fitlearn the numbers of a scaler (a minimum, a mean) from data
transformapply the learned numbers to data
data leakageinformation from the test data reaches the training

1The data and a first score

1.1The file

cars.csv describes 240 invented used cars. The target is the price in thousands.

Python
import pandas as pd

df = pd.read_csv("cars.csv")

print(df.shape)
print(df.head(3).T)

Output

(240, 10)
                 0       1       2
car_id        1001    1002    1003
owner_name  Orkhan  Orkhan   Leyla
year          2018    2019    2010
mileage_km  100300  112500  534700
engine_cc     1000    2000    1200
horsepower      61     131      68
weight_kg     2260     980    2320
doors            5       4       2
wheels           4       4       4
price         12.0    42.1     4.5

df.head(3).T shows the first three cars turned on their side (.T, as in NumPy): every column is a line, so all ten columns fit.

The file
ColumnMeaning
car_idthe identification number of the car in the list
owner_namethe first name of the owner
yearthe year in which the car was built
mileage_kmhow far the car has driven, in km
engine_ccthe size of the engine in cubic centimetres
horsepowerthe power of the engine
weight_kgthe weight of the car in kg
doorsthe number of doors
wheelsthe number of wheels
pricethe price in thousands: the target

The data file: cars.csv

240 cars, 10 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.

Download

Loading the table ...

1.2A first model, before any work on the features

To see what feature engineering is worth, we need a starting point: a model that uses the numerical columns as they are. The recipe is the one of Topic 23.

The cell continues from the one above: df is already there.

Python, continues from the cells above
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

X = df[["year", "mileage_km", "engine_cc", "horsepower", "weight_kg", "doors"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)

print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))

Output

0.864
0.879

A test score of 0.879 is the number to beat. Every step of this lesson is judged by what it does to this score.

2Dropping columns that carry no information

Not every column of a table is a feature. Some columns are there to organise the data, not to describe it. Three kinds are dropped before anything else.

2.1An identification number

car_id runs from 1001 to 1240: every car has its own number. It was given in the order in which the cars were written into the list, and it says nothing about the car. A model can still try to use it. With enough flexibility it would even "learn" that car 1017 costs 21.4, which is memorising, not learning: the overfitting of Topic 23. And for a new car, which gets the number 1241, that knowledge is worthless.

The same holds for every column that only names a row: an order number, a customer number, a telephone number, a passport number.

2.2A name

owner_name is the first name of the owner. The price of a car does not depend on whether the owner is called Murad or Leyla. It is also text, and a model calculates with numbers: a column of names cannot go into LinearRegression at all. (Text columns that do carry information, such as a city or a colour, are turned into numbers by encoding. That is Topic 25.)

2.3A column that never changes

wheels is 4 in every row. A column with a single value cannot explain why one car is more expensive than another: it has no variation, and a model learns from variation.

2.4Finding such columns

nunique() counts the different values of every column:

Python, continues from the cells above
print(df.nunique())

Output

car_id        240
owner_name     20
year           20
mileage_km    232
engine_cc       9
horsepower    111
weight_kg     123
doors           4
wheels          1
price         192
dtype: int64
  • car_id has 240 different values in 240 rows: one for each row. That is the mark of an identification number.
  • wheels has 1 value: a constant.
  • owner_name has 20 values, and its meaning (a name) tells you that it is not a feature. No number can tell you that: you have to know what a column means.

2.5Dropping them

Python, continues from the cells above
df = df.drop(columns=["car_id", "owner_name", "wheels"])

print(df.columns.tolist())

Output

['year', 'mileage_km', 'engine_cc', 'horsepower', 'weight_kg', 'doors', 'price']

Change it and run: add "doors" to the list and run: one column less.

2.6Why not leave them in?

  • They can hurt. A column without information gives the model room to find accidental patterns: overfitting (Topic 23).
  • They cost. Every column makes the model larger and slower and harder to read.
  • Some cannot be used at all. Text stops the model with an error.

The rule: before modelling, go through the columns and ask of each one whether it can sensibly influence the target.

A feature for the model, or a column to drop?

1 of 8

customer_id: a different number for every customer, given in the order of registration. The target is the amount a customer spends.

Try it yourself

Drop the three columns of cars.csv that carry no information and print the shape of the table that is left.
Show a hint
df = df.drop(columns=["car_id", "owner_name", "wheels"]), then print(df.shape).
Show the solution
Python
import pandas as pd

df = pd.read_csv("cars.csv")

df = df.drop(columns=["car_id", "owner_name", "wheels"])

print(df.shape)

Output

(240, 7)

3Creating new features

3.1Why create features?

A linear regression can do two things with its features: multiply each one by a weight, and add the results. It cannot subtract a year from today's date, and it cannot divide one column by another. If the price depends on such a combination, the model cannot find it. But you can calculate the combination yourself and hand it to the model as a new column. That is feature creation: putting your knowledge of the subject into the data.

3.2Three features made with logic

Think about what really decides the price of a used car.

1. The age. A buyer does not think "this car is from 2015". The buyer thinks "this car is 11 years old". The age is the year turned into the quantity that matters:

age=2026−year\text{age} = 2026 - \text{year}

2. The power for the weight. 150 horsepower make a small light car fast and a heavy one slow. What a driver feels is the power for every kilogram:

power for the weight=horsepowerweight in kg\text{power for the weight} = \frac{\text{horsepower}}{\text{weight in kg}}

3. The use per year. 120,000 km are a lot for a car of 3 years and little for a car of 15. How hard a car was used is the distance for every year:

km for every year=mileage in kmage\text{km for every year} = \frac{\text{mileage in km}}{\text{age}}

In pandas a new column is one line (Topic 11):

Python, continues from the cells above
df["age"] = 2026 - df["year"]
df["power_to_weight"] = df["horsepower"] / df["weight_kg"]
df["km_per_year"] = df["mileage_km"] / df["age"]

print(df[["year", "age", "power_to_weight", "km_per_year"]].head().round(3))

Output

   year  age  power_to_weight  km_per_year
0  2018    8            0.027    12537.500
1  2019    7            0.134    16071.429
2  2010   16            0.029    33418.750
3  2017    9            0.100     7733.333
4  2010   16            0.049    24068.750

3.3Do they help?

A created feature is an idea, and an idea has to be tested. The test is the score on the test data. The model now gets the age in the place of the year, and the two new ratios:

Python, continues from the cells above
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

X = df[["age", "mileage_km", "engine_cc", "horsepower", "weight_kg", "doors", "power_to_weight", "km_per_year"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)

print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))

Output

0.942
0.943

Change it and run: take "power_to_weight" out of the list and run: the test score falls.

The test score rises from 0.879 to 0.943. The same cars, the same model, the same split: only the features changed.

3.4What each new feature did

What each new feature did
ChangeTest scoreWhy
the six numerical columns as they are0.879the starting point
age in the place of year0.879no change: age is year turned round, and a linear model handles that itself
adding power_to_weight0.929a division: the model could not build it from horsepower and weight_kg
adding km_per_year too0.943another division, with a smaller gain

Two lessons are in this table.

  • A new feature helps when it holds something the model cannot calculate itself. For a linear model that means products, ratios and other curved combinations. A feature that is only a sum or a multiple of existing ones (age from year) changes nothing in the score. It is still worth making, because the model becomes easier to read: "every year of age takes away ..." is clearer than a weight for the year 2015.
  • Not every idea helps, and you find out only by testing. Keep the features that raise the test score (or the cross-validation score), and drop the ones that do not.

3.5How to find ideas

How to find ideas
LogicExample
a difference from a reference pointthe age from a year; the days since the last purchase
a ratio of two columnspower for the weight; price for every square metre; income for every member of a family
a product of two columnsthe area from a length and a width; the total from a price and a number of units
a part of a datethe month, the day of the week (Topic 11)
a total or a mean of several columnsthe total of three exam marks

The question to ask is always: what would a person who knows the subject look at?

Try it yourself

A car was built in 2014. It has 120 horsepower, weighs 1,500 kg and has driven 96,000 km. Calculate its three created features: (a) age, (b) power_to_weight, (c) km_per_year.

Show a hint
The age is 2026 minus the year. The other two are divisions.
Show the solution

Answer: (a) 12; (b) 0.08; (c) 8,000.

age=2026−2014=12power for the weight=1201500=0.08km for every year=9600012=8000\begin{aligned} \text{age} &= 2026 - 2014 = 12 \\[6pt] \text{power for the weight} &= \frac{120}{1500} = 0.08 \\[6pt] \text{km for every year} &= \frac{96000}{12} = 8000 \end{aligned}

Each feature is calculated from the columns of the car's own row. Nothing is taken from other cars, and nothing from the price.

4Selecting features

More features are not always better. A feature that says nothing adds room for overfitting, and two features that say the same confuse the model. Feature selection chooses the columns that go into the model. Its main tool here is the correlation of Topic 20.

4.1Covariance and correlation, once more

Both measure how two columns move together.

  • The covariance is the average product of the deviations from the two means. Its sign says whether the columns rise together (positive) or against each other (negative). But its size depends on the units: a column in kilometres gives huge numbers, a column in doors gives small ones, and the two cannot be compared.
  • The correlation rr is the covariance divided by the two standard deviations. It has no units and always lies between −1-1 and 1. That makes it the tool for comparing columns.
Python, continues from the cells above
print(round(df["mileage_km"].cov(df["price"]), 1))
print(round(df["doors"].cov(df["price"]), 3))

print(round(df["mileage_km"].corr(df["price"]), 2))
print(round(df["doors"].corr(df["price"]), 2))

Output

-688099.3
-0.137
-0.45
-0.01

The first covariance is a number in the hundreds of thousands and the second is close to zero, only because kilometres are large numbers and doors are small ones. The correlations tell the real story: the mileage moves clearly against the price, and the doors have nothing to do with it.

4.2Step 1: which features move with the target?

Python, continues from the cells above
print(df.corr()["price"].round(2).sort_values())

Output

weight_kg         -0.59
mileage_km        -0.45
age               -0.39
km_per_year       -0.27
doors             -0.01
year               0.39
engine_cc          0.52
horsepower         0.56
power_to_weight    0.84
price              1.00
Name: price, dtype: float64

df.corr() is the table of the correlations of all pairs of columns. ["price"] takes the column of the target, and sort_values() puts it in order.

  • Strong (far from 0, in either direction): power_to_weight, weight_kg, horsepower, engine_cc, mileage_km. These are candidates.
  • Close to 0: doors. A candidate for dropping.
  • year and age have the same strength with opposite signs: they are the same information, and one of them is enough.

The created feature power_to_weight has the strongest correlation of all: stronger than the two columns it was made from.

4.3Step 2: which features say the same? Multicollinearity

Two features that are strongly correlated with each other carry almost the same information. This is called multicollinearity. For a linear model it is a problem of its own:

  • The model cannot decide how to divide the effect between the two. One weight can become large and positive and the other large and negative, and they change strongly from one sample to the next (the variance of Topic 23).
  • The weights can no longer be read: "the effect of the horsepower with the engine size held fixed" means little when the two always move together.
  • The predictions are usually still fine. Multicollinearity damages the explanation, not the score.
Python, continues from the cells above
features = df.drop(columns=["price", "year"])

print(features.corr().round(2).to_string())

Output

                 mileage_km  engine_cc  horsepower  weight_kg  doors   age  power_to_weight  km_per_year
mileage_km             1.00       0.08        0.04       0.10  -0.10  0.65            -0.03         0.65
engine_cc              0.08       1.00        0.93      -0.02  -0.08  0.06             0.62         0.00
horsepower             0.04       0.93        1.00      -0.01  -0.04  0.03             0.65        -0.02
weight_kg              0.10      -0.02       -0.01       1.00  -0.02 -0.01            -0.71         0.12
doors                 -0.10      -0.08       -0.04      -0.02   1.00 -0.10            -0.05        -0.04
age                    0.65       0.06        0.03      -0.01  -0.10  1.00             0.06        -0.05
power_to_weight       -0.03       0.62        0.65      -0.71  -0.05  0.06             1.00        -0.11
km_per_year            0.65       0.00       -0.02       0.12  -0.04 -0.05            -0.11         1.00

to_string() prints the whole table; without it pandas leaves out the middle columns of a wide table. Read it for values close to 1 or −1-1 outside the diagonal:

  • engine_cc and horsepower: 0.93. A larger engine has more power: the two columns say almost the same.
  • power_to_weight with weight_kg (−0.71-0.71) and with horsepower (0.65), mileage_km with age and with km_per_year (0.65): related, as expected for features made from one another, but far from saying the same.

A common rule of thumb: a pair above about 0.9 (or below −0.9-0.9) is one feature too many.

The same table as a picture, the heatmap of Topic 12:

Python, continues from the cells above
import matplotlib.pyplot as plt
import seaborn as sns

sns.heatmap(features.corr().round(2), annot=True, cmap="coolwarm", vmin=-1, vmax=1)
plt.title("Correlations between the features")
plt.show()
Chart: Correlations between the features

4.4Step 3: the choice

  • engine_cc and horsepower say the same. Keep the one that is more strongly correlated with the price: horsepower (0.56 against 0.52). Drop engine_cc.
  • doors has a correlation of −0.01-0.01 with the price. Drop it.
  • year is replaced by age.

Six features remain. Does the score suffer?

Python, continues from the cells above
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

X = df[["age", "mileage_km", "horsepower", "weight_kg", "power_to_weight", "km_per_year"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)

print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))

Output

0.941
0.942

Eight features gave 0.943, six give 0.942. Two columns less, and nothing lost: the model is simpler, and its weights can be read again. These six features are the ones the rest of the lesson works with.

4.5The limits of this method

  • Correlation sees only straight lines (Topic 20). A feature with a curved relationship to the target can have a correlation near 0 and still be useful.
  • A feature can be weak alone and useful together with others. The final judge is the score on data the model has not seen: try the model with and without the feature, with the test score or with cross-validation (Topic 23).
  • A strong correlation is not a cause.

Try it yourself

A table has the target sales and four features. Their correlations with the target: adverts 0.81, discount −0.74-0.74, shelf_number 0.03, advert_minutes 0.78. The features adverts and advert_minutes have a correlation of 0.96 with each other. (a) Which feature has no straight-line relationship with the target? (b) Which pair is a case of multicollinearity? (c) Which feature of that pair is kept?

Show a hint
Close to 0 means no straight-line relationship. A pair of features above about 0.9 says the same; keep the one that is more strongly correlated with the target.
Show the solution

Answer: (a) shelf_number; (b) adverts and advert_minutes; (c) adverts.

The correlation 0.03 is close to 0, so shelf_number is a candidate for dropping. The sign of −0.74-0.74 does not make discount weak: it is a strong relationship in the other direction. The pair with 0.96 carries almost the same information, and adverts (0.81) is a little closer to the target than advert_minutes (0.78).

5Why scale?

5.1Columns of very different sizes

Python, continues from the cells above
print(X.describe().loc[["min", "max"]].round(2).T)

Output

                     min        max
age                 1.00      20.00
mileage_km       2800.00  534700.00
horsepower         55.00     260.00
weight_kg         800.00    2390.00
power_to_weight     0.03       0.22
km_per_year      2369.23   42991.67

The mileage runs into the hundreds of thousands. The power for the weight is always below 1. The largest value of one column is several million times the largest value of another. These sizes say nothing about importance: they come from the units. A distance in kilometres is a large number; the same distance in thousands of kilometres would be a small one.

Scaling changes the numbers of every column to a comparable size, without changing what they say: the order of the cars in a column stays the same, and so do the relative distances between them.

5.2Three reasons

1. The weights become comparable. The weights of the model with the six features:

Python, continues from the cells above
for name, weight in zip(X.columns, model.coef_):
    print(name, round(weight, 4))

Output

age -1.0567
mileage_km -0.0
horsepower -0.019
weight_kg 0.0034
power_to_weight 340.4242
km_per_year -0.0003

The weight of power_to_weight is in the hundreds, and the weight of mileage_km prints as -0.0. That does not mean that the power matters and the mileage does not. A weight is the change for one unit of its feature (Topic 22): one kilometre more changes almost nothing, and "one unit more" of power_to_weight is far more than the difference between the weakest and the strongest car. Weights of features on different scales cannot be compared. After scaling they can (Part 8).

2. Gradient descent needs it. Topic 22 trained a line by walking down the loss with a learning rate. With features of very different sizes, the loss is a valley that is extremely steep in one direction and almost flat in another. A step that is small enough for the steep direction makes no progress in the flat one, and a step that is large enough for the flat direction jumps out of the valley in the steep one.

Features on different scales

a narrow valley: the steps zigzag

Features on the same scale

a round bowl: the steps go straight down

The loss of a model with two weights, seen from above: every line joins weights with the same loss, and the dot in the middle is the lowest point. Left: features of very different sizes make a narrow valley, and the steps of gradient descent jump from side to side. Right: after scaling the valley is a round bowl, and the same walk goes straight to the bottom.

LinearRegression does not walk: it uses the exact formulas, so it does not suffer from this. scikit-learn also has a linear regression that is trained by gradient descent, SGDRegressor. It is used exactly like LinearRegression. On the unscaled cars:

Python, continues from the cells above
from sklearn.linear_model import SGDRegressor

sgd = SGDRegressor(random_state=0)
sgd.fit(X_train, y_train)

print(sgd.score(X_test, y_test) < 0)

Output

True

The score is not only below 0: it is a negative number with dozens of digits. The walk ran away, as with a learning rate that is too large in Topic 22. The same model on scaled features works well, as Part 8 shows. Most models of modern machine learning are trained by gradient descent, so for them scaling is not a nicety. It decides whether the training works.

3. Distances need it. Many later models compare samples by their distance (k-nearest neighbours, k-means, support vector machines). In a distance, a feature with large numbers decides almost alone: two cars that differ by 20,000 km are "far apart", whatever their age and power. Regularization (Topic 26) and principal component analysis depend on the scale in a similar way.

5.3Which models need scaling?

Which models need scaling?
Needs scalingDoes not need it
models trained by gradient descent (SGDRegressor, logistic regression, neural networks)LinearRegression with its exact formulas: the predictions and the score stay the same
models that use distances (k-nearest neighbours, k-means, support vector machines)decision trees and the models built from them (random forests, boosting)
regularized models (Ridge, Lasso), principal component analysis

When in doubt, scale: it rarely hurts, and for LinearRegression it still makes the weights comparable.

Try it yourself

Does scaling matter here? (a) A model of k-nearest neighbours, which compares samples by their distance. (b) A decision tree. (c) An SGDRegressor. (d) The test score of LinearRegression.

Show a hint
Gradient descent and distances depend on the size of the numbers. Trees and the exact formulas of LinearRegression do not.
Show the solution

Answer: (a) yes; (b) no; (c) yes; (d) no.

In a distance the feature with the large numbers decides almost alone, and gradient descent runs away on features of very different sizes. A tree and the exact formulas of LinearRegression give the same predictions before and after scaling. For LinearRegression scaling still makes the weights comparable.

6Four ways of scaling

All four are shown on the same five values, so that you can see what each one does: 10, 20, 30, 40, 100. Four values lie close together and one, 100, lies far away: an outlier.

6.1Min-max scaling

xscaled=x−min⁡max⁡−min⁡x_{\text{scaled}} = \frac{x - \min}{\max - \min}

The smallest value becomes 0, the largest becomes 1, and everything else lies in between.

min⁡=10max⁡=100max⁡−min⁡=9010:10−1090=020:20−1090=0.11130:30−1090=0.22240:40−1090=0.333100:100−1090=1\begin{aligned} & \min = 10 \qquad \max = 100 \\[4pt] & \max - \min = 90 \\[8pt] 10:\quad & \frac{10 - 10}{90} = 0 \\[4pt] 20:\quad & \frac{20 - 10}{90} = 0.111 \\[4pt] 30:\quad & \frac{30 - 10}{90} = 0.222 \\[4pt] 40:\quad & \frac{40 - 10}{90} = 0.333 \\[4pt] 100:\quad & \frac{100 - 10}{90} = 1 \end{aligned}
  • For: easy to understand, and a fixed range from 0 to 1. Useful when the values have natural limits (a percentage, the brightness of a pixel).
  • Against: the minimum and the maximum are the two values most exposed to outliers. Here the single value 100 squeezes the other four into the lowest third of the range.

6.2Standard scaling

xscaled=x−meanstandard deviationx_{\text{scaled}} = \frac{x - \text{mean}}{\text{standard deviation}}

This is the z-score of Topic 18: how many standard deviations a value lies above or below the mean. After it the column has the mean 0 and the standard deviation 1.

mean=10+20+30+40+1005=40squared deviations:900+400+100+0+3600=5000standard deviation=50005=1000=31.623\begin{aligned} & \text{mean} = \frac{10 + 20 + 30 + 40 + 100}{5} = 40 \\[6pt] & \text{squared deviations:} \\ & 900 + 400 + 100 + 0 + 3600 = 5000 \\[6pt] & \text{standard deviation} = \sqrt{\frac{5000}{5}} \\[4pt] & \qquad = \sqrt{1000} = 31.623 \end{aligned}
10:10−4031.623=−0.94920:20−4031.623=−0.63230:30−4031.623=−0.31640:40−4031.623=0100:100−4031.623=1.897\begin{aligned} 10:\quad & \frac{10 - 40}{31.623} = -0.949 \\[4pt] 20:\quad & \frac{20 - 40}{31.623} = -0.632 \\[4pt] 30:\quad & \frac{30 - 40}{31.623} = -0.316 \\[4pt] 40:\quad & \frac{40 - 40}{31.623} = 0 \\[4pt] 100:\quad & \frac{100 - 40}{31.623} = 1.897 \end{aligned}

(scikit-learn divides the sum of squares by nn, the population formula of Topic 18, not by n−1n - 1. For scaling the difference does not matter.)

  • For: the usual first choice. It has no fixed limits, so an outlier is not squeezed against a wall, and it suits models that are trained by gradient descent.
  • Against: the mean and the standard deviation are themselves moved by outliers (Topic 18): here the value 100 pulls the mean up to 40, above four of the five values.

6.3Robust scaling

xscaled=x−medianIQRIQR=Q3−Q1x_{\text{scaled}} = \frac{x - \text{median}}{\text{IQR}} \qquad \text{IQR} = Q_3 - Q_1

It uses the median and the interquartile range of Topic 18, which outliers hardly move.

median=30Q1=20Q3=40IQR=40−20=2010:10−3020=−120:20−3020=−0.530:30−3020=040:40−3020=0.5100:100−3020=3.5\begin{aligned} & \text{median} = 30 \qquad Q_1 = 20 \qquad Q_3 = 40 \\[4pt] & \text{IQR} = 40 - 20 = 20 \\[8pt] 10:\quad & \frac{10 - 30}{20} = -1 \\[4pt] 20:\quad & \frac{20 - 30}{20} = -0.5 \\[4pt] 30:\quad & \frac{30 - 30}{20} = 0 \\[4pt] 40:\quad & \frac{40 - 30}{20} = 0.5 \\[4pt] 100:\quad & \frac{100 - 30}{20} = 3.5 \end{aligned}
  • For: the four ordinary values are spread evenly around 0, as if the outlier were not there. The outlier itself stays far away, visibly.
  • Against: no fixed range.

6.4The log transform

xscaled=log⁡(x)x_{\text{scaled}} = \log(x)

The logarithm is different from the other three. They move and stretch a column evenly; the logarithm changes its shape: it pulls large values in much more than small ones. With the logarithm to the base 10:

10:log⁡10(10)=120:log⁡10(20)=1.30130:log⁡10(30)=1.47740:log⁡10(40)=1.602100:log⁡10(100)=2\begin{aligned} 10:\quad & \log_{10}(10) = 1 \\ 20:\quad & \log_{10}(20) = 1.301 \\ 30:\quad & \log_{10}(30) = 1.477 \\ 40:\quad & \log_{10}(40) = 1.602 \\ 100:\quad & \log_{10}(100) = 2 \end{aligned}

The value 100 was ten times the value 10; now it is twice as large. Equal ratios become equal distances: from 10 to 100 is as far as from 100 to 1,000.

  • For: columns with a long tail of large values: incomes, prices, mileages, numbers of visitors. Many such quantities work in ratios in real life: the difference between 10,000 and 20,000 km matters more than the difference between 210,000 and 220,000 km.
  • Against: only for positive values (the logarithm of 0 or of a negative number does not exist; for columns with zeros np.log1p(x), the logarithm of x+1x + 1, is used). And because it changes the shape, it changes the model: the score of a linear regression can go up or down.

The values

10203040100

Min-max (from 0 to 1)

00.110.220.331

Standard (mean 0, standard deviation 1)

−0.95−0.63−0.3201.9

Robust (median 0, the middle half has the width 1)

−1−0.500.53.5

Logarithm (large values are pulled in)

11.31.481.62
The same five values under the four ways of scaling. Every line stretches from its smallest to its largest value. The first three keep the picture: four values close together and one far away. Only the numbers change. The logarithm changes the picture itself: the distant value moves in.

6.5The four side by side

The four side by side
Min-maxStandardRobustLogarithm
Formulax−min⁡max⁡−min⁡\frac{x - \min}{\max - \min}x−meanstd\frac{x - \text{mean}}{\text{std}}x−medianIQR\frac{x - \text{median}}{\text{IQR}}log⁡(x)\log(x)
Resultfrom 0 to 1mean 0, standard deviation 1median 0a new shape
Outlierssqueeze all other valuespull the mean and the spreadhardly matterare pulled in
Changes the shape of the columnnononoyes
In scikit-learnMinMaxScalerStandardScalerRobustScalernp.log (NumPy)
Use it whena fixed range is needed; no strong outliersthe usual first choicethe column has outliersthe column has a long tail of large positive values

6.6In Python

The three scalers of scikit-learn live in sklearn.preprocessing and are used in the same way. Here is MinMaxScaler on the training data of the cars:

Python, continues from the cells above
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)

print(X_train_scaled[:3].round(3))
print(X_train_scaled.min(axis=0))
print(X_train_scaled.max(axis=0))

Output

[[0.263 0.139 0.58  0.157 0.789 0.256]
 [0.684 0.822 0.205 0.994 0.078 0.715]
 [0.053 0.065 0.215 0.189 0.358 0.402]]
[0. 0. 0. 0. 0. 0.]
[1. 1. 1. 1. 1. 1.]

The result is a NumPy array with the same rows and columns. The first print shows three cars: every number now lies between 0 and 1. The other two prints are the smallest and the largest value of every column (axis=0, as in Topic 9): exactly 0 and 1.

StandardScaler gives every column the mean 0 and the standard deviation 1:

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)

print(X_train_scaled[:3].round(3))
print(X_train_scaled.mean(axis=0).round(3))
print(X_train_scaled.std(axis=0).round(3))

Output

[[-0.735 -0.573  1.498 -1.258  2.347 -0.218]
 [ 0.737  2.67  -0.594  1.456 -1.037  2.264]
 [-1.472 -0.922 -0.539 -1.156  0.296  0.573]]
[ 0. -0. -0.  0. -0.  0.]
[1. 1. 1. 1. 1. 1.]

The values are now positive and negative: above and below the mean of their column. (A mean printed as -0. is zero: a tiny rounding remainder with a minus sign.)

RobustScaler gives every column the median 0. To see what the three scalers do with an outlier, compare the largest value of the column mileage_km, a car with more than 500,000 km, under each of them:

Python, continues from the cells above
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler

for scaler in [MinMaxScaler(), StandardScaler(), RobustScaler()]:
    mileage = scaler.fit_transform(X_train)[:, 1]
    print(type(scaler).__name__, round(mileage.min(), 2), round(pd.Series(mileage).median(), 2), round(mileage.max(), 2))

Output

MinMaxScaler 0.0 0.21 1.0
StandardScaler -1.23 -0.23 3.52
RobustScaler -0.91 0.0 3.42

Every line shows the smallest value, the median and the largest value of the scaled mileage ([:, 1] is the second column). With min-max the median lies at about 0.2: most cars are pressed into the lower part of the range by a few cars with a very high mileage. With the robust scaler the median is exactly 0 and the ordinary cars lie around it; the extreme car stands out at more than 3.

6.7The logarithm on a column with a long tail

The mileage is such a column: most cars have between 50,000 and 200,000 km, and a few have 400,000 or more.

Python, continues from the cells above
import matplotlib.pyplot as plt

plt.hist(df["mileage_km"], bins=20)
plt.xlabel("mileage_km")
plt.ylabel("number of cars")
plt.title("The mileage: a long tail to the right")
plt.show()
Chart: The mileage: a long tail to the right
Python, continues from the cells above
import numpy as np
import matplotlib.pyplot as plt

df["log_mileage"] = np.log(df["mileage_km"])

plt.hist(df["log_mileage"], bins=20)
plt.xlabel("log of mileage_km")
plt.ylabel("number of cars")
plt.title("After the logarithm: the tail is pulled in")
plt.show()
Chart: After the logarithm: the tail is pulled in

The correlation with the price, before and after:

Python, continues from the cells above
print(round(df["mileage_km"].corr(df["price"]), 2))
print(round(df["log_mileage"].corr(df["price"]), 2))

Output

-0.45
-0.49

np.log is the natural logarithm of NumPy; which base is used makes no difference for a model. After the transform the long tail to the right is gone, and the correlation of the column with the price is a little stronger: the price follows the ratio of the mileages, not their difference. Part 8 shows what that does to the score.

Four values, 10, 20, 30 and 40, and a fifth one that you can move away. Choose a way of scaling.

The values

10203040100

Scaled

00.110.220.331

Min-max: 0, 0.111, 0.222, 0.333, 1

The largest value is always 1. The further away it is, the more the other four are pressed towards 0.

Try it yourself

(a) The values 0, 5, 10 and 20 are scaled with min-max scaling. What does 5 become? (b) What does 10 become? (c) The values 2, 4, 6, 8 and 10 have the median 6 and the quartiles Q1=4Q_1 = 4 and Q3=8Q_3 = 8. What does robust scaling make of 10? (d) What is the logarithm to the base 10 of 1,000?

Show a hint
Min-max: subtract the minimum and divide by the maximum minus the minimum. Robust: subtract the median and divide by Q3−Q1Q_3 - Q_1. 103=100010^3 = 1000.
Show the solution

Answer: (a) 0.25; (b) 0.5; (c) 1; (d) 3.

(a)5−020−0=0.25(b)10−020−0=0.5(c)10−68−4=44=1(d)log⁡10(1000)=3because103=1000\begin{aligned} \text{(a)}\quad & \frac{5 - 0}{20 - 0} = 0.25 \\[6pt] \text{(b)}\quad & \frac{10 - 0}{20 - 0} = 0.5 \\[6pt] \text{(c)}\quad & \frac{10 - 6}{8 - 4} = \frac{4}{4} = 1 \\[6pt] \text{(d)}\quad & \log_{10}(1000) = 3 \quad\text{because}\quad 10^3 = 1000 \end{aligned}

7fit, transform, and the order of the steps

7.1Two actions

A scaler works in two steps, and it is important to keep them apart.

  • fit looks at data and learns the numbers the scaler needs: the minimum and the maximum of every column for MinMaxScaler, the mean and the standard deviation for StandardScaler, the median and the quartiles for RobustScaler. It changes nothing.
  • transform applies these learned numbers to data and returns the scaled values. It learns nothing.
  • fit_transform does both, one after the other, on the same data. It is a shortcut.
Python, continues from the cells above
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
scaler.fit(X_train)

for name, low, high in zip(X.columns, scaler.data_min_, scaler.data_max_):
    print(name, round(low, 2), round(high, 2))

Output

age 1.0 20.0
mileage_km 2800.0 534700.0
horsepower 55.0 260.0
weight_kg 800.0 2390.0
power_to_weight 0.03 0.2
km_per_year 2369.23 42991.67

After fit, the scaler holds the smallest and the largest value of every column of the training data: data_min_ and data_max_. The loop prints them next to the names of the columns. The names end in an underscore, because they were learned from data (Topic 21). This is the same idea as model.fit: a model learns its weights, a scaler learns its numbers.

7.2The split comes first

The order of the steps is the most important rule of this lesson:

The order of the steps. The data is split first. The scaler learns its numbers from the training data only (fit_transform) and applies the same numbers to the test data (transform). One scaler serves both parts.
  1. Split the data into a training part and a test part.
  2. fit the scaler on the training data only.
  3. transform the training data and the test data with that one scaler.

7.3Why not scale first and split afterwards?

It looks simpler to scale the whole table once and split it later. It is wrong, and the reason is the rule of Topic 23: the test data stands for data the model has never seen.

When a scaler is fitted on all the rows, its minimum, maximum, mean and standard deviation are calculated from the test rows too. Something about the test data (how large its values are, where its extremes lie) has then flowed into the numbers the training data is scaled with. That is data leakage. The test is no longer a test of unseen data, and its score is a little too flattering.

Think of the model in real use. A new car arrives tomorrow. It has to be scaled with numbers that exist today, and those are the numbers of the training data. The test data must be treated exactly like that new car.

Python, continues from the cells above
print(round(X["mileage_km"].mean(), 1), round(X["mileage_km"].std(), 1))
print(round(X_train["mileage_km"].mean(), 1), round(X_train["mileage_km"].std(), 1))

Output

145240.8 116584.6
140661.5 112323.2

The first line is the mean and the standard deviation of the mileage in all 240 cars, the second in the 192 training cars. They differ. A StandardScaler fitted on all the rows would use the first pair, and that pair contains the 48 test cars.

7.4Train and test: who gets what

Python, continues from the cells above
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(X_train_scaled.min(axis=0).round(2), X_train_scaled.max(axis=0).round(2))
print(X_test_scaled.min(axis=0).round(2), X_test_scaled.max(axis=0).round(2))

Output

[0. 0. 0. 0. 0. 0.] [1. 1. 1. 1. 1. 1.]
[0.   0.   0.03 0.02 0.07 0.  ] [1.   0.89 0.85 0.99 1.09 0.94]

The training data lies exactly between 0 and 1: its own minimum and maximum were used. The test data does not: its smallest values are not all 0, and one of its largest values is above 1 (the fifth column, 1.09), because a test car can have more power for its weight than every training car. That is correct, and it is what happens with every new car in real use. Do not "repair" it by fitting the scaler again.

Train and test: who gets what
DataWhat to callWhy
training datascaler.fit_transform(X_train)learn the numbers and apply them
test datascaler.transform(X_test)apply the numbers of the training data
new data in real usescaler.transform(X_new)the same
neverscaler.fit(X_test), scaler.fit_transform(X_test), scaler.fit(X) before the splitthe test data would shape its own scaling

Only the features are scaled. The target y stays as it is.

7.5Which steps come before the split?

Which steps come before the split?
StepBefore or after the split?Why
dropping columnsbeforeit uses the meaning of a column, not its values
creating a feature from the columns of the same row (age, power_to_weight)beforeevery row is calculated from itself alone; nothing is learned from other rows
the logarithm of a columnbefore or afterevery value is transformed by itself; nothing is learned
min-max, standard, robust scalingfit after the split, on the training datathe scaler learns numbers from the rows it sees

The question that decides: does the step learn something from the rows? If it does, it learns from the training rows only.

A MinMaxScaler was fitted on training data with the minimum 10 and the maximum 50. Now a value of the test data arrives.

(30 − 10) / (50 − 10) = 0.5

The result lies between 0 and 1, like the training values. The scaler uses the minimum and the maximum it learned from the training data, whatever the test value is.

Try it yourself

Fit a MinMaxScaler on X_train and transform X_test with it. Print the largest value of each of the two columns of the scaled test data, rounded to 2 decimals.
Show a hint
scaler.fit(X_train), then X_test_scaled = scaler.transform(X_test) and print(X_test_scaled.max(axis=0).round(2)).
Show the solution
Python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler

df = pd.read_csv("cars.csv")
X = df[["horsepower", "weight_kg"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = MinMaxScaler()
scaler.fit(X_train)
X_test_scaled = scaler.transform(X_test)

print(X_test_scaled.max(axis=0).round(2))

Output

[0.85 0.99]

8Every scaler at once, and the scores

Now the comparison the lesson has been building up to: the same six features, the same split, four ways of scaling, two models.

8.1LinearRegression

Python, continues from the cells above
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler

for scaler in [MinMaxScaler(), StandardScaler(), RobustScaler()]:
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    model = LinearRegression()
    model.fit(X_train_scaled, y_train)
    print(type(scaler).__name__, round(model.score(X_test_scaled, y_test), 3))

Output

MinMaxScaler 0.942
StandardScaler 0.942
RobustScaler 0.942

Three scalers, one score, and it is the score without scaling (0.942). This is not a mistake. Min-max, standard and robust scaling only move and stretch every column, and a linear regression with exact formulas adjusts its weights to any such change: the predictions stay the same. For this model scaling changes the weights, not the score.

8.2SGDRegressor: the model that walks

Python, continues from the cells above
from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler

for scaler in [MinMaxScaler(), StandardScaler(), RobustScaler()]:
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    sgd = SGDRegressor(random_state=0)
    sgd.fit(X_train_scaled, y_train)
    print(type(scaler).__name__, round(sgd.score(X_test_scaled, y_test), 3))

Output

MinMaxScaler 0.935
StandardScaler 0.946
RobustScaler 0.946

Without scaling this model failed completely (Part 5). With any of the three scalers it works, and now the scalers differ a little, because the shape of the valley decides how far the walk gets in its steps. random_state=0 fixes the random order in which the model visits the rows.

8.3The scores side by side

The scores side by side
ScalingLinearRegressionSGDRegressor
none0.942fails (far below 0)
min-max0.9420.935
standard0.9420.946
robust0.9420.946

8.4Weights that can be compared

With standard scaling every feature has the same spread, so one unit means the same for all of them: one standard deviation.

Python, continues from the cells above
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)

model = LinearRegression()
model.fit(X_train_scaled, y_train)

for name, weight in zip(X.columns, model.coef_):
    print(name, round(weight, 2))

Output

age -5.74
mileage_km -0.18
horsepower -0.7
weight_kg 1.65
power_to_weight 12.57
km_per_year -2.53

Now the weights tell a story. A car whose power for the weight is one standard deviation above the average costs about 12.6 thousand more; one standard deviation of age takes away almost 6 thousand. The power for the weight is the strongest feature, the age the second. In Part 5 the weight of the mileage printed as -0.0; that was only the unit.

8.5The logarithm changes the score

The logarithm is the one transform that changes the shape of a column, so it is the one that can change the score of a linear regression. The model gets the logarithm of the mileage in the place of the two mileage features:

Python, continues from the cells above
import numpy as np

df["log_mileage"] = np.log(df["mileage_km"])

X = df[["age", "log_mileage", "horsepower", "weight_kg", "power_to_weight"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)

print(round(model.score(X_train, y_train), 3))
print(round(model.score(X_test, y_test), 3))

Output

0.962
0.954

The test score rises from 0.942 to 0.954, with one feature less. For these cars the price falls with the ratio of the mileages: the first 50,000 km cost a car much more of its value than the 50,000 km between 250,000 and 300,000. A straight line through the raw mileage cannot follow that; a straight line through its logarithm can.

8.6The road from the first model to the last

The road from the first model to the last
StepFeaturesTest score
the numerical columns as they are (Part 1)60.879
created features added (Part 3)80.943
after selection (Part 4)60.942
the logarithm of the mileage (Part 8)50.954
The test score of the same model, LinearRegression, after each step of the lesson. Every gain came from the work on the features.

The model never changed. It was LinearRegression from the first line to the last. Everything was won by the work on the features.

Try it yourself

(a) LinearRegression has a test score of 0.90 on unscaled features. What is its score after standard scaling of the same features? (b) Which transform can change the score of a linear regression? (c) After standard scaling a model has the weights 4.2 for area, −7.5-7.5 for distance and 0.9 for floor. Which feature has the largest effect?

Show a hint
Min-max, standard and robust scaling move and stretch a column. The logarithm changes its shape. For the effect, the distance of a weight from 0 counts, not its sign.
Show the solution

Answer: (a) 0.90; (b) the logarithm; (c) distance.

A linear regression with exact formulas adjusts its weights to every moving and stretching of a column, so the predictions stay the same. The logarithm bends the column, and the model is a different one. The weight −7.5-7.5 is furthest from 0: one standard deviation more distance takes away 7.5.

9Common mistakes

Common mistakes
MistakeWhy it is wrongRight
Leaving an identification number among the features.It names a row and describes nothing; a model can only memorise it.Drop it before modelling.
Dropping a column only because its name looks unimportant.Whether a column matters is decided by its meaning and by the test score.Ask whether it can sensibly influence the target; test with and without it.
Creating a feature from the target (price_per_kg = price / weight_kg) and using it as a feature.The feature contains the answer: data leakage.Create features only from other features.
Expecting that age = 2026 - year raises the score of a linear model.It is the same information turned round.Create ratios and products; keep age for readability.
Keeping two features with a correlation of 0.95.They say the same; the weights become unstable and unreadable.Keep one of them.
Dropping every feature with a low correlation to the target.Correlation sees only straight lines, and a feature can help together with others.Use correlation as a first look and the test score as the judge.
Scaling the whole table and splitting afterwards.The test rows shape the numbers of the scaler: data leakage.Split first; fit on the training data.
scaler.fit_transform(X_test)The test data gets its own scaling, different from the one the model was trained with.scaler.transform(X_test)
A second scaler for the test data.The same value would become two different numbers in the two parts.One scaler, fitted once on the training data.
Scaling the target y together with the features.The predictions would be in scaled units.Scale the features only.
"After min-max scaling the test data must lie between 0 and 1."The limits come from the training data; a test value can lie outside them.Values slightly below 0 or above 1 are correct.
Expecting a better score from scaling for LinearRegression.Its predictions do not change with min-max, standard or robust scaling.Scale for comparable weights, and for the models that need it.
Training an SGDRegressor on unscaled features.Gradient descent runs away when the features have very different sizes.Scale first.
np.log on a column with zeros or negative values.The logarithm does not exist there.np.log1p for columns with zeros; no logarithm for negative values.
Using min-max scaling on a column with strong outliers.One extreme value presses all the others into a corner.RobustScaler, or the logarithm for a long tail.

10Solved problems

Ten problems. The first three are short calculations by hand; the others are in Python on cars.csv, and each one runs on its own (the second cell of Problem 9 continues from its first).

Problem 1: Min-max by hand

Scale the values 4, 6, 10, 20 with min-max scaling.

Idea. x−min⁡max⁡−min⁡\frac{x - \min}{\max - \min} (Part 6).

min⁡=4max⁡=20max⁡−min⁡=164:4−416=06:6−416=0.12510:10−416=0.37520:20−416=1\begin{aligned} & \min = 4 \qquad \max = 20 \\[4pt] & \max - \min = 16 \\[8pt] 4:\quad & \frac{4 - 4}{16} = 0 \\[4pt] 6:\quad & \frac{6 - 4}{16} = 0.125 \\[4pt] 10:\quad & \frac{10 - 4}{16} = 0.375 \\[4pt] 20:\quad & \frac{20 - 4}{16} = 1 \end{aligned}

Why: the smallest value becomes 0 and the largest 1. The order and the relative distances stay: 10 lies three eighths of the way from 4 to 20, before and after.

Problem 2: Standard scaling by hand

Scale the values 2, 4, 6, 8 with standard scaling.

Idea. x−meanstandard deviation\frac{x - \text{mean}}{\text{standard deviation}}, with the standard deviation that divides by nn (Part 6).

mean=2+4+6+84=5squared deviations:9+1+1+9=20standard deviation=204=5=2.2362:2−52.236=−1.3424:4−52.236=−0.4476:6−52.236=0.4478:8−52.236=1.342\begin{aligned} \text{mean} &= \frac{2 + 4 + 6 + 8}{4} = 5 \\[6pt] \text{squared deviations:}\quad & 9 + 1 + 1 + 9 = 20 \\[6pt] \text{standard deviation} &= \sqrt{\frac{20}{4}} = \sqrt{5} = 2.236 \\[8pt] 2:\quad & \frac{2 - 5}{2.236} = -1.342 \\[4pt] 4:\quad & \frac{4 - 5}{2.236} = -0.447 \\[4pt] 6:\quad & \frac{6 - 5}{2.236} = 0.447 \\[4pt] 8:\quad & \frac{8 - 5}{2.236} = 1.342 \end{aligned}

Why: the scaled values add up to 0 (their mean is 0), and they are symmetric because the original values are. A value of −1.342-1.342 lies 1.342 standard deviations below the mean.

Problem 3: An outlier and two scalers

Scale the values 1, 2, 3, 4, 50 with min-max scaling and with robust scaling. What happens to the four small values?

Idea. Min-max uses the extremes; the robust scaler uses the median and the quartiles (Part 6).

Min-maxmin⁡=1max⁡=50max⁡−min⁡=491:02:149=0.023:249=0.0414:349=0.06150:1Robustmedian=3Q1=2Q3=4IQR=4−2=21:1−32=−12:−0.53:04:0.550:50−32=23.5\begin{aligned} & \textbf{Min-max} \\[4pt] & \min = 1 \qquad \max = 50 \\[4pt] & \max - \min = 49 \\[6pt] 1:\quad & 0 \\ 2:\quad & \frac{1}{49} = 0.02 \\[4pt] 3:\quad & \frac{2}{49} = 0.041 \\[4pt] 4:\quad & \frac{3}{49} = 0.061 \\[4pt] 50:\quad & 1 \\[10pt] & \textbf{Robust} \\[4pt] & \text{median} = 3 \quad Q_1 = 2 \quad Q_3 = 4 \\[4pt] & \text{IQR} = 4 - 2 = 2 \\[6pt] 1:\quad & \frac{1 - 3}{2} = -1 \\[4pt] 2:\quad & -0.5 \\ 3:\quad & 0 \\ 4:\quad & 0.5 \\ 50:\quad & \frac{50 - 3}{2} = 23.5 \end{aligned}

Why: with min-max the four ordinary values are pressed into the first 6 percent of the range: they are almost indistinguishable. With the robust scaler they are spread evenly from −1-1 to 0.5, and the outlier stands far away at 23.5. The outlier is not removed by either method; the robust scaler only stops it from deciding the scale.

Problem 4: Columns to drop

Find the columns of cars.csv that have one value for every row, or a single value in all rows.

Idea. nunique() counts the different values; compare it with the number of rows (Part 2).

Python
import pandas as pd

df = pd.read_csv("cars.csv")

counts = df.nunique()
print(counts[counts == len(df)].index.tolist())
print(counts[counts == 1].index.tolist())

Output

['car_id']
['wheels']

Why: a column with as many values as rows names the rows: an identification number. A column with one value is a constant. Both carry no information for a model. (owner_name must be found by its meaning.)

Problem 5: A new feature

Create the feature cc_per_kg, the engine size for every kilogram of weight, and print its correlation with the price next to the correlations of the two columns it is made from.

Idea. A ratio of two columns is one line; corr measures how it moves with the target (Parts 3 and 4).

Python
import pandas as pd

df = pd.read_csv("cars.csv")

df["cc_per_kg"] = df["engine_cc"] / df["weight_kg"]

print(round(df["engine_cc"].corr(df["price"]), 2))
print(round(df["weight_kg"].corr(df["price"]), 2))
print(round(df["cc_per_kg"].corr(df["price"]), 2))

Output

0.52
-0.59
0.8

Why: the ratio is more strongly correlated with the price than either of its parts. A large engine in a light car is what the price follows, and that only shows when the two columns are combined.

Problem 6: Pairs that say the same

Print the correlation between engine_cc and horsepower, and between year and mileage_km. Which pair is a case of multicollinearity?

Idea. A correlation between two features above about 0.9 or below −0.9-0.9 (Part 4).

Python
import pandas as pd

df = pd.read_csv("cars.csv")

print(round(df["engine_cc"].corr(df["horsepower"]), 2))
print(round(df["year"].corr(df["mileage_km"]), 2))

Output

0.93
-0.65

Why: the engine size and the horsepower have a correlation of 0.93: they carry almost the same information, and one of them is enough. The year and the mileage are related (older cars have driven more), but −0.65-0.65 leaves each of them plenty to say on its own.

Problem 7: Does a feature help?

Compare two models with the test score: one with the six numerical columns of the file, and one that also gets power_to_weight.

Idea. The judge of a created feature is the score on the test data (Part 3).

Python
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

df = pd.read_csv("cars.csv")
df["power_to_weight"] = df["horsepower"] / df["weight_kg"]
y = df["price"]

columns = ["year", "mileage_km", "engine_cc", "horsepower", "weight_kg", "doors"]

for features in [columns, columns + ["power_to_weight"]]:
    X_train, X_test, y_train, y_test = train_test_split(df[features], y, test_size=0.2, random_state=42)
    model = LinearRegression()
    model.fit(X_train, y_train)
    print(len(features), round(model.score(X_test, y_test), 3))

Output

6 0.879
7 0.929

Why: the seventh feature is calculated from two columns the model already has, and still the score rises: a linear model can add and weight its columns, but it cannot divide them. The same random_state gives the same split for both models, so the comparison is fair.

Problem 8: Scale after the split

Take the features mileage_km and weight_kg. Split the data, fit a StandardScaler on the training data, and transform both parts. Print the means of the two columns in the scaled training data and in the scaled test data.

Idea. fit_transform on the training data, transform on the test data (Part 7).

Python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("cars.csv")
X = df[["mileage_km", "weight_kg"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

print(X_train_scaled.mean(axis=0).round(2))
print(X_test_scaled.mean(axis=0).round(2))

Output

[-0.  0.]
[ 0.2  -0.12]

Why: the means of the training data are 0, because its own means were subtracted. The means of the test data are close to 0 but not exactly 0, because the means of the training data were subtracted from it. That small difference is correct: it is what happens to every new car.

Problem 9: A model that needs scaling

Train an SGDRegressor on mileage_km, horsepower and weight_kg, once without scaling and once with a StandardScaler. Print for the first model whether its test score is below 0, and for the second its test score.

Idea. Gradient descent runs away on features of very different sizes (Parts 5 and 8).

Python
import pandas as pd
from sklearn.linear_model import SGDRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("cars.csv")
X = df[["mileage_km", "horsepower", "weight_kg"]]
y = df["price"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = SGDRegressor(random_state=0)
model.fit(X_train, y_train)
print(model.score(X_test, y_test) < 0)

Output

True

The same data and the same model, after scaling:

Python, continues from the cells above
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

model = SGDRegressor(random_state=0)
model.fit(X_train_scaled, y_train)
print(round(model.score(X_test_scaled, y_test), 3))

Output

0.823

Why: the same model and the same data: without scaling the training fails, with scaling it gives a usable score. Nothing about the cars changed, only the size of the numbers.

Problem 10: The logarithm of a skewed column

Compare two models with the test score: one with mileage_km and power_to_weight, and one with the logarithm of the mileage in the place of the mileage.

Idea. The logarithm changes the shape of a column with a long tail, and with it the model (Parts 6 and 8).

Python
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

df = pd.read_csv("cars.csv")
df["power_to_weight"] = df["horsepower"] / df["weight_kg"]
df["log_mileage"] = np.log(df["mileage_km"])
y = df["price"]

for columns in [["mileage_km", "power_to_weight"], ["log_mileage", "power_to_weight"]]:
    X_train, X_test, y_train, y_test = train_test_split(df[columns], y, test_size=0.2, random_state=42)
    model = LinearRegression()
    model.fit(X_train, y_train)
    print(columns[0], round(model.score(X_test, y_test), 3))

Output

mileage_km 0.856
log_mileage 0.93

Why: the score with the logarithm is clearly higher. The price of these cars follows the ratio of the mileages, and the logarithm turns ratios into the equal steps a straight line needs.

11Practice

Twelve problems. The first three are solved on paper. Problems 4 to 12 are one small project in Python on a new data file, motorcycles.csv. Under every problem there is a hint and a solution.

11.1Group A: by hand

  1. 1.Scale the values 5, 10, 15 and 25 with min-max scaling.

    Show a hint
    The minimum is 5, and the maximum minus the minimum is 20.
    Show one possible solution

    Answer: 0, 0.25, 0.5 and 1.

    5:5−520=010:10−520=0.2515:15−520=0.525:25−520=1\begin{aligned} 5:\quad & \frac{5 - 5}{20} = 0 \\[4pt] 10:\quad & \frac{10 - 5}{20} = 0.25 \\[4pt] 15:\quad & \frac{15 - 5}{20} = 0.5 \\[4pt] 25:\quad & \frac{25 - 5}{20} = 1 \end{aligned}
  2. 2.Scale the values 10, 20 and 30 with standard scaling. Use the standard deviation that divides by nn. Round to 3 decimals.

    Show a hint
    The mean is 20, and the squared deviations are 100, 0 and 100.
    Show one possible solution

    Answer: −1.225-1.225, 0 and 1.225.

    mean=10+20+303=20standard deviation=100+0+1003=66.67=8.16510:10−208.165=−1.22520:20−208.165=030:30−208.165=1.225\begin{aligned} \text{mean} &= \frac{10 + 20 + 30}{3} = 20 \\[6pt] \text{standard deviation} &= \sqrt{\frac{100 + 0 + 100}{3}} \\[4pt] &= \sqrt{66.67} = 8.165 \\[8pt] 10:\quad & \frac{10 - 20}{8.165} = -1.225 \\[4pt] 20:\quad & \frac{20 - 20}{8.165} = 0 \\[4pt] 30:\quad & \frac{30 - 20}{8.165} = 1.225 \end{aligned}
  3. 3.A MinMaxScaler was fitted on training data in which a column has the minimum 10 and the maximum 50. (a) What does the scaler make of the training value 30? (b) What does it make of the test value 60? (c) Is the result of (b) a mistake?

    Show a hint
    The test value is scaled with the minimum and the maximum of the training data.
    Show one possible solution

    Answer: (a) 0.5; (b) 1.25; (c) no.

    (a)30−1050−10=2040=0.5(b)60−1050−10=5040=1.25\begin{aligned} \text{(a)}\quad & \frac{30 - 10}{50 - 10} = \frac{20}{40} = 0.5 \\[6pt] \text{(b)}\quad & \frac{60 - 10}{50 - 10} = \frac{50}{40} = 1.25 \end{aligned}

    (c) No: the limits 0 and 1 belong to the training data. A test value that is larger than every training value lands above 1, and that is correct.

11.2Group B: one project in Python

The lesson worked with cars. The practice repeats its steps on a file you have not seen: motorcycles.csv describes 200 invented used motorcycles, and it is built like cars.csv.

The columns of motorcycles.csv
ColumnMeaning
bike_idthe identification number of the motorcycle in the list
owner_namethe first name of the owner
yearthe year in which the motorcycle was built
mileage_kmhow far it has driven, in km
engine_ccthe size of the engine in cubic centimetres
horsepowerthe power of the engine
weight_kgthe weight in kg
seatsthe number of seats
wheelsthe number of wheels
pricethe price in thousands: the target

The data file: motorcycles.csv

200 motorcycles, 10 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.

Download

Loading the table ...

The task: predict the price of a motorcycle from five features, with scaled data, and judge the model on test data. The steps continue from one another, like the cells of a notebook: every step uses what the steps before it created.

Steps 4 to 6: the columns

Drop what carries no information, create two features, look at the correlations.

  1. 4.Read motorcycles.csv into df and drop the columns bike_id, owner_name and wheels. Print the names of the remaining columns as a list.
    Show a hint
    df = pd.read_csv("motorcycles.csv"), df = df.drop(columns=["bike_id", "owner_name", "wheels"]), then print(df.columns.tolist()).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("motorcycles.csv")
    df = df.drop(columns=["bike_id", "owner_name", "wheels"])
    
    print(df.columns.tolist())

    Output

    ['year', 'mileage_km', 'engine_cc', 'horsepower', 'weight_kg', 'seats', 'price']
  2. 5.Create the columns age (2026 minus year) and power_to_weight (horsepower divided by weight_kg). Print the first three rows of these two columns, rounded to 3 decimals. This step continues from Step 4.
    Show a hint
    df["age"] = 2026 - df["year"]. Then print(df[["age", "power_to_weight"]].head(3).round(3)).
    Show one possible solution
    Python, continues from the cells above
    df["age"] = 2026 - df["year"]
    df["power_to_weight"] = df["horsepower"] / df["weight_kg"]
    
    print(df[["age", "power_to_weight"]].head(3).round(3))

    Output

       age  power_to_weight
    0   13            0.470
    1    8            0.421
    2    9            0.931
  3. 6.Print the correlation of every column with price, rounded to 2 decimals and sorted from the smallest to the largest. This step continues from Step 5.
    Show a hint
    print(df.corr()["price"].round(2).sort_values()).
    Show one possible solution
    Python, continues from the cells above
    print(df.corr()["price"].round(2).sort_values())

    Output

    weight_kg         -0.42
    age               -0.40
    mileage_km        -0.36
    seats              0.06
    year               0.40
    engine_cc          0.74
    horsepower         0.76
    power_to_weight    0.89
    price              1.00
    Name: price, dtype: float64

Steps 7 to 9: split, scale, train

The split first, then the scaler, then the model.

  1. 7.Make X from the columns age, mileage_km, horsepower, weight_kg and power_to_weight, and y from price. Split them into X_train, X_test, y_train, y_test with test_size=0.25 and random_state=7. Print the shapes of X_train and X_test on one line. This step continues from Step 5.
    Show a hint
    from sklearn.model_selection import train_test_split, then train_test_split(X, y, test_size=0.25, random_state=7). It returns four pieces.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.model_selection import train_test_split
    
    X = df[["age", "mileage_km", "horsepower", "weight_kg", "power_to_weight"]]
    y = df["price"]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=7)
    
    print(X_train.shape, X_test.shape)

    Output

    (150, 5) (50, 5)
  2. 8.Create a StandardScaler called scaler. Fit it on the training data, and make X_train_scaled and X_test_scaled. Print the standard deviations of the columns of X_train_scaled, rounded to 2 decimals, then the column means of X_test_scaled, rounded to 2 decimals. This step continues from Step 7.
    Show a hint
    scaler.fit_transform(X_train) for the training data and scaler.transform(X_test) for the test data. The standard deviations are .std(axis=0).round(2), the means .mean(axis=0).round(2). The training columns have the standard deviation 1; the means of the test data are close to 0, not exactly 0. If your numbers differ, check test_size=0.25 and random_state=7 in Step 7.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.preprocessing import StandardScaler
    
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    
    print(X_train_scaled.std(axis=0).round(2))
    print(X_test_scaled.mean(axis=0).round(2))

    Output

    [1. 1. 1. 1. 1.]
    [-0.26 -0.22  0.06 -0.06  0.12]
  3. 9.Train a LinearRegression called model on the scaled training data. Print the training score, then the test score, each rounded to 3 decimals. This step continues from Step 8.
    Show a hint
    model.fit(X_train_scaled, y_train), then model.score(X_train_scaled, y_train) and model.score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.linear_model import LinearRegression
    
    model = LinearRegression()
    model.fit(X_train_scaled, y_train)
    
    print(round(model.score(X_train_scaled, y_train), 3))
    print(round(model.score(X_test_scaled, y_test), 3))

    Output

    0.957
    0.962

Steps 10 to 12: read and compare

Comparable weights, a model trained by gradient descent, and a second scaler.

  1. 10.Print the weight of every feature of model next to its name, rounded to 2 decimals, one feature on a line. Which feature has the largest effect? This step continues from Step 9.
    Show a hint
    for name, weight in zip(X.columns, model.coef_): and inside the loop print(name, round(weight, 2)). The features were standardised, so the weight furthest from 0 has the largest effect.
    Show one possible solution
    Python, continues from the cells above
    for name, weight in zip(X.columns, model.coef_):
        print(name, round(weight, 2))

    Output

    age -0.91
    mileage_km -0.59
    horsepower 0.22
    weight_kg -0.13
    power_to_weight 2.52
  2. 11.Train an SGDRegressor with random_state=0 on the scaled training data and print its test score, rounded to 3 decimals. This step continues from Step 8.
    Show a hint
    from sklearn.linear_model import SGDRegressor. It is used exactly like LinearRegression: fit with the scaled training data, score with the scaled test data.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.linear_model import SGDRegressor
    
    sgd = SGDRegressor(random_state=0)
    sgd.fit(X_train_scaled, y_train)
    
    print(round(sgd.score(X_test_scaled, y_test), 3))

    Output

    0.953
  3. 12.Fit a MinMaxScaler on X_train and transform X_test with it. Print the smallest value of every column of the scaled test data, rounded to 2 decimals, then the largest value of every column. This step continues from Step 7.
    Show a hint
    .min(axis=0).round(2) and .max(axis=0).round(2) of the transformed test data. The values do not have to lie exactly between 0 and 1: the limits come from the training data.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.preprocessing import MinMaxScaler
    
    minmax = MinMaxScaler()
    minmax.fit(X_train)
    X_test_minmax = minmax.transform(X_test)
    
    print(X_test_minmax.min(axis=0).round(2))
    print(X_test_minmax.max(axis=0).round(2))

    Output

    [0.   0.01 0.09 0.03 0.04]
    [1.   0.81 1.04 1.03 0.94]

12Check yourself

Twelve questions. Every question has one right answer.

Question 1

1.Why is a column such as car_id dropped before modelling?

Question 2

2.Which created feature can raise the score of a linear regression the most?

Question 3

3.Why is the correlation better than the covariance for comparing features?

Question 4

4.Two features have a correlation of 0.95 with each other. What is this called, and what is usually done?

Question 5

5.A feature has a correlation of 0.02 with the target. Which statement is right?

Question 6

6.What does min-max scaling do with a column?

Question 7

7.The values 10, 20, 30 are scaled with min-max scaling. What does 20 become?

Question 8

8.A column has a few very large outliers. Which scaler is least disturbed by them?

Question 9

9.When is the logarithm a good transform?

Question 10

10.What is the difference between fit and transform of a scaler?

Question 11

11.Which lines scale the data correctly?

Question 12

12.LinearRegression gives a test score of 0.942 on unscaled features. What score does it give on the same features after standard scaling?

0 of 12 answered.

13Summary

Summary
StepWhat is doneWhy
Dropidentification numbers, names, constantsthey carry no information and invite overfitting
Createages, ratios, products, parts of datesto give the model what it cannot calculate itself
Selectdrop features with no relationship to the target, and one of every pair that says the samea simpler, more stable model with readable weights
Splittraining data and test databefore anything is learned from the rows
Scalefit on the training data, transform both partscomparable sizes, without data leakage
Modeltrain on the scaled training data, judge on the scaled test data
Summary
ScalerFormulaUse it when
MinMaxScalerx−min⁡max⁡−min⁡\frac{x - \min}{\max - \min}a range from 0 to 1 is needed and there are no strong outliers
StandardScalerx−meanstd\frac{x - \text{mean}}{\text{std}}the usual first choice
RobustScalerx−medianIQR\frac{x - \text{median}}{\text{IQR}}the column has outliers
np.loglog⁡(x)\log(x)the column has a long tail of large positive values
Summary
CodeWhat it does
df.drop(columns=["car_id"])removes columns
df["age"] = 2026 - df["year"]creates a feature
df.corr()["price"].sort_values()the correlation of every column with the target
scaler = StandardScaler()creates a scaler
X_train_scaled = scaler.fit_transform(X_train)learns from the training data and scales it
X_test_scaled = scaler.transform(X_test)scales the test data with the same numbers

Rules to keep

  1. Ask of every column whether it can sensibly influence the target. Drop the ones that cannot.
  2. Create features with knowledge of the subject, and keep the ones that raise the test score.
  3. Correlation with the target shows candidates; correlation between features shows doubles.
  4. Split first, then scale.
  5. fit_transform on the training data, transform on the test data, one scaler for both.
  6. Scaling changes the size of the numbers, not what they say. The logarithm also changes the shape.
  7. Standard scaling is the usual first choice; robust scaling for outliers; the logarithm for long tails.

What comes next

Every column of this lesson was a number, and the one text column was dropped. But a column such as the city of a flat or the fuel of a car is text that does carry information. Topic 25, feature engineering with the encoding of categorical variables and the handling of outliers, shows how such columns become numbers, and what to do with the extreme values that this lesson only scaled around.