Module 3, topic 25, week 13, Tuesday
Feature engineering: encoding categorical variables, and handling outliers
What to do with values that lie far away from the rest, and how to turn text columns into numbers a model can use: the IQR rule and the z-score, mistakes against real extreme values, label, one-hot, target and frequency encoding, and the whole preparation of a data file in the right order.
Lesson notebook
The lesson as a Jupyter notebook: the explanations, every example as a short cell on laptops.csv, and the fourteen solved problems.
topic-25-feature-engineering-encoding-and-outliers.ipynb, 91 KB
Practice notebook
One small project in fourteen steps on phones.csv, from reading the file to the weights of the model, with a hint and a hidden solution for each step.
topic-25-practice.ipynb, 22 KB
Data file: the laptops
300 invented laptops with 15 columns: the data of every example of the lesson.
laptops.csv, 20 KB
Data file: the phones
260 invented phones with 15 columns, built like laptops.csv: the data of the practice.
phones.csv, 17 KB
Introduction: extreme values and text columns
The fifth lesson of Module 3, and the second one on feature engineering. Topic 24 worked on numerical columns: dropping the ones without information, creating and selecting features, and scaling. Two things were left open there. The data had a few extreme values that were only "scaled around", and the one text column was simply dropped. This lesson closes both gaps.
It has two halves. The first is about outliers: values that lie far away from the rest. You will learn how to find them with two rules (the IQR rule and the z-score), and, more important, what to do with them: whether to remove them at all, before or after the split, in the training data or in the test data, in the target or in the features, in every column or in selected ones. The second half is about encoding: turning text columns such as a brand or a condition into numbers a model can calculate with. There are several ways to do it, and the right one depends on the kind of column.
At the end everything of Topics 24 and 25 is put together in one recipe, from reading the file to the test score.
Everything is done on one data file, laptops.csv, with the tools you know.
You need: pandas (Topics 10 and 11), the quartiles, the interquartile range and the z-score (Topic 18), linear regression (Topic 22), the train/test split (Topic 23), and dropping, selecting and scaling features (Topic 24).
What you will learn
- 1.What an outlier is, and the difference between a mistake and a real extreme value
- 2.Two rules for finding outliers, the IQR rule and the z-score, and when each is used
- 3.Five ways of handling outliers: remove, repair, cap, transform, keep
- 4.Whether outliers are handled before or after the split, in the training or in the test data, in the target, and in which columns
- 5.Why a model needs numbers, and the kinds of categorical columns
- 6.Label (ordinal) encoding, one-hot (dummy) encoding, target encoding and frequency encoding, and which one fits which column
- 7.The whole preparation of a data file in the right order, from reading it to the test score
| Word | Meaning |
|---|---|
| outlier | a value that lies far away from the other values of its column |
| IQR rule | a value is an outlier when it lies more than 1.5 IQR below the first or above the third quartile |
| z-score | how many standard deviations a value lies from the mean |
| removing (trimming) | deleting the rows with outliers |
| capping | replacing a value beyond a limit by the limit itself |
| categorical variable | a column whose values are groups, not amounts: a brand, a colour, a condition |
| nominal | categories without an order: brand, type, city |
| ordinal | categories with an order: used, good, like new, new |
| encoding | turning categories into numbers |
| label (ordinal) encoding | one whole number for every category |
| one-hot (dummy) encoding | one column of 0 and 1 for every category |
| target encoding | every category is replaced by the mean of the target in that category |
| frequency encoding | every category is replaced by how often it appears |
| cardinality | the number of different categories of a column |
1The data
laptops.csv describes 300 invented laptops that a shop sells, new and used. The target is the price in manat.
import pandas as pd
df = pd.read_csv("laptops.csv")
print(df.shape)
print(df.head(3).T)Output
(300, 15)
0 1 2
laptop_id 3001 3002 3003
seller_name Orkhan Tural Nigar
currency AZN AZN AZN
brand Boreal Altra Delto
type office gaming office
condition good new good
touchscreen no no yes
ram_gb 32 8 16
storage_gb 1024 2048 512
screen_inch 15.6 13.3 14.0
screen_cm 39.6 33.8 35.6
weight_kg 1.91 2.31 2.16
usb_ports 2 3 4
age_months 6 14 9
price 1800 2580 1510Every code block of this lesson is a cell that continues from the cells above it, like a notebook: df stays in memory.
| Column | Meaning |
|---|---|
laptop_id | the identification number of the laptop in the list |
seller_name | the first name of the person who sold it to the shop |
currency | the currency of the price |
brand | the maker (12 invented brands) |
type | what the laptop is built for: office, gaming or ultrabook |
condition | used, good, like new or new |
touchscreen | yes or no |
ram_gb | the memory in gigabytes |
storage_gb | the size of the disk in gigabytes |
screen_inch | the size of the screen in inches |
screen_cm | the size of the screen in centimetres |
weight_kg | the weight in kilograms |
usb_ports | the number of USB ports |
age_months | the age in months (0 for a new laptop) |
price | the price in manat: the target |
The data file: laptops.csv
300 laptops, 15 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
Six columns are text, not numbers:
print(df.select_dtypes(exclude="number").columns.tolist())Output
['seller_name', 'currency', 'brand', 'type', 'condition', 'touchscreen']
select_dtypes(exclude="number") keeps the columns that are not numbers. A model cannot use them as they are. Three of them will be dropped, and the other three, with touchscreen, are the subject of the second half of the lesson.
2First, the columns that carry no information
This is the first step of Topic 24, and it comes first here too.
print(df.nunique())Output
laptop_id 300 seller_name 20 currency 1 brand 12 type 3 condition 4 touchscreen 2 ram_gb 4 storage_gb 5 screen_inch 4 screen_cm 4 weight_kg 152 usb_ports 3 age_months 60 price 160 dtype: int64
laptop_idhas 300 values in 300 rows: an identification number.currencyhas 1 value: a constant.seller_nameis a name. It has 20 values, like a real feature could have, so only its meaning tells you that it says nothing about the laptop.
df = df.drop(columns=["laptop_id", "seller_name", "currency"])
print(df.shape)Output
(300, 12)
The other text columns stay. A brand, a type and a condition do say something about a laptop, and so they must not be dropped: they must be turned into numbers. That is the difference between a column without information and a column whose information is not a number yet.
3Outliers: what they are and why they matter
3.1A look at two columns
print(df[["weight_kg", "price"]].describe().round(1))Output
weight_kg price count 300.0 300.0 mean 41.9 1769.3 std 291.7 2335.8 min 0.9 190.0 25% 1.5 1120.0 50% 1.9 1410.0 75% 2.3 1812.5 max 2770.0 25860.0
Read the two columns from the top to the bottom. Three quarters of the laptops weigh 2.3 kg or less, and the heaviest one weighs 2,770 kg. Three quarters cost about 1,810 manat or less, and the most expensive one costs 25,860. Something is wrong at the upper end of both columns.
An outlier is a value that lies far away from the other values of its column.
3.2Two kinds of outliers
This is the most important idea of the first half of the lesson: an outlier is not automatically a mistake.
| A mistake | A real extreme value | |
|---|---|---|
| What it is | a value that is wrong: a typing error, a wrong unit, a broken sensor | a value that is true, only rare |
| Example | a laptop that weighs 2,770 kg (the weight was typed in grams) | a laptop with 32 GB of memory and a disk of 2,048 GB that costs 3,290 |
| Does it describe the real world? | no | yes |
| What to do | repair it, or remove the row | think first; very often keep it |
A rule can find values that lie far away. It cannot tell you which of the two kinds a value is. That decision needs a person who knows what the column means.
3.3Why outliers matter
1. They pull the mean and the standard deviation. The mean and the median of the weight:
print(round(df["weight_kg"].mean(), 2))
print(df["weight_kg"].median())Output
41.94 1.91
The median says that a typical laptop weighs 1.91 kg. The mean says about 42 kg: a handful of wrong values are enough to make it useless (Topic 18). Everything that is built on the mean and the standard deviation suffers with it, and that includes standard scaling (Topic 24).
2. They pull the model. A linear regression minimises the squared errors (Topic 22). A point that lies far away has a huge squared error, so the line turns towards it and gives up the fit for many ordinary points.
Without the outlier
the line follows the points
With one outlier
the line turns towards it
A first model shows how bad it can get. It uses the numerical columns as they are. (screen_cm is left out: it repeats screen_inch. Part 10 comes back to it.)
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
numbers = ["ram_gb", "storage_gb", "screen_inch", "weight_kg", "usb_ports", "age_months"]
train, test = train_test_split(df, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(train[numbers], train["price"])
print(round(model.score(train[numbers], train["price"]), 3))
print(round(model.score(test[numbers], test["price"]), 3))Output
0.05 -0.618
Two things are new in this cell, and both will be used all through the lesson.
train_test_split(df, ...)gets one table and returns two: the training rows and the test rows, each with all its columns. It is the same split as in Topic 23, only the features and the target stay together in one table. That is practical when rows have to be removed or columns have to be added later.- The features are then
train[numbers], and the target istrain["price"].
The scores: 0.05 on the training data and a negative score on the test data. A negative means that the model predicts worse than a model that always answers with the mean price (Topic 22). With these outliers in the data the model is useless.
3. They disturb scaling. Topic 24 showed it: with min-max scaling one extreme value presses all the others into a corner.
We will need the recipe of this cell many times. To keep the cells short, it goes into a small function (Topic 3):
def scores(train, test, columns):
model = LinearRegression()
model.fit(train[columns], train["price"])
print(round(model.score(train[columns], train["price"]), 3))
print(round(model.score(test[columns], test["price"]), 3))
scores(train, test, numbers)Output
0.05 -0.618
The same two numbers: the function does exactly what the cell above did.
Try it yourself
Show a hint
Show the solution
Answer: (a) a mistake; (b) real; (c) a mistake; (d) real.
Nobody is 230 years old, and no place on Earth has degrees: both values are wrong. (Numbers such as are often written by a machine to say "no measurement".) A director's salary and a large order from a school are rare, but they are true, and a model for salaries or orders will meet such cases again.
4Finding outliers: the IQR rule and the z-score
4.1Look first
Before any rule, look at the column: describe() as above, or a picture. The box plot of Topic 12 was made for this: it draws every value beyond its whiskers as a single point.
import matplotlib.pyplot as plt
import seaborn as sns
sns.boxplot(x=df["price"])
plt.title("The prices of the 300 laptops")
plt.show()
The box with the middle half of the prices is squeezed to the left edge, and a row of single points stretches far to the right. Now the two rules that put numbers on "far away".
4.2The IQR rule
The interquartile range is the width of the middle half of the data (Topic 18):
The rule draws two limits, 1.5 IQR outside the quartiles:
A value below the lower limit or above the upper limit is called an outlier. The whiskers of a box plot end at these limits.
By hand. Nine values, already sorted:
With the rule of Topic 18, the quartile for the share stands at the position :
Eight values lie between 7 and 23. The value 65 lies above 23: it is an outlier.
In pandas, on the prices:
q1 = df["price"].quantile(0.25)
q3 = df["price"].quantile(0.75)
iqr = q3 - q1
lower = q1 - 1.5 * iqr
upper = q3 + 1.5 * iqr
print(q1, q3, iqr)
print(lower, upper)Output
1120.0 1812.5 692.5 81.25 2851.25
Change it and run: replace 1.5 by 3 in both lines and run: the upper limit moves out to 3,890, a limit for values that are "far out".
quantile(0.25) is the first quartile and quantile(0.75) the third (Topic 18). No price lies below the lower limit, so only the upper limit matters here. The rows above it:
outliers = df[df["price"] > upper]
print(len(outliers))
print(outliers[["brand", "type", "ram_gb", "storage_gb", "price"]].sort_values("price"))Output
9
brand type ram_gb storage_gb price
212 Helio gaming 32 1024 3000
32 Ixon ultrabook 32 2048 3170
135 Delto ultrabook 16 2048 3290
166 Altra office 8 256 9790
214 Delto gaming 8 512 12450
59 Lumo office 16 512 16450
220 Juno ultrabook 16 128 17480
294 Helio ultrabook 8 256 19260
36 Delto ultrabook 32 1024 25860Nine laptops. Now read them, because the rule has done its part and the thinking begins.
- The first three cost about 3,000 to 3,300. They have 16 or 32 GB of memory and a large disk. These are simply the best laptops of the shop: real extreme values.
- The other six cost between 9,790 and 25,860. An office laptop with 8 GB for 9,790? An ultrabook with a small disk for 17,480? Every one of these prices is about ten times what such a laptop costs. Somebody typed one zero too many: mistakes.
There is a wide gap between the two groups (from 3,290 to 9,790), and it separates them cleanly.
4.3The z-score
The z-score says how many standard deviations a value lies above or below the mean (Topic 18; it is also the formula of standard scaling in Topic 24):
In a column with the shape of a bell almost all values (99.7 percent) have a z-score between and 3 (Topic 17). So the usual rule is: a value with a z-score below or above 3 is an outlier. Some people use 2.5 or 2 as a stricter limit.
By hand, for the same nine values:
The z-score of 65 is 2.798. That is below 3: the z-score rule does not call 65 an outlier, although it is more than three times as large as every other value.
The reason is the weak point of this rule. The mean and the standard deviation are calculated with the outlier in the data, and the outlier pulls both: the mean rose to 20, above eight of the nine values, and the standard deviation grew to 16. The outlier hides itself. This is called masking, and it is worst in small data sets. The quartiles of the IQR rule did not move at all.
In pandas:
z = (df["price"] - df["price"].mean()) / df["price"].std()
print((z.abs() > 3).sum())
print(df[z.abs() > 3]["price"].sort_values().tolist())Output
6 [9790, 12450, 16450, 17480, 19260, 25860]
z.abs() takes away the sign, so that one comparison covers both sides. (std() of pandas divides by ; with hundreds of rows the difference to dividing by does not matter.)
The z-score marks six prices, and they are exactly the six mistakes. The IQR rule marked nine: the same six and the three real, expensive laptops.
4.4The two rules on the weight
q1 = df["weight_kg"].quantile(0.25)
q3 = df["weight_kg"].quantile(0.75)
upper_weight = q3 + 1.5 * (q3 - q1)
z = (df["weight_kg"] - df["weight_kg"].mean()) / df["weight_kg"].std()
print(round(upper_weight, 2))
print(df[df["weight_kg"] > upper_weight]["weight_kg"].sort_values().tolist())
print(df[z.abs() > 3]["weight_kg"].sort_values().tolist())Output
3.58 [900.0, 1960.0, 1970.0, 2200.0, 2220.0, 2770.0] [1960.0, 1970.0, 2200.0, 2220.0, 2770.0]
The IQR rule puts the upper limit at 3.58 kg and finds six weights above it: 900, 1,960, 1,970, 2,200, 2,220 and 2,770. No laptop weighs a ton. The weights were typed in grams. The z-score finds only five of them: the value 900 has a z-score just below 3, because the six wrong values themselves blew up the standard deviation to almost 300. Masking again, this time on real data.
4.5Which rule, and when?
| IQR rule | z-score | |
|---|---|---|
| Built on | the quartiles | the mean and the standard deviation |
| Moved by the outliers themselves | hardly | yes: masking |
| Shape of the column | any shape; also skewed columns | meant for columns with the shape of a bell |
| Small data sets | works | weak: in 9 values no z-score can reach 3 |
| Usual limit | 1.5 IQR (3 IQR for "far out") | 3 (sometimes 2.5 or 2) |
| Typical weakness | in a skewed column it marks many real values | misses outliers that hide behind each other |
- The IQR rule is the usual first choice. It needs no assumption about the shape of the column, the outliers do not disturb it, and it is the rule behind the box plot, so the picture and the numbers agree.
- The z-score is used when a column has roughly the shape of a bell and there are many rows: measurements, heights, test results, the errors of a model. It is also the language of many fields ("a three sigma event"), and it gives a number for how far away a value is, not only yes or no.
- Both are rules of thumb, not judges. They point at candidates. Whether a candidate is a mistake or a real value is decided by looking at it.
The nine values of the example. Move the ninth one away from the others and watch the two rules.
IQR rule: the limits are 7 and 23. The value 65 is an outlier.
z-score: mean 20, standard deviation 16.08, so z = (65 − 20) / 16.08 = 2.798: not beyond 3.
The limits of the IQR rule do not move, however far the value goes. The z-score hardly grows: the value pulls the mean and the standard deviation along with it. Among nine values no z-score can pass 2.83, so this rule never marks the value. That is masking.
Try it yourself
weight_kg and print how many of them are above 2.5.Show a hint
z = (df["weight_kg"] - df["weight_kg"].mean()) / df["weight_kg"].std(), then print((z > 2.5).sum()).Show the solution
import pandas as pd
df = pd.read_csv("laptops.csv")
z = (df["weight_kg"] - df["weight_kg"].mean()) / df["weight_kg"].std()
print((z > 2.5).sum())Output
6
Try it yourself
Show a hint
Show the solution
Answer: (a) 10; (b) 90; (c) yes; (d) 3.5.
The value 95 lies above 90, so the IQR rule calls it an outlier. A z-score of 3.5 is beyond 3, so the z-score rule would mark the value 85 in the second column.
5What to do with outliers
5.1Five options
| Option | What is done | Fits when |
|---|---|---|
| Repair | the wrong value is replaced by the right one | the value is a mistake and its cause is known (a wrong unit, a shifted decimal point) |
| Remove | the row is deleted | the value is a mistake and the right value is not known; there are few such rows |
| Cap | a value beyond a limit is replaced by the limit | the value is real but so extreme that it would dominate; the row itself is worth keeping |
| Transform | the whole column is changed, for example with the logarithm (Topic 24) | the column has a long tail of real, large values |
| Keep | nothing | the value is real, and the model should know such cases |
Removing is only one of five, and it is the one that throws information away. The questions below decide which option fits.
5.2Question 1: is it a mistake or a real value?
Everything else depends on this answer.
- A mistake does not describe the world. A model that learns from it learns something false, and a test that contains it measures something false. Mistakes are cleaned in the whole table, and it is done before the split. This is data cleaning, the same kind of work as fixing a wrong date in Topic 11.
- A real extreme value is part of the world the model will work in. The rules for it are stricter, and they follow from Topic 23: see Questions 2 and 3.
5.3Cleaning the mistakes
The prices. The true prices of the six laptops are not known for certain: probably a tenth, but nobody can check. So the rows are removed. The limit comes from looking at the data: the real prices end at 3,290 and the mistakes begin at 9,790.
df = df[df["price"] < 9000]
print(df.shape)Output
(294, 12)
Six rows less: 294 laptops. The model again, with the same recipe:
train, test = train_test_split(df, test_size=0.2, random_state=42)
scores(train, test, numbers)Output
0.419 0.405
From a negative test score to 0.405. Six rows out of 300 had ruined the model.
The weights. Here the cause is known: grams in the place of kilograms. So the values can be repaired, and no row is lost: every weight above 10 is divided by 1,000.
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
print(df["weight_kg"].describe().round(2))Output
count 294.00 mean 1.92 std 0.56 min 0.90 25% 1.48 50% 1.91 75% 2.30 max 3.33 Name: weight_kg, dtype: float64
df.loc[rows, column] = ... changes the column only in the chosen rows (Topic 11). The weights now run from 0.9 to 3.33 kg, and the mean (1.92) and the median (1.91) agree again.
train, test = train_test_split(df, test_size=0.2, random_state=42)
scores(train, test, numbers)Output
0.542 0.527
| The data | Test score |
|---|---|
| as it came | |
| the six wrong prices removed | 0.405 |
| the six wrong weights repaired too | 0.527 |
Twelve wrong values in a table of 300 rows made the difference between a useless model and a usable one. The score is still not high, but for another reason: the model has not seen the brand, the type and the condition yet. That is the second half of the lesson.
5.4Question 2: before or after the split?
It depends on what is done.
- Cleaning mistakes with a fixed rule: before the split, in the whole table. "No laptop weighs more than 10 kg" is knowledge about laptops. It was not learned from the rows, and it would be applied in the same way to every laptop that arrives tomorrow.
- Everything that learns limits from the data: after the split, from the training data only. The IQR limits and the z-scores are calculated from the rows, exactly like the minimum and the maximum of a scaler in Topic 24. If they are calculated from all the rows, the test rows have helped to decide which training rows are removed: data leakage. So: split first, calculate the limits on the training data, and use these same limits wherever they are needed.
The question to ask is the one of Topic 24: does the step learn something from the rows?
Now the three real, expensive laptops. The data is already split. The limits come from the training data:
q1 = train["price"].quantile(0.25)
q3 = train["price"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)
print(upper)
print((train["price"] > upper).sum())
print((test["price"] > upper).sum())Output
2832.5 3 0
In the training data three prices lie above the limit of 2,832.5; in the test data none.
Removing them from the training data, and the scores:
train_removed = train[train["price"] <= upper]
print(len(train), len(train_removed))
scores(train_removed, test, numbers)Output
235 232 0.493 0.522
Capping them: clip(upper=...) replaces every value above the limit by the limit.
train_capped = train.copy()
train_capped["price"] = train_capped["price"].clip(upper=upper)
print(train["price"].max(), train_capped["price"].max())
scores(train_capped, test, numbers)Output
3290 2832.5 0.53 0.528
train.copy() makes a copy, so that train itself stays as it is.
| The training data | Test score |
|---|---|
| all rows kept | 0.527 |
| the three most expensive laptops removed | 0.522 |
| their prices capped at the limit | 0.528 |
Almost nothing changes. That is the usual result for real extreme values that are not very far away: the model can live with them, and removing them brings nothing. The large gains of this lesson came from the mistakes. So these three laptops stay in the data.
5.5Question 3: in the training data, in the test data, or in both?
| Mistakes | Real extreme values | |
|---|---|---|
| Training data | clean them | may be removed or capped, if that helps |
| Test data | clean them | leave them in |
- Never remove real extreme values from the test data. The test data stands for the laptops that will arrive tomorrow (Topic 23), and expensive laptops will arrive too. The model cannot refuse to price them. A test without them gives a score that is too flattering: it measures the model only on the easy cases.
- Never remove outliers only from the test data. The model would still be trained on them and judged without them: the worst of both.
- If a feature is capped, the limits of the training data are applied to the test data too (
clipwith the same numbers), exactly as a fitted scaler is applied to the test data. The row stays; only its extreme value is pulled in. - There is one honest exception: you decide that the model is not meant for such cases ("this model prices laptops up to 3,000; more expensive ones are priced by hand"). Then they leave both parts, and the decision is written down as a limit of the model.
5.6Question 4: outliers in the target?
The target is the column the model learns to predict, so it deserves the most care.
- A mistake in the target is the most harmful kind: the model learns a wrong answer, and a test row with a wrong answer punishes even a perfect prediction. The six wrong prices showed it. Clean them, in the whole table.
- A real extreme target value may be removed from the training data when it damages the fit for the ordinary cases. It stays in the test data.
- For a target with a long tail of real, large values (prices of houses, incomes), a common alternative to removing is to train on the logarithm of the target. The idea is the one of the log transform in Topic 24.
- Never change the targets of the test data. They are the truth the model is measured against.
5.7Question 5: in every column, or in selected ones?
In selected ones. Here is what the IQR rule would do in each numerical column of the training data:
for name in ["ram_gb", "storage_gb", "screen_inch", "weight_kg", "usb_ports", "age_months", "price"]:
q1 = train[name].quantile(0.25)
q3 = train[name].quantile(0.75)
low = q1 - 1.5 * (q3 - q1)
high = q3 + 1.5 * (q3 - q1)
print(name, ((train[name] < low) | (train[name] > high)).sum())Output
ram_gb 25 storage_gb 38 screen_inch 0 weight_kg 0 usb_ports 0 age_months 0 price 3
The rule would throw away 25 laptops for their memory and 38 for their disk. Look at why. Most laptops have 8 or 16 GB of memory, so the upper limit lies at 28, and every laptop with 32 GB counts as an "outlier". The same happens to the disks of 1,024 and 2,048 GB. These are not mistakes and not even rare accidents. They are the upper models of the shop.
Applied blindly to every column, the rule would remove about a quarter of the training data, and afterwards the model would never have seen a laptop with 32 GB. The rules for choosing the columns:
- Columns with continuous measurements (a weight, a price, an area, an income) are the place for outlier rules.
- Columns with a few fixed values (the memory, the number of rooms, the number of doors) are not: there the quartiles sit on the common values, and every less common value is marked.
- Never on columns of 0 and 1, on encoded categories, or on identification numbers.
- Every column in which rows are removed costs rows. Check how many rows are left.
5.8The answers side by side
| Question | Answer |
|---|---|
| Is every outlier a mistake? | No. A rule finds candidates; you decide what they are. |
| Mistakes | Repair them if the cause is known, remove the rows if not. In the whole table, before the split. |
| Real extreme values | Often keep them. If they are handled: after the split, with limits from the training data. |
| Remove them from the test data? | No. The test data stands for the real world. |
| Remove them only from the test data? | Never. |
| Outliers in the target | Mistakes: clean them everywhere. Real ones: at most out of the training data. |
| Every column? | No. Selected columns with continuous measurements. |
| Other ways than removing | Cap, transform with the logarithm, a robust scaler (Topic 24), or keep. |
An outlier was found. What do you do with it?
1 of 8
A laptop weight of 1,850 in a column of kilograms. The seller typed grams.
Try it yourself
weight_kg above 10 by 1,000. Print the mean of the column, then its median, each rounded to 2 decimals.Show a hint
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000, then print(round(df["weight_kg"].mean(), 2)) and the same with median().Show the solution
import pandas as pd
df = pd.read_csv("laptops.csv")
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
print(round(df["weight_kg"].mean(), 2))
print(round(df["weight_kg"].median(), 2))Output
1.91 1.91
Try it yourself
rooms with the values 1 to 5? (d) A table has heights in metres, and a few were typed in centimetres. When are they repaired?Show a hint
Show the solution
Answer: (a) from the training rows; (b) it stays; (c) no; (d) before the split, in the whole table.
(a) Limits are numbers learned from the data, like the numbers of a scaler. (b) Expensive laptops will arrive in real use too; a test without them would flatter the model. (c) In a column with a few fixed values the quartiles sit on the common values, and every less common value would be marked. (d) "A height above 3 is in centimetres" is knowledge about the column, not something learned from the rows.
6Categorical variables: why they are encoded
6.1A model calculates
A linear regression multiplies every feature by a weight and adds the results. It cannot multiply the word "gaming" by 3.2.
model = LinearRegression()
model.fit(train[["ram_gb", "type"]], train["price"])Error
ValueError: could not convert string to float: 'office'
Nearly every model has this limit. A column of words must become one or several columns of numbers before training. That is encoding.
It is worth the work, because the words carry information. The mean price in each group:
print(df.groupby("type")["price"].mean().round(0))
print(df.groupby("touchscreen")["price"].mean().round(0))Output
type gaming 1384.0 office 1273.0 ultrabook 1865.0 Name: price, dtype: float64 touchscreen no 1414.0 yes 1583.0 Name: price, dtype: float64
An ultrabook costs almost 600 manat more than an office laptop on average, and a touchscreen adds about 170. The model of Part 5 knew none of this.
6.2The kinds of categorical columns
for name in ["touchscreen", "condition", "type", "brand"]:
print(name, df[name].nunique(), df[name].unique()[:4].tolist())Output
touchscreen 2 ['no', 'yes'] condition 4 ['good', 'new', 'used', 'like new'] type 3 ['office', 'gaming', 'ultrabook'] brand 12 ['Boreal', 'Altra', 'Delto', 'Evora']
Every line shows a column, the number of its different values and up to four of them. The four columns are four different cases:
| Column | Values | Kind | Encoding |
|---|---|---|---|
touchscreen | 2: yes, no | binary: two values | 0 and 1 |
condition | 4: used, good, like new, new | ordinal: the values have an order | label (ordinal) encoding |
type | 3: office, gaming, ultrabook | nominal: no order, few values | one-hot encoding |
brand | 12 | nominal: no order, many values | target or frequency encoding (or one-hot) |
Two questions decide the encoding: do the categories have an order? and how many are there? The number of different categories of a column is its cardinality.
Which encoding fits the column?
1 of 8
gift_wrap: yes, no
7Label encoding: one number for every category
7.1Two values: 0 and 1
df["touchscreen"] = df["touchscreen"].map({"no": 0, "yes": 1})
print(df["touchscreen"].value_counts())Output
touchscreen 0 213 1 81 Name: count, dtype: int64
map with a dictionary replaces every value by the one the dictionary gives for it (Topic 11). For a column with two values this is all that is needed: 1 means "has it", 0 means "does not". The weight of this feature will then say how much a touchscreen adds to the price.
7.2Ordered categories: numbers in the right order
Label encoding gives every category a whole number. For an ordinal column the numbers follow the order of the categories. For this reason it is also called ordinal encoding.
order = {"used": 0, "good": 1, "like new": 2, "new": 3}
df["condition"] = df["condition"].map(order)
print(df["condition"].value_counts().sort_index())Output
condition 0 74 1 94 2 61 3 65 Name: count, dtype: int64
The order is written by you, in the dictionary. Now "new" (3) is larger than "used" (0), which is true, and a model can use the column like any number: one weight for every step up.
The numbers also say that every step is equally large: from used to good is as far as from like new to new. That is an assumption. It is usually close enough, and when it is clearly wrong, one-hot encoding (Part 8) is the alternative.
The model with the two new columns:
features = numbers + ["condition", "touchscreen"]
train, test = train_test_split(df, test_size=0.2, random_state=42)
scores(train, test, features)Output
0.674 0.699
Change it and run: take "condition" out of the list and run: the test score falls to 0.551.
The test score rises from 0.527 to 0.699.
Both columns were encoded before the split. That is allowed here, because a dictionary written by hand learns nothing from the rows: "used" becomes 0 for every laptop, whatever the other rows contain.
7.3The encoders of scikit-learn
scikit-learn has an encoder for this, OrdinalEncoder. It is used like a scaler, with fit and transform. The order is given as a list:
from sklearn.preprocessing import OrdinalEncoder
raw = pd.read_csv("laptops.csv")
encoder = OrdinalEncoder(categories=[["used", "good", "like new", "new"]])
codes = encoder.fit_transform(raw[["condition"]])
print(raw["condition"].head(4).tolist())
print(codes[:4].ravel())Output
['good', 'new', 'good', 'new'] [1. 3. 1. 3.]
raw is a fresh copy of the file, because df["condition"] is already encoded. The encoder wants a table, so the column is taken with two pairs of brackets. ravel() only prints the result on one line.
Without the list of categories the encoder puts them in the order of the alphabet:
encoder = OrdinalEncoder()
encoder.fit(raw[["condition"]])
print(encoder.categories_)Output
[array(['good', 'like new', 'new', 'used'], dtype=object)]
good = 0, like new = 1, new = 2, used = 3: "used" would be the best condition. The order of the alphabet is almost never the order of the meaning. Always give the order yourself.
There is also a LabelEncoder. It numbers the categories in the order of the alphabet too, and it is meant for the target of a classification (Topic 27), not for features.
7.4The danger: numbers invent an order
Label encoding is right for ordinal columns. For a nominal column it does harm. Try it with the type, encoded in the order of the alphabet:
trial = df.copy()
trial["type_code"] = trial["type"].map({"gaming": 0, "office": 1, "ultrabook": 2})
train, test = train_test_split(trial, test_size=0.2, random_state=42)
scores(train, test, features + ["type_code"])Output
0.675 0.695
Change it and run: change the dictionary to {"office": 0, "gaming": 1, "ultrabook": 2} and run: with an order that follows the prices the score rises to 0.749. It is still below one-hot encoding (Part 8).
trial is a copy of the table, so df itself stays as it is. The test score is 0.695. Without the column it was 0.699: the type, encoded like this, is worth nothing.
The numbers tell the model that an office laptop lies exactly between a gaming laptop and an ultrabook, and that an ultrabook is "twice an office laptop". None of that means anything. In the prices the office laptops are the cheapest of the three, so a single weight for this column cannot follow them.
Try it yourself
condition in its order (used 0, good 1, like new 2, new 3) and print the mean of the encoded column, rounded to 2 decimals.Show a hint
df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3}), then print(round(df["condition"].mean(), 2)).Show the solution
import pandas as pd
df = pd.read_csv("laptops.csv")
df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3})
print(round(df["condition"].mean(), 2))Output
1.4
Try it yourself
size has the values S, M, L and XL. (a) With an ordinal encoding that starts at 0, which number does S get? (b) Which number does XL get? (c) An encoder that sorts by the alphabet puts the values in the order L, M, S, XL. Which number does S get then? (d) Is label encoding right for a column colour with the values red, blue and green?Show a hint
Show the solution
Answer: (a) 0; (b) 3; (c) 2; (d) no.
In the right order S = 0, M = 1, L = 2, XL = 3. In the order of the alphabet L = 0, M = 1, S = 2, XL = 3: the smallest size would lie above the large one. Colours have no order at all, so any numbers would invent one.
8One-hot encoding: one column for every category
8.1The idea
One-hot encoding makes a new column for every category. A row has a 1 in the column of its own category and a 0 in all the others. These columns are called dummy variables, and so the method is also called dummy encoding.
type
type_gaming
type_office
type_ultrabook
office
0
1
0
gaming
1
0
0
ultrabook
0
0
1
office
0
1
0
No category is larger than another, and no order is invented. The model gets one weight for every category: "a gaming laptop costs this much more".
8.2In pandas
print(pd.get_dummies(df["type"], dtype=int).head(4))Output
gaming office ultrabook 0 0 1 0 1 1 0 0 2 0 1 0 3 0 1 0
pd.get_dummies makes the columns. dtype=int asks for 0 and 1; without it pandas writes False and True.
8.3One column can go: drop_first
Look at the three columns. If a laptop is not a gaming laptop and not an ultrabook, it must be an office laptop: the third column can always be calculated from the other two. It is a perfect case of the multicollinearity of Topic 24, and it has a name of its own, the dummy variable trap. The cure is to drop one of the columns:
df = pd.get_dummies(df, columns=["type"], drop_first=True, dtype=int)
print(df.columns.tolist())
print(df[["type_office", "type_ultrabook"]].head(4))Output
['brand', 'condition', 'touchscreen', 'ram_gb', 'storage_gb', 'screen_inch', 'screen_cm', 'weight_kg', 'usb_ports', 'age_months', 'price', 'type_office', 'type_ultrabook'] type_office type_ultrabook 0 1 0 1 0 0 2 1 0 3 1 0
Change it and run: take drop_first=True out and run: the table gets a third column, type_gaming.
With columns=["type"] pandas encodes that column inside the table and removes the original. drop_first=True drops the first category in the order of the alphabet, gaming. A gaming laptop is now the row with 0 in both columns: it is the reference, and the weights of the other two columns say how much an office laptop or an ultrabook differs from a gaming laptop.
For a linear model use drop_first=True. The predictions and the score are the same with all three columns; the weights are only readable with one column dropped.
8.4The score
features = numbers + ["condition", "touchscreen", "type_office", "type_ultrabook"]
train, test = train_test_split(df, test_size=0.2, random_state=42)
scores(train, test, features)Output
0.805 0.76
From 0.699 to 0.760. The three ways of handling the column, side by side:
| How type is given to the model | Test score |
|---|---|
| not at all | 0.699 |
| label encoding: gaming 0, office 1, ultrabook 2 | 0.695 |
| one-hot encoding | 0.760 |
Label encoding with an invented order brought nothing. One-hot encoding lets every type have its own effect.
8.5The encoder of scikit-learn
OneHotEncoder does the same, with fit and transform:
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
encoder.fit(raw[["type"]])
print(encoder.get_feature_names_out())
print(encoder.transform(raw[["type"]].head(3)))Output
['type_gaming' 'type_office' 'type_ultrabook'] [[0. 1. 0.] [1. 0. 0.] [0. 1. 0.]]
sparse_output=Falsereturns an ordinary array.fitlearns the list of categories. That is its advantage overget_dummies: fitted on the training data, it produces the same columns for every later table, also for one new laptop.handle_unknown="ignore": a category that was not in the training data (a new type, "tablet") gets 0 in all columns, where it would otherwise stop with an error.
For a table that is encoded once, get_dummies is the simplest way, and this lesson uses it. In a system that receives new data every day, OneHotEncoder fitted on the training data is the safe way.
8.6When one-hot encoding does not fit
Every category costs a column. Three types are three columns. Twelve brands are twelve. A column with 500 cities would be 500 columns, most of them almost always 0, and many with only a handful of rows to learn from: a wide table and an invitation to overfitting (Topic 23). For columns with many categories there are other encodings.
Try it yourself
brand inside the table, with drop_first=True and dtype=int, and print the shape of the table. How many columns did the 12 brands become?Show a hint
df = pd.get_dummies(df, columns=["brand"], drop_first=True, dtype=int), then print(df.shape). The table had 15 columns: brand leaves and 11 new columns arrive.Show the solution
import pandas as pd
df = pd.read_csv("laptops.csv")
df = pd.get_dummies(df, columns=["brand"], drop_first=True, dtype=int)
print(df.shape)Output
(300, 25)
Try it yourself
fuel has the values petrol, diesel, electric and hybrid. (a) How many columns does one-hot encoding make of it? (b) How many with drop_first=True? (c) With drop_first=True a car has 0 in all the remaining columns. Which fuel does it have? (d) A column street has 400 different values. How many columns would one-hot encoding make of it?Show a hint
drop_first=True drops the first category in the order of the alphabet.Show the solution
Answer: (a) 4; (b) 3; (c) diesel; (d) 400.
Four categories give four columns. In the order of the alphabet the first one is diesel, so drop_first=True drops fuel_diesel, and a diesel car is the row with 0 in the other three. Four hundred streets would be four hundred columns: too many, and the reason for the encodings of Part 9.
9Many categories: target encoding and frequency encoding
The column brand has 12 values and no order.
9.1Target encoding
Target encoding replaces every category by one number: the mean of the target in that category. A brand is replaced by the mean price of its laptops. It is also called mean encoding.
By hand, with six laptops:
| brand | price |
|---|---|
| Altra | 1,500 |
| Altra | 1,700 |
| Boreal | 1,000 |
| Boreal | 1,200 |
| Boreal | 1,400 |
| Cirro | 2,000 |
Every "Altra" in the column becomes 1,600, every "Boreal" 1,200, every "Cirro" 2,000. One column stays one column, however many categories there are, and its numbers have a meaning the model can use directly: an expensive brand has a large number.
9.2The danger: the target is inside the feature
This encoding is built from the target, and that makes it the most dangerous one of the lesson.
- It must be learned from the training data only. If the means are calculated from all the rows, the prices of the test laptops are inside the feature that is used to predict them: data leakage of the clearest kind (Topic 24). So: split first, calculate the means from the training data, and use these same means for the test data.
- Rare categories are unreliable. The "mean" of Cirro above is the price of a single laptop. The model would learn that one price by heart: overfitting.
That is why this encoding comes after the split, unlike the three before it:
train, test = train_test_split(df, test_size=0.2, random_state=42)
train = train.copy()
test = test.copy()
brand_means = train.groupby("brand")["price"].mean()
print(brand_means.round(0))Output
brand Altra 1503.0 Boreal 1256.0 Cirro 2045.0 Delto 1445.0 Evora 1761.0 Fenix 1171.0 Galo 1397.0 Helio 1881.0 Ixon 1343.0 Juno 1666.0 Kora 1218.0 Lumo 1460.0 Name: price, dtype: float64
groupby("brand")["price"].mean() is the mean price of every brand (Topic 11), from the training laptops only. The two copy() lines make train and test tables of their own, so that columns can be added to them.
train["brand_price"] = train["brand"].map(brand_means)
test["brand_price"] = test["brand"].map(brand_means)
test["brand_price"] = test["brand_price"].fillna(train["price"].mean())
print(train[["brand", "brand_price"]].head(4).round(0))Output
brand brand_price 184 Lumo 1460.0 212 Helio 1881.0 171 Helio 1881.0 6 Lumo 1460.0
map replaces every brand by its mean. The test data gets the means of the training data. If the test data contains a brand that the training data did not have, map leaves a gap there, and fillna fills it with the mean price of all training laptops: the best guess for an unknown brand.
scores(train, test, features + ["brand_price"])Output
0.953 0.941
From 0.760 to 0.941. The brand was the strongest piece of information in the table, and it was hidden in a text column.
9.3Frequency encoding
Frequency encoding replaces every category by how often it appears: its share of the rows (or its count). It does not use the target, so it cannot leak the target. The shares are still learned from the training data.
brand_share = train["brand"].value_counts(normalize=True)
train["brand_share"] = train["brand"].map(brand_share)
test["brand_share"] = test["brand"].map(brand_share).fillna(0)
print(brand_share.round(3).head(3))
scores(train, test, features + ["brand_share"])Output
brand Lumo 0.140 Delto 0.119 Galo 0.115 Name: proportion, dtype: float64 0.807 0.769
value_counts(normalize=True) gives shares in the place of counts (Topic 10). The score is 0.769, hardly above the 0.760 without the brand. In this shop a brand that is sold often is not more or less expensive than a rare one, so the frequency says nothing about the price. Frequency encoding helps only when being common or rare is itself connected to the target: a product that is bought often, a city with many customers.
9.4All the encodings of the brand side by side
For the comparison the brand is also one-hot encoded (eleven columns, with drop_first):
brand_columns = pd.get_dummies(df["brand"], prefix="brand", drop_first=True, dtype=int)
train_wide = train.join(brand_columns)
test_wide = test.join(brand_columns)
print(len(brand_columns.columns))
scores(train_wide, test_wide, features + brand_columns.columns.tolist())Output
11 0.971 0.965
join adds the new columns to the rows with the same index (Topic 11).
| How brand is given to the model | Columns | Test score |
|---|---|---|
| not at all | 0 | 0.760 |
| frequency encoding | 1 | 0.769 |
| target encoding | 1 | 0.941 |
| one-hot encoding | 11 | 0.965 |
- One-hot encoding gives the best score here. With 12 brands and almost 300 rows the model can afford eleven columns, and every brand gets its own exact weight.
- Target encoding comes close with a single column. With 12 categories that is a matter of taste. With 500 categories it is the difference between a table that works and one that does not.
- Frequency encoding does not help in this data.
9.5Which encoding for which column
| The column | Encoding | In Python |
|---|---|---|
| two values | 0 and 1 | df[c].map({"no": 0, "yes": 1}) |
| ordered categories | label (ordinal) encoding, in your order | df[c].map(order) or OrdinalEncoder(categories=[[...]]) |
| no order, few categories (up to about 10 or 15) | one-hot encoding | pd.get_dummies(df, columns=[c], drop_first=True, dtype=int) or OneHotEncoder |
| no order, many categories | target encoding (from the training data) | train.groupby(c)[target].mean(), then map |
| no order, many categories, and how common a category is matters | frequency encoding | train[c].value_counts(normalize=True), then map |
scikit-learn also has a TargetEncoder. It does the same as the cells above and adds two protections: it pulls the means of rare categories towards the overall mean, and it calculates the training values in a way that is safer against overfitting. The idea is the one you have just done by hand.
Six laptops and their type. Choose an encoding and read the new columns.
| type | price | type_gaming | type_office | type_ultrabook |
|---|---|---|---|---|
| office | 1,000 | 0 | 1 | 0 |
| gaming | 1,500 | 1 | 0 | 0 |
| ultrabook | 2,000 | 0 | 0 | 1 |
| office | 1,200 | 0 | 1 | 0 |
| gaming | 1,300 | 1 | 0 | 0 |
| office | 1,100 | 0 | 1 | 0 |
One column for every type. Every row has exactly one 1.
Try it yourself
type replaces every type by its share of the training rows. Print the share of the office laptops in train, rounded to 3 decimals.Show a hint
shares = train["type"].value_counts(normalize=True), then print(round(shares["office"], 3)).Show the solution
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("laptops.csv")
train, test = train_test_split(df, test_size=0.2, random_state=42)
shares = train["type"].value_counts(normalize=True)
print(round(shares["office"], 3))Output
0.462
Try it yourself
Show a hint
Show the solution
Answer: (a) 15; (b) 50; (c) 36; (d) 0.6.
10The whole road, from the file to the test score
Topics 24 and 25 gave many steps. Their order matters, and one question sorts them: does the step learn something from the rows? Steps that do not come before the split. Steps that do come after it and learn from the training data only.
Nothing is learned from the rows: the whole table
1. Drop
the ID, the name, the constant
2. Clean
repair or remove the mistakes
3. Encode by rule
0 and 1, ordinal, one-hot
4. Split
training data and test data
Learned from the training data only
5. Learn from the training data
target encoding, the selection of features, the scaler
6. Model
fit on the training data, score on the test data
Here is the whole recipe once more in one place, from an empty notebook. Every cell is short, and nothing in it is new.
Step 1: read the file and drop the columns without information.
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("laptops.csv")
df = df.drop(columns=["laptop_id", "seller_name", "currency"])
print(df.shape)Output
(300, 12)
Step 2: clean the mistakes. The wrong prices are removed, the wrong weights are repaired.
df = df[df["price"] < 9000]
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
print(df.shape)
print(df["weight_kg"].max(), df["price"].max())Output
(294, 12) 3.33 3290
Step 3: encode the columns that need no learning.
df["touchscreen"] = df["touchscreen"].map({"no": 0, "yes": 1})
df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3})
df = pd.get_dummies(df, columns=["type"], drop_first=True, dtype=int)
print(df.columns.tolist())Output
['brand', 'condition', 'touchscreen', 'ram_gb', 'storage_gb', 'screen_inch', 'screen_cm', 'weight_kg', 'usb_ports', 'age_months', 'price', 'type_office', 'type_ultrabook']
Step 4: split.
train, test = train_test_split(df, test_size=0.2, random_state=42)
train = train.copy()
test = test.copy()
print(train.shape, test.shape)Output
(235, 13) (59, 13)
Step 5: target encoding of the brand, from the training data.
brand_means = train.groupby("brand")["price"].mean()
train["brand_price"] = train["brand"].map(brand_means)
test["brand_price"] = test["brand"].map(brand_means).fillna(train["price"].mean())
train = train.drop(columns=["brand"])
test = test.drop(columns=["brand"])
print(train.shape, test.shape)Output
(235, 13) (59, 13)
The text column brand has done its work and is dropped. Every column is a number now.
Step 6: select the features (Topic 24). First the correlation of every column with the price, in the training data:
print(train.corr()["price"].round(2).sort_values())Output
type_office -0.38 weight_kg -0.36 age_months -0.26 usb_ports -0.00 touchscreen 0.09 screen_inch 0.14 screen_cm 0.14 condition 0.29 brand_price 0.41 storage_gb 0.43 ram_gb 0.44 type_ultrabook 0.49 price 1.00 Name: price, dtype: float64
usb_portshas a correlation of practically zero with the price (it prints as-0.00): it says nothing. It is dropped.screen_inchandscreen_cmhave exactly the same correlation with the price. That is suspicious:
print(round(train["screen_inch"].corr(train["screen_cm"]), 2))Output
1.0
A correlation of 1.0: the two columns are the same measurement in two units, the purest case of multicollinearity. One of them is enough; screen_cm is dropped.
features = ["ram_gb", "storage_gb", "screen_inch", "weight_kg", "age_months", "condition", "touchscreen", "type_office", "type_ultrabook", "brand_price"]
X_train = train[features]
X_test = test[features]
y_train = train["price"]
y_test = test["price"]
print(X_train.shape, X_test.shape)Output
(235, 10) (59, 10)
Step 7: scale (Topic 24). The scaler is fitted on the training data.
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(X_train_scaled.shape, X_test_scaled.shape)Output
(235, 10) (59, 10)
The columns of 0 and 1 are scaled here together with the others. That is simple and does no harm; for a linear regression the score is the same with and without scaling (Topic 24), and the scaled weights can be compared.
Step 8: train and judge.
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.953 0.939
Step 9: read the weights.
for name, weight in zip(features, model.coef_):
print(name, round(weight, 1))Output
ram_gb 197.8 storage_gb 209.3 screen_inch 48.5 weight_kg -205.2 age_months -127.1 condition 154.5 touchscreen 87.7 type_office -209.1 type_ultrabook -27.5 brand_price 201.0
After standard scaling the weights can be compared (Topic 24). Five features are about equally strong, each worth around 200 manat for one standard deviation: the disk, the type (office or not), the weight, the brand and the memory. The size of the screen matters least. The encoded columns stand in the list like any other number.
The test score is 0.939, practically the 0.941 of Part 9: the two dropped columns carried nothing, and scaling does not change the score of a linear regression. The model is simpler, and its weights can be read.
10.1From the first model to the last
| Step | Test score |
|---|---|
| the numerical columns as they came | |
| the wrong prices removed | 0.405 |
| the wrong weights repaired | 0.527 |
condition and touchscreen encoded | 0.699 |
type one-hot encoded | 0.760 |
brand target encoded | 0.941 |
| two columns dropped, features scaled | 0.939 |
The model was a plain LinearRegression from the first line to the last. The data was the same file. Cleaning twelve wrong values and encoding four text columns made the whole difference.
Try it yourself
StandardScaler. (e) Repairing weights that were typed in the wrong unit.Show a hint
Show the solution
Answer: (a) before; (b) before; (c) after; (d) after; (e) before.
Dropping a column, a dictionary and the repair of a unit use knowledge about the columns. They learn nothing from the rows and are done on the whole table. Target encoding learns the mean of the target in every category, and a scaler learns a mean and a standard deviation: both learn from the rows, so both come after the split and use the training data only.
11Common mistakes
| Mistake | Why it is wrong | Right |
|---|---|---|
| Removing every value that a rule marks. | A rule finds candidates. Many of them are real values. | Look at the marked rows and decide: mistake or real? |
| Calling a real extreme value a mistake because it disturbs the model. | The model will meet such cases in real use. | Keep it, cap it, or state a limit for the model. |
| Calculating IQR limits or z-scores from all rows and splitting afterwards. | The test rows help to decide what the training data looks like: data leakage. | Split first; limits from the training data. |
| Removing real extreme values from the test data. | The score becomes too flattering. | Leave the test data as the world is. |
| Removing outliers only from the test data. | The model is trained on them and judged without them. | Never. |
| Applying the IQR rule to every column. | Columns with a few fixed values lose their less common values; a large part of the rows disappears. | Selected columns with continuous measurements. |
| Using the z-score on a small or strongly skewed column. | The outliers pull the mean and the standard deviation and hide themselves. | The IQR rule. |
| Removing a row when the mistake can be repaired. | A row of good data is lost with it. | Repair when the cause is known. |
| Dropping a text column because "models need numbers". | The information is lost. | Encode it. |
| Label encoding for a column without order (a type, a city). | The numbers invent an order and distances that do not exist. | One-hot encoding. |
| Letting an encoder order an ordinal column by the alphabet. | "used" becomes the best condition. | Give the order yourself. |
| One-hot encoding for a column with hundreds of categories. | Hundreds of columns, most of them almost empty. | Target or frequency encoding. |
| Target encoding with the means of all rows. | The target of the test rows is inside their feature. | Means from the training data only. |
get_dummies without dtype=int and wondering about True and False. | pandas makes truth values by default. | dtype=int |
| Keeping all dummy columns in a linear model and reading the weights. | One column follows from the others: the dummy variable trap. | drop_first=True |
| Forgetting a category that appears only in the test data. | map leaves a gap, and the model stops at it. | fillna with a sensible value; handle_unknown="ignore" for OneHotEncoder. |
12Solved problems
Fourteen problems. The first four are short and solved by hand; the others are in Python on laptops.csv, and each one starts on its own, from reading the file. The longer ones are split into two or three cells.
Problem 1: The IQR rule by hand
The delivery times of nine orders in days, sorted: 2, 3, 3, 4, 4, 5, 5, 6, 15. Find the limits of the IQR rule and the outliers.
Idea. The quartiles stand at the positions (Part 4).
Why: all values from 2 to 6 lie between 0 and 8. The value 15 lies above 8: it is the only outlier. Whether it is a mistake or a delivery that really took 15 days, the rule cannot say.
Problem 2: A z-score by hand
The marks of an exam have the mean 70 and the standard deviation 8. Find the z-scores of the marks 94, 50 and 98. Which of them does the z-score rule with the limit 3 call an outlier?
Idea. (Part 4).
Why: only 98 has a z-score above 3. The mark 94 lies exactly on the limit and is not beyond it; 50 lies 2.5 standard deviations below the mean, which is far but inside the limits.
Problem 3: Which encoding?
A table of flats has the columns balcony (yes, no), floor_level (low, middle, high), heating (gas, electric, central) and street (340 different streets). Choose an encoding for each.
Idea. Two questions: is there an order, and how many categories are there? (Part 6)
balcony: two values. 0 and 1.floor_level: three values with an order. Label (ordinal) encoding: low = 0, middle = 1, high = 2.heating: three values without an order. One-hot encoding.street: 340 values without an order. Target encoding (or frequency encoding).
Why: numbers in order are right only where the categories have an order. Without an order every category needs its own column, and when that would be hundreds of columns, the category is replaced by one number that is learned from the training data.
Problem 4: Target encoding by hand
Six flats of the training data are in the table below. Encode the district with target encoding. What does a test flat in the district "East" get?
| district | price |
|---|---|
| North | 90 |
| North | 110 |
| South | 150 |
| South | 170 |
| South | 160 |
| West | 200 |
Idea. The mean of the target in every category; an unknown category gets the mean of all training rows (Part 9).
Why: North becomes 100, South 160 and West 200. "East" does not appear in the training data, so it gets the overall mean 146.667. The value of West rests on a single flat and should not be trusted much.
Problem 5: Outliers of a column with the IQR rule
Find the upper limit of the IQR rule for weight_kg in laptops.csv and print the number of weights above it.
Idea. quantile(0.25) and quantile(0.75), then the limit (Part 4).
import pandas as pd
df = pd.read_csv("laptops.csv")
q1 = df["weight_kg"].quantile(0.25)
q3 = df["weight_kg"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)
print(round(upper, 2))
print((df["weight_kg"] > upper).sum())Output
3.58 6
Why: a comparison gives a column of True and False, and sum() counts the True values (Topic 10). Six weights lie above 3.58 kg: the six that were typed in grams.
Problem 6: The z-score against the IQR rule
Count the outliers of storage_gb with the z-score (limit 3) and with the IQR rule. Why do the two numbers differ so much?
Idea. A skewed column with a few fixed values (Parts 4 and 5).
import pandas as pd
df = pd.read_csv("laptops.csv")
z = (df["storage_gb"] - df["storage_gb"].mean()) / df["storage_gb"].std()
print((z.abs() > 3).sum())
q1 = df["storage_gb"].quantile(0.25)
q3 = df["storage_gb"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)
print(upper, (df["storage_gb"] > upper).sum())Output
10 896.0 44
Why: the z-score marks the ten laptops with 2,048 GB. The IQR rule puts its limit at 896 GB and marks all 44 laptops with 1,024 or 2,048 GB. None of them is a mistake: these are real disk sizes. A column with a few fixed values is not a place for outlier rules.
Problem 7: Remove or repair
Remove the rows with a price of 9,000 or more, and repair the weights above 10 by dividing them by 1,000. Print the shape of the table and the largest weight.
Idea. A mistake whose true value is not known is removed; a mistake with a known cause is repaired (Part 5).
import pandas as pd
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
print(df.shape)
print(df["weight_kg"].max())Output
(294, 15) 3.33
Why: six rows are gone, and six weights are right again without losing their rows. Both steps use a fixed rule, so they are done on the whole table before any split.
Problem 8: Limits from the training data
Clean the table as in Problem 7 and split it (test_size=0.2, random_state=42). Calculate the upper IQR limit of the price from the training data, and print it together with the number of training rows and of test rows above it.
Idea. A limit that is learned from the rows is learned from the training rows (Part 5).
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
train, test = train_test_split(df, test_size=0.2, random_state=42)
print(train.shape, test.shape)Output
(235, 15) (59, 15)
The limit comes from train alone. Then the same limit is used to look at both parts:
q1 = train["price"].quantile(0.25)
q3 = train["price"].quantile(0.75)
upper = q3 + 1.5 * (q3 - q1)
print(upper)
print((train["price"] > upper).sum(), (test["price"] > upper).sum())Output
2832.5 3 0
Why: the limit was calculated without the test data, and then the same limit was used to look at both parts. Three training laptops lie above it. They are real laptops, so nothing has to be done with them.
Problem 9: Two values and an order
Encode touchscreen as 0 and 1 and condition in its order from 0 to 3. Print the mean price for every value of the encoded condition, rounded to whole numbers.
Idea. map with a dictionary (Part 7).
import pandas as pd
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
df["touchscreen"] = df["touchscreen"].map({"no": 0, "yes": 1})
df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3})
print(df.groupby("condition")["price"].mean().round(0))Output
condition 0 1188.0 1 1477.0 2 1624.0 3 1596.0 Name: price, dtype: float64
Why: the mean price rises clearly from 0 (used) to 2 (like new), which is what the order of the numbers promises to the model. Between 2 and 3 the two means are close: in this file other columns, such as the brand and the memory, differ between the two groups. The model with all columns sorts that out.
Problem 10: One-hot encoding
One-hot encode the column type with all three columns, and print how many laptops each type has by adding up the new columns.
Idea. pd.get_dummies makes a column of 0 and 1 for every category; the sum of such a column counts its rows (Part 8).
import pandas as pd
df = pd.read_csv("laptops.csv")
dummies = pd.get_dummies(df["type"], dtype=int)
print(dummies.head(3))
print(dummies.sum())Output
gaming office ultrabook 0 0 1 0 1 1 0 0 2 0 1 0 gaming 82 office 137 ultrabook 81 dtype: int64
Why: every row has exactly one 1, so the three sums add up to the 300 rows. With drop_first=True the column gaming would be left out and a gaming laptop would be the row with two zeros.
Problem 11: Target encoding of a column
Clean the prices, split the table (test_size=0.2, random_state=42) and encode type with target encoding from the training data. Print the three means, rounded to whole numbers, and the first three values of the new column in the test data.
Idea. groupby on the training data, map on both parts (Part 9).
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
train, test = train_test_split(df, test_size=0.2, random_state=42)
train = train.copy()
test = test.copy()
print(train.shape, test.shape)Output
(235, 15) (59, 15)
The means come from the training data and are used for both parts:
type_means = train.groupby("type")["price"].mean()
train["type_price"] = train["type"].map(type_means)
test["type_price"] = test["type"].map(type_means)
print(type_means.round(0))
print(test["type_price"].head(3).round(0).tolist())Output
type gaming 1412.0 office 1262.0 ultrabook 1878.0 Name: price, dtype: float64 [1262.0, 1412.0, 1412.0]
Why: the test laptops get the means of the training laptops, never their own. Target encoding works for any categorical column; for a column with three categories one-hot encoding is the more usual choice.
Problem 12: Does the encoding help?
Clean the table as in Problem 7. Compare two models with the test score: one with ram_gb, storage_gb, weight_kg and age_months, and one that also gets the encoded condition.
Idea. The judge of every feature is the score on the test data (Topic 24).
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3})
train, test = train_test_split(df, test_size=0.2, random_state=42)
print(train.shape, test.shape)Output
(235, 15) (59, 15)
The two models, one after the other. Every line of the output shows the number of features and the test score:
columns = ["ram_gb", "storage_gb", "weight_kg", "age_months"]
for features in [columns, columns + ["condition"]]:
model = LinearRegression()
model.fit(train[features], train["price"])
print(len(features), round(model.score(test[features], test["price"]), 3))Output
4 0.53 5 0.662
Why: one encoded column raises the score clearly. The information was in the file all the time; the model could not read it while it was text.
Problem 13: Frequency encoding
Split the table of Problem 7 and encode brand with frequency encoding from the training data. Print the three most common brands with their shares, rounded to 3 decimals.
Idea. value_counts(normalize=True) on the training data, then map (Part 9).
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
train, test = train_test_split(df, test_size=0.2, random_state=42)
train = train.copy()
test = test.copy()
print(train.shape, test.shape)Output
(235, 15) (59, 15)
The shares come from the training data:
brand_share = train["brand"].value_counts(normalize=True)
train["brand_share"] = train["brand"].map(brand_share)
test["brand_share"] = test["brand"].map(brand_share).fillna(0)
print(brand_share.head(3).round(3))Output
brand Lumo 0.140 Delto 0.119 Galo 0.115 Name: proportion, dtype: float64
Why: every brand is replaced by its share of the training rows. A brand that the training data does not contain would get 0: it was never seen.
Problem 14: A small complete recipe
Use the features ram_gb, weight_kg, age_months and the encoded condition and touchscreen. Clean, encode, split (test_size=0.2, random_state=42), scale with a StandardScaler and train a LinearRegression. Print the test score and the weights.
Idea. The order of Part 10: clean, encode by rule, split, scale with the training data, train.
Clean and encode:
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("laptops.csv")
df = df[df["price"] < 9000]
df.loc[df["weight_kg"] > 10, "weight_kg"] = df["weight_kg"] / 1000
df["touchscreen"] = df["touchscreen"].map({"no": 0, "yes": 1})
df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3})
print(df.shape)Output
(294, 15)
Split, then scale with the numbers of the training data:
features = ["ram_gb", "weight_kg", "age_months", "condition", "touchscreen"]
train, test = train_test_split(df, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(train[features])
X_test_scaled = scaler.transform(test[features])
print(X_train_scaled.shape, X_test_scaled.shape)Output
(235, 5) (59, 5)
Train, judge, and read the weights:
model = LinearRegression()
model.fit(X_train_scaled, train["price"])
print(round(model.score(X_test_scaled, test["price"]), 3))
for name, weight in zip(features, model.coef_):
print(name, round(weight, 1))Output
0.69 ram_gb 231.3 weight_kg -192.4 age_months -116.8 condition 148.4 touchscreen 60.1
Why: the scaler was fitted on the training data and applied to both parts. Because the features are standardised, the weights can be compared: the memory has the largest effect of these five, and the two encoded columns stand in the list like any other number.
13Practice
Eighteen problems. The first four are solved on paper. Problems 5 to 18 are one small project in Python on a new data file, phones.csv, from reading the file to the test score. Under every problem there is a hint and a solution.
13.1Group A: by hand
- 1.The ages of nine customers, sorted: 20, 22, 23, 24, 25, 26, 27, 30, 58. Find the two limits of the IQR rule. Which value is an outlier?
Show a hint
is the third value and the seventh. The limits lie 1.5 IQR outside the quartiles.Show one possible solution
Answer: lower limit 17, upper limit 33; the outlier is 58.
Only 58 lies outside the limits.
- 2.The weights of parcels have the mean 12 kg and the standard deviation 4 kg. (a) What is the z-score of a parcel of 26 kg? (b) What is the z-score of a parcel of 2 kg? (c) Which of the two is an outlier by the z-score rule with the limit 3?
Show a hint
.Show one possible solution
Answer: (a) 3.5; (b) ; (c) the parcel of 26 kg.
(c) Only 3.5 lies beyond 3. The z-score is far from the mean, but inside the limits.
- 3.Choose the encoding. (a)
sizeof a shirt: S, M, L, XL. (b)colourof a shirt: red, blue, green, black. (c)gift_wrap: yes, no. (d)postcodeof the customer: 900 different values.Show a hint
Is there an order? How many categories are there?Show one possible solution
Answer: (a) label (ordinal) encoding; (b) one-hot encoding; (c) 0 and 1; (d) target encoding.
(a) The sizes have an order: S = 0, M = 1, L = 2, XL = 3. (b) Four colours without an order: one column for each. (c) Two values. (d) No order and far too many categories for one-hot encoding: one number for every postcode, learned from the training data.
- 4.Five training rows: city A with the targets 10 and 14, city B with the targets 20, 22 and 24. (a) What does target encoding make of city A? (b) Of city B? (c) What does a test row from the unknown city C get?
Show a hint
The mean of the target in every city; an unknown city gets the mean of all training rows.Show one possible solution
Answer: (a) 12; (b) 22; (c) 18.
13.2Group B: one project in Python
The lesson worked with laptops. The practice repeats its steps on a file you have not seen: phones.csv describes 260 invented phones of a shop, and it is built like laptops.csv.
| Column | Meaning |
|---|---|
phone_id | the identification number of the phone |
seller_name | the first name of the seller |
currency | the currency of the price |
brand | the maker (10 invented brands) |
material | the material of the body: plastic, glass or metal |
condition | used, good, like new or new |
dual_sim | yes or no |
ram_gb | the memory in gigabytes |
storage_gb | the storage in gigabytes |
screen_inch | the size of the screen in inches |
screen_cm | the size of the screen in centimetres |
weight_g | the weight in grams |
camera_mp | the megapixels of the camera |
age_months | the age in months |
price | the price in manat: the target |
The data file: phones.csv
260 phones, 15 columns. A cell marked "empty" has no value in the file: pandas shows it as NaN.
Loading the table ...
The task: prepare the file, predict the price of a phone, 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 5 to 9: the columns and the outliers
Drop what carries no information, find the wrong prices with two rules, remove them, repair the weights.
- 5.Read
phones.csvintodfand drop the columnsphone_id,seller_nameandcurrency. Print the shape of the table.Show a hint
df = pd.read_csv("phones.csv"),df = df.drop(columns=["phone_id", "seller_name", "currency"]), thenprint(df.shape).Show one possible solution
Pythonimport pandas as pd df = pd.read_csv("phones.csv") df = df.drop(columns=["phone_id", "seller_name", "currency"]) print(df.shape)Output
(260, 12)
- 6.Calculate the upper limit of the IQR rule for
priceinto the variableupper. Print the limit, then the number of prices above it. This step continues from Step 5.Show a hint
q1 = df["price"].quantile(0.25), the same with0.75forq3, thenupper = q3 + 1.5 * (q3 - q1). The number of prices above it is(df["price"] > upper).sum().Show one possible solution
Python, continues from the cells aboveq1 = df["price"].quantile(0.25) q3 = df["price"].quantile(0.75) upper = q3 + 1.5 * (q3 - q1) print(upper) print((df["price"] > upper).sum())Output
1855.0 5
- 7.Calculate the z-scores of
priceand print the prices with a z-score above 3 as a sorted list. This step continues from Step 5.Show a hint
z = (df["price"] - df["price"].mean()) / df["price"].std(), thenprint(df[z > 3]["price"].sort_values().tolist()). Each of these prices is about ten times the price of an ordinary phone: typing mistakes.Show one possible solution
Python, continues from the cells abovez = (df["price"] - df["price"].mean()) / df["price"].std() print(df[z > 3]["price"].sort_values().tolist())Output
[6040, 9900, 10560, 10920, 13880]
- 8.Remove the rows whose price lies above
upper. Print the shape of the table, then the largest price that is left. This step continues from Step 6.Show a hint
df = df[df["price"] <= upper], thenprint(df.shape)andprint(df["price"].max()).Show one possible solution
Python, continues from the cells abovedf = df[df["price"] <= upper] print(df.shape) print(df["price"].max())Output
(255, 12) 1770
- 9.Some weights were typed in kilograms (0.19 where 190 was meant). Print how many values of
weight_gare below 10. Then multiply these values by 1,000 and print the smallest weight. This step continues from Step 8.Show a hint
print((df["weight_g"] < 10).sum()), thendf.loc[df["weight_g"] < 10, "weight_g"] = df["weight_g"] * 1000andprint(df["weight_g"].min()).Show one possible solution
Python, continues from the cells aboveprint((df["weight_g"] < 10).sum()) df.loc[df["weight_g"] < 10, "weight_g"] = df["weight_g"] * 1000 print(df["weight_g"].min())Output
5 120.0
Steps 10 to 14: encode, split, select
Three encodings by rule, the split, target encoding from the training data, and a look at the correlations.
- 10.Encode
dual_simas 0 (no) and 1 (yes), andconditionin its order: used 0, good 1, like new 2, new 3. Print the first three rows of the two columns. This step continues from Step 9.Show a hint
df["dual_sim"] = df["dual_sim"].map({"no": 0, "yes": 1}), a second dictionary forcondition, thenprint(df[["dual_sim", "condition"]].head(3)).Show one possible solution
Python, continues from the cells abovedf["dual_sim"] = df["dual_sim"].map({"no": 0, "yes": 1}) df["condition"] = df["condition"].map({"used": 0, "good": 1, "like new": 2, "new": 3}) print(df[["dual_sim", "condition"]].head(3))Output
dual_sim condition 0 0 1 1 1 0 2 0 0
- 11.One-hot encode
materialinside the table, withdrop_first=Trueanddtype=int. Print the names of the columns as a list. This step continues from Step 10.Show a hint
df = pd.get_dummies(df, columns=["material"], drop_first=True, dtype=int), thenprint(df.columns.tolist()). The first material in the order of the alphabet,glass, becomes the reference.Show one possible solution
Python, continues from the cells abovedf = pd.get_dummies(df, columns=["material"], drop_first=True, dtype=int) print(df.columns.tolist())Output
['brand', 'condition', 'dual_sim', 'ram_gb', 'storage_gb', 'screen_inch', 'screen_cm', 'weight_g', 'camera_mp', 'age_months', 'price', 'material_metal', 'material_plastic']
- 12.Split
dfintotrainandtestwithtest_size=0.25andrandom_state=7, and make each of them a copy. Print the two shapes on one line. This step continues from Step 11.Show a hint
from sklearn.model_selection import train_test_split, thentrain, test = train_test_split(df, test_size=0.25, random_state=7),train = train.copy()andtest = test.copy().Show one possible solution
Python, continues from the cells abovefrom sklearn.model_selection import train_test_split train, test = train_test_split(df, test_size=0.25, random_state=7) train = train.copy() test = test.copy() print(train.shape, test.shape)Output
(191, 13) (64, 13)
- 13.Target-encode
brandinto a new columnbrand_priceintrainandtest, with the mean prices oftrain. Then dropbrandfrom both tables. Print the mean prices of the brands, rounded to whole numbers. This step continues from Step 12.Show a hint
brand_means = train.groupby("brand")["price"].mean(), thentrain["brand_price"] = train["brand"].map(brand_means)and the same fortest(a gap intestis filled with.fillna(train["price"].mean())). Drop withtrain = train.drop(columns=["brand"]). Printbrand_means.round(0).Show one possible solution
Python, continues from the cells abovebrand_means = train.groupby("brand")["price"].mean() train["brand_price"] = train["brand"].map(brand_means) test["brand_price"] = test["brand"].map(brand_means).fillna(train["price"].mean()) train = train.drop(columns=["brand"]) test = test.drop(columns=["brand"]) print(brand_means.round(0))Output
brand Arvo 977.0 Brio 1317.0 Celo 838.0 Dexa 1167.0 Elan 1435.0 Fyra 955.0 Gemo 1159.0 Hilo 753.0 Isto 1169.0 Jolt 1212.0 Name: price, dtype: float64
- 14.Print the correlation of every column of
trainwithprice, rounded to 2 decimals. Which column has the weakest correlation, and which two say the same? This step continues from Step 13.Show a hint
print(train.corr()["price"].round(2)).camera_mphas the weakest correlation;screen_inchandscreen_cmare one measurement in two units. Bothcamera_mpandscreen_cmare left out in the next step.Show one possible solution
Python, continues from the cells aboveprint(train.corr()["price"].round(2))Output
condition 0.27 dual_sim 0.14 ram_gb 0.33 storage_gb 0.29 screen_inch -0.14 screen_cm -0.14 weight_g -0.24 camera_mp 0.10 age_months -0.37 price 1.00 material_metal 0.38 material_plastic -0.31 brand_price 0.65 Name: price, dtype: float64
Steps 15 to 18: scale, train, read
The features, the scaler, the model and its weights.
- 15.The list
featuresis in the editor. MakeX_trainandX_testfrom these columns oftrainandtest, andy_trainandy_testfromprice. Print the shapes ofX_trainandX_teston one line. This step continues from Step 13.Show a hint
X_train = train[features]andy_train = train["price"], and the same fortest.Show one possible solution
Python, continues from the cells abovefeatures = ["ram_gb", "storage_gb", "screen_inch", "weight_g", "age_months", "condition", "dual_sim", "material_metal", "material_plastic", "brand_price"] X_train = train[features] X_test = test[features] y_train = train["price"] y_test = test["price"] print(X_train.shape, X_test.shape)Output
(191, 10) (64, 10)
- 16.Scale the features with a
StandardScalercalledscalerintoX_train_scaledandX_test_scaled. Print the column means ofX_test_scaled, rounded to 2 decimals. This step continues from Step 15.Show a hint
from sklearn.preprocessing import StandardScaler, thenscaler.fit_transform(X_train)for the training data andscaler.transform(X_test)for the test data. The means are.mean(axis=0).round(2): close to 0, not exactly 0. If your numbers differ, checktest_size=0.25andrandom_state=7in Step 12.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_test_scaled.mean(axis=0).round(2))Output
[ 0.02 0.04 -0.11 0.02 -0.05 -0.28 -0.04 0.1 0.1 -0.04]
- 17.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 16.Show a hint
from sklearn.linear_model import LinearRegression,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.946 0.947
- 18.Print the weight of every feature next to its name, rounded to 1 decimal, one feature on a line. Which feature has the largest effect? This step continues from Step 17.
Show a hint
for name, weight in zip(features, model.coef_):and inside the loopprint(name, round(weight, 1)). 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(features, model.coef_): print(name, round(weight, 1))Output
ram_gb 95.8 storage_gb 92.0 screen_inch 7.8 weight_g -19.2 age_months -78.9 condition 88.2 dual_sim 34.0 material_metal 39.3 material_plastic -71.6 brand_price 166.0
14Check yourself
Twelve questions. Every question has one right answer.
0 of 12 answered.
15Summary
| Outliers | |
|---|---|
| IQR rule | below or above ; the usual first choice |
| z-score | below or above 3; for bell-shaped columns with many rows |
| Mistakes | repair (cause known) or remove; whole table, before the split |
| Real extreme values | often keep; otherwise cap or remove in the training data, with limits from the training data |
| Test data | only mistakes are cleaned; real values stay |
| Columns | selected ones with continuous measurements, never all |
| The column | Encoding |
|---|---|
| two values | 0 and 1 |
| ordered categories | label (ordinal) encoding in your own order |
| no order, few categories | one-hot (dummy) encoding, drop_first=True for linear models |
| no order, many categories | target encoding, from the training data |
| no order, many categories, frequency matters | frequency encoding |
| Code | What it does |
|---|---|
df[c].quantile(0.25) | the first quartile |
z = (df[c] - df[c].mean()) / df[c].std() | the z-scores |
df = df[df[c] < limit] | removes rows |
df.loc[df[c] > 10, c] = df[c] / 1000 | repairs values in chosen rows |
train[c].clip(upper=limit) | caps values |
df[c].map({"no": 0, "yes": 1}) | encodes with a dictionary |
pd.get_dummies(df, columns=[c], drop_first=True, dtype=int) | one-hot encoding |
train.groupby(c)["price"].mean() | the means for target encoding |
train[c].value_counts(normalize=True) | the shares for frequency encoding |
The order of the steps
- Drop the columns without information.
- Clean the mistakes: repair or remove.
- Encode what needs no learning: 0 and 1, ordinal, one-hot.
- Split.
- Learn from the training data: limits for real extreme values, target or frequency encoding, the selection of features, the scaler.
- Train on the training data, judge on the test data.
Rules to keep
- A rule finds outliers. You decide whether they are mistakes.
- Mistakes are cleaned everywhere. Real extreme values stay in the test data.
- Whatever learns from the rows learns from the training rows only.
- Never drop a text column that carries information: encode it.
- Numbers in order only for categories in order. Without order: one column per category.
- Target encoding only with the means of the training data.
- The judge of every step is the score on the test data.
What comes next
The data is now clean, encoded and scaled, and the model has more features than ever. More features are also more room for overfitting. Topic 26, Ridge and Lasso regression, shows how a linear model is kept simple while it is trained: regularization.