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.
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example as a short cell on cars.csv, and the ten solved problems.
topic-24-feature-engineering-scaling.ipynb, 68 KB
Practice notebook
One small project in nine steps on motorcycles.csv, from reading the file to comparing two scalers, with a hint and a hidden solution for each step.
topic-24-practice.ipynb, 15 KB
Data file: the cars
240 invented used cars with 10 columns: the data of every example of the lesson.
cars.csv, 11 KB
Data file: the motorcycles
200 invented used motorcycles with 10 columns, built like cars.csv: the data of the practice.
motorcycles.csv, 8 KB
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.Why some columns must be dropped before modelling, and how to recognise them
- 2.How to create new features from existing columns with logic, and how to check whether they help
- 3.How covariance and correlation help to select features, and what multicollinearity is
- 4.Why numerical features are scaled, and which models need it
- 5.Four ways of scaling: min-max, standard, robust and the logarithm, and when each is used
- 6.The difference between
fit,transformandfit_transform - 7.Why the data is split before it is scaled, and what is done with the training data and with the test data
| Word | Meaning |
|---|---|
| feature engineering | the work on the input columns: dropping, creating, selecting and transforming them |
| feature creation | building a new column from existing ones: an age from a year, a ratio from two columns |
| feature selection | choosing which columns go into the model |
| multicollinearity | two or more features that say almost the same |
| scaling | changing the numbers of a column to a comparable size, without changing what they say |
| min-max scaling | squeezing 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 scaling | scaling with the median and the quartiles, which outliers hardly move |
| log transform | replacing a value by its logarithm, to pull in a long tail of large values |
fit | learn the numbers of a scaler (a minimum, a mean) from data |
transform | apply the learned numbers to data |
| data leakage | information 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.
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.5df.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.
| Column | Meaning |
|---|---|
car_id | the identification number of the car in the list |
owner_name | the first name of the owner |
year | the year in which the car was built |
mileage_km | how far the car has driven, in km |
engine_cc | the size of the engine in cubic centimetres |
horsepower | the power of the engine |
weight_kg | the weight of the car in kg |
doors | the number of doors |
wheels | the number of wheels |
price | the 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.
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.
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:
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_idhas 240 different values in 240 rows: one for each row. That is the mark of an identification number.wheelshas 1 value: a constant.owner_namehas 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
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
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
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:
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:
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:
In pandas a new column is one line (Topic 11):
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:
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
| Change | Test score | Why |
|---|---|---|
| the six numerical columns as they are | 0.879 | the starting point |
age in the place of year | 0.879 | no change: age is year turned round, and a linear model handles that itself |
adding power_to_weight | 0.929 | a division: the model could not build it from horsepower and weight_kg |
adding km_per_year too | 0.943 | another 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 (
agefromyear) 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
| Logic | Example |
|---|---|
| a difference from a reference point | the age from a year; the days since the last purchase |
| a ratio of two columns | power for the weight; price for every square metre; income for every member of a family |
| a product of two columns | the area from a length and a width; the total from a price and a number of units |
| a part of a date | the month, the day of the week (Topic 11) |
| a total or a mean of several columns | the total of three exam marks |
The question to ask is always: what would a person who knows the subject look at?
Try it yourself
age, (b) power_to_weight, (c) km_per_year.Show a hint
Show the solution
Answer: (a) 12; (b) 0.08; (c) 8,000.
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 is the covariance divided by the two standard deviations. It has no units and always lies between and 1. That makes it the tool for comparing columns.
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?
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. yearandagehave 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.
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 outside the diagonal:
engine_ccandhorsepower: 0.93. A larger engine has more power: the two columns say almost the same.power_to_weightwithweight_kg() and withhorsepower(0.65),mileage_kmwithageand withkm_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 ) is one feature too many.
The same table as a picture, the heatmap of Topic 12:
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()
4.4Step 3: the choice
engine_ccandhorsepowersay the same. Keep the one that is more strongly correlated with the price:horsepower(0.56 against 0.52). Dropengine_cc.doorshas a correlation of with the price. Drop it.yearis replaced byage.
Six features remain. Does the score suffer?
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
sales and four features. Their correlations with the target: adverts 0.81, discount , 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
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 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
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:
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
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:
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?
| Needs scaling | Does 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
SGDRegressor. (d) The test score of LinearRegression.Show a hint
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
The smallest value becomes 0, the largest becomes 1, and everything else lies in between.
- 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
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.
(scikit-learn divides the sum of squares by , the population formula of Topic 18, not by . 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
It uses the median and the interquartile range of Topic 18, which outliers hardly move.
- 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
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:
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 , 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
Min-max (from 0 to 1)
Standard (mean 0, standard deviation 1)
Robust (median 0, the middle half has the width 1)
Logarithm (large values are pulled in)
6.5The four side by side
| Min-max | Standard | Robust | Logarithm | |
|---|---|---|---|---|
| Formula | ||||
| Result | from 0 to 1 | mean 0, standard deviation 1 | median 0 | a new shape |
| Outliers | squeeze all other values | pull the mean and the spread | hardly matter | are pulled in |
| Changes the shape of the column | no | no | no | yes |
| In scikit-learn | MinMaxScaler | StandardScaler | RobustScaler | np.log (NumPy) |
| Use it when | a fixed range is needed; no strong outliers | the usual first choice | the column has outliers | the 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:
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:
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:
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.
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()
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()
The correlation with the price, before and after:
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
Scaled
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
Show a hint
Show the solution
Answer: (a) 0.25; (b) 0.5; (c) 1; (d) 3.
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.
fitlooks at data and learns the numbers the scaler needs: the minimum and the maximum of every column forMinMaxScaler, the mean and the standard deviation forStandardScaler, the median and the quartiles forRobustScaler. It changes nothing.transformapplies these learned numbers to data and returns the scaled values. It learns nothing.fit_transformdoes both, one after the other, on the same data. It is a shortcut.
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:
All the data
1. split it first
Training data
scaler.fit_transform
2. learn the numbers, apply them
model.fit
Test data
scaler.transform
3. apply the same numbers
model.score
- Split the data into a training part and a test part.
fitthe scaler on the training data only.transformthe 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.
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
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.
| Data | What to call | Why |
|---|---|---|
| training data | scaler.fit_transform(X_train) | learn the numbers and apply them |
| test data | scaler.transform(X_test) | apply the numbers of the training data |
| new data in real use | scaler.transform(X_new) | the same |
| never | scaler.fit(X_test), scaler.fit_transform(X_test), scaler.fit(X) before the split | the 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?
| Step | Before or after the split? | Why |
|---|---|---|
| dropping columns | before | it uses the meaning of a column, not its values |
creating a feature from the columns of the same row (age, power_to_weight) | before | every row is calculated from itself alone; nothing is learned from other rows |
| the logarithm of a column | before or after | every value is transformed by itself; nothing is learned |
| min-max, standard, robust scaling | fit after the split, on the training data | the 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
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
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
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
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
| Scaling | LinearRegression | SGDRegressor |
|---|---|---|
| none | 0.942 | fails (far below 0) |
| min-max | 0.942 | 0.935 |
| standard | 0.942 | 0.946 |
| robust | 0.942 | 0.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.
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:
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
| Step | Features | Test score |
|---|---|---|
| the numerical columns as they are (Part 1) | 6 | 0.879 |
| created features added (Part 3) | 8 | 0.943 |
| after selection (Part 4) | 6 | 0.942 |
| the logarithm of the mileage (Part 8) | 5 | 0.954 |
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
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, for distance and 0.9 for floor. Which feature has the largest effect?Show a hint
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 is furthest from 0: one standard deviation more distance takes away 7.5.
9Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| 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. (Part 6).
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. , with the standard deviation that divides by (Part 6).
Why: the scaled values add up to 0 (their mean is 0), and they are symmetric because the original values are. A value of 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).
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 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).
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).
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 (Part 4).
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 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).
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).
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).
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:
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).
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.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.
- 2.Scale the values 10, 20 and 30 with standard scaling. Use the standard deviation that divides by . 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: , 0 and 1.225.
- 3.A
MinMaxScalerwas 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.
(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.
| Column | Meaning |
|---|---|
bike_id | the identification number of the motorcycle in the list |
owner_name | the first name of the owner |
year | the year in which the motorcycle was built |
mileage_km | how far it has driven, in km |
engine_cc | the size of the engine in cubic centimetres |
horsepower | the power of the engine |
weight_kg | the weight in kg |
seats | the number of seats |
wheels | the number of wheels |
price | the 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.
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.
- 4.Read
motorcycles.csvintodfand drop the columnsbike_id,owner_nameandwheels. 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"]), thenprint(df.columns.tolist()).Show one possible solution
Pythonimport 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']
- 5.Create the columns
age(2026 minusyear) andpower_to_weight(horsepowerdivided byweight_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"]. Thenprint(df[["age", "power_to_weight"]].head(3).round(3)).Show one possible solution
Python, continues from the cells abovedf["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
- 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 aboveprint(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.
- 7.Make
Xfrom the columnsage,mileage_km,horsepower,weight_kgandpower_to_weight, andyfromprice. Split them intoX_train,X_test,y_train,y_testwithtest_size=0.25andrandom_state=7. Print the shapes ofX_trainandX_teston one line. This step continues from Step 5.Show a hint
from sklearn.model_selection import train_test_split, thentrain_test_split(X, y, test_size=0.25, random_state=7). It returns four pieces.Show one possible solution
Python, continues from the cells abovefrom 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)
- 8.Create a
StandardScalercalledscaler. Fit it on the training data, and makeX_train_scaledandX_test_scaled. Print the standard deviations of the columns ofX_train_scaled, rounded to 2 decimals, then the column means ofX_test_scaled, rounded to 2 decimals. This step continues from Step 7.Show a hint
scaler.fit_transform(X_train)for the training data andscaler.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, checktest_size=0.25andrandom_state=7in Step 7.Show one possible solution
Python, continues from the cells abovefrom 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]
- 9.Train a
LinearRegressioncalledmodelon 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), thenmodel.score(X_train_scaled, y_train)andmodel.score(X_test_scaled, y_test).Show one possible solution
Python, continues from the cells abovefrom 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.
- 10.Print the weight of every feature of
modelnext 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 loopprint(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 abovefor 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
- 11.Train an
SGDRegressorwithrandom_state=0on 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 likeLinearRegression:fitwith the scaled training data,scorewith the scaled test data.Show one possible solution
Python, continues from the cells abovefrom 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
- 12.Fit a
MinMaxScaleronX_trainand transformX_testwith 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 abovefrom 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.
0 of 12 answered.
13Summary
| Step | What is done | Why |
|---|---|---|
| Drop | identification numbers, names, constants | they carry no information and invite overfitting |
| Create | ages, ratios, products, parts of dates | to give the model what it cannot calculate itself |
| Select | drop features with no relationship to the target, and one of every pair that says the same | a simpler, more stable model with readable weights |
| Split | training data and test data | before anything is learned from the rows |
| Scale | fit on the training data, transform both parts | comparable sizes, without data leakage |
| Model | train on the scaled training data, judge on the scaled test data |
| Scaler | Formula | Use it when |
|---|---|---|
MinMaxScaler | a range from 0 to 1 is needed and there are no strong outliers | |
StandardScaler | the usual first choice | |
RobustScaler | the column has outliers | |
np.log | the column has a long tail of large positive values |
| Code | What 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
- Ask of every column whether it can sensibly influence the target. Drop the ones that cannot.
- Create features with knowledge of the subject, and keep the ones that raise the test score.
- Correlation with the target shows candidates; correlation between features shows doubles.
- Split first, then scale.
fit_transformon the training data,transformon the test data, one scaler for both.- Scaling changes the size of the numbers, not what they say. The logarithm also changes the shape.
- 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.