Asiman Data School

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.

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. 1.What an outlier is, and the difference between a mistake and a real extreme value
  2. 2.Two rules for finding outliers, the IQR rule and the z-score, and when each is used
  3. 3.Five ways of handling outliers: remove, repair, cap, transform, keep
  4. 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. 5.Why a model needs numbers, and the kinds of categorical columns
  6. 6.Label (ordinal) encoding, one-hot (dummy) encoding, target encoding and frequency encoding, and which one fits which column
  7. 7.The whole preparation of a data file in the right order, from reading it to the test score
The words of this lesson
WordMeaning
outliera value that lies far away from the other values of its column
IQR rulea value is an outlier when it lies more than 1.5 IQR below the first or above the third quartile
z-scorehow many standard deviations a value lies from the mean
removing (trimming)deleting the rows with outliers
cappingreplacing a value beyond a limit by the limit itself
categorical variablea column whose values are groups, not amounts: a brand, a colour, a condition
nominalcategories without an order: brand, type, city
ordinalcategories with an order: used, good, like new, new
encodingturning categories into numbers
label (ordinal) encodingone whole number for every category
one-hot (dummy) encodingone column of 0 and 1 for every category
target encodingevery category is replaced by the mean of the target in that category
frequency encodingevery category is replaced by how often it appears
cardinalitythe 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.

Python
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    1510

Every code block of this lesson is a cell that continues from the cells above it, like a notebook: df stays in memory.

The data
ColumnMeaning
laptop_idthe identification number of the laptop in the list
seller_namethe first name of the person who sold it to the shop
currencythe currency of the price
brandthe maker (12 invented brands)
typewhat the laptop is built for: office, gaming or ultrabook
conditionused, good, like new or new
touchscreenyes or no
ram_gbthe memory in gigabytes
storage_gbthe size of the disk in gigabytes
screen_inchthe size of the screen in inches
screen_cmthe size of the screen in centimetres
weight_kgthe weight in kilograms
usb_portsthe number of USB ports
age_monthsthe age in months (0 for a new laptop)
pricethe 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.

Download

Loading the table ...

Six columns are text, not numbers:

Python, continues from the cells above
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.

Python, continues from the cells above
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_id has 300 values in 300 rows: an identification number.
  • currency has 1 value: a constant.
  • seller_name is 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.
Python, continues from the cells above
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

Python, continues from the cells above
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.

Two kinds of outliers
A mistakeA real extreme value
What it isa value that is wrong: a typing error, a wrong unit, a broken sensora value that is true, only rare
Examplea 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?noyes
What to dorepair it, or remove the rowthink 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:

Python, continues from the cells above
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.

051002040

Without the outlier

the line follows the points

051002040

With one outlier

the line turns towards it

The same eighteen points, and the line that linear regression draws through them. Left: without the outlier. Right: one point far above the others is added. The line turns towards it and now misses most of the ordinary points; the dashed line is the line from the left.

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.)

Python, continues from the cells above
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 is train["price"].

The scores: 0.05 on the training data and a negative score on the test data. A negative R2R^2 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):

Python, continues from the cells above
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

A mistake, or a real extreme value? (a) The age of a customer: 230 years. (b) The salary of the director of a company: twenty times the median salary. (c) A temperature of −999-999 degrees in the data of a weather station. (d) One order of 50 laptops, from a school.

Show a hint
Ask of every value: can it be true?
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 −999-999 degrees: both values are wrong. (Numbers such as −999-999 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.

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

sns.boxplot(x=df["price"])
plt.title("The prices of the 300 laptops")
plt.show()
Chart: The prices of the 300 laptops

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):

IQR=Q3−Q1\text{IQR} = Q_3 - Q_1

The rule draws two limits, 1.5 IQR outside the quartiles:

lower limit=Q1−1.5×IQRupper limit=Q3+1.5×IQR\begin{aligned} \text{lower limit} &= Q_1 - 1.5 \times \text{IQR} \\[4pt] \text{upper limit} &= Q_3 + 1.5 \times \text{IQR} \end{aligned}

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:

10121314151617186510 \quad 12 \quad 13 \quad 14 \quad 15 \quad 16 \quad 17 \quad 18 \quad 65

With the rule of Topic 18, the quartile for the share pp stands at the position 1+(n−1)×p1 + (n - 1) \times p:

Q1:position 1+8×0.25=3the third value: Q1=13Q3:position 1+8×0.75=7the seventh value: Q3=17IQR=17−13=41.5×IQR=1.5×4=6lower limit=13−6=7upper limit=17+6=23\begin{aligned} Q_1:\quad & \text{position } 1 + 8 \times 0.25 = 3 \\ & \text{the third value: } Q_1 = 13 \\[6pt] Q_3:\quad & \text{position } 1 + 8 \times 0.75 = 7 \\ & \text{the seventh value: } Q_3 = 17 \\[10pt] & \text{IQR} = 17 - 13 = 4 \\[4pt] & 1.5 \times \text{IQR} = 1.5 \times 4 = 6 \\[10pt] & \text{lower limit} = 13 - 6 = 7 \\[4pt] & \text{upper limit} = 17 + 6 = 23 \end{aligned}

Eight values lie between 7 and 23. The value 65 lies above 23: it is an outlier.

upper limit 23lower limit 701020304050607065
The nine values on a number line. The dark box runs from the first to the third quartile (13 to 17): the middle half of the data. The pale band runs 1.5 IQR further on both sides, from 7 to 23. Eight values lie inside it. The value 65 lies outside: an outlier.

In pandas, on the prices:

Python, continues from the cells above
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:

Python, continues from the cells above
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  25860

Nine 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):

z=x−meanstandard deviationz = \frac{x - \text{mean}}{\text{standard deviation}}

In a column with the shape of a bell almost all values (99.7 percent) have a z-score between −3-3 and 3 (Topic 17). So the usual rule is: a value with a z-score below −3-3 or above 3 is an outlier. Some people use 2.5 or 2 as a stricter limit.

By hand, for the same nine values:

sum=10+12+13+14+15+16+17+18+65=180mean=1809=20squared deviations:100+64+49+36+25+16+9+4+2025=2328standard deviation=23289=258.667=16.083z of 65:65−2016.083=2.798\begin{aligned} & \text{sum} = 10 + 12 + 13 + 14 + 15 \\ & \qquad\quad + 16 + 17 + 18 + 65 = 180 \\[6pt] & \text{mean} = \frac{180}{9} = 20 \\[10pt] & \text{squared deviations:} \\ & 100 + 64 + 49 + 36 + 25 \\ & \quad + 16 + 9 + 4 + 2025 = 2328 \\[10pt] & \text{standard deviation} = \sqrt{\frac{2328}{9}} \\[4pt] & \qquad = \sqrt{258.667} = 16.083 \\[10pt] & z \text{ of } 65:\quad \frac{65 - 20}{16.083} = 2.798 \end{aligned}

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:

Python, continues from the cells above
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 n−1n - 1; with hundreds of rows the difference to dividing by nn 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

Python, continues from the cells above
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?

Which rule, and when?
IQR rulez-score
Built onthe quartilesthe mean and the standard deviation
Moved by the outliers themselveshardlyyes: masking
Shape of the columnany shape; also skewed columnsmeant for columns with the shape of a bell
Small data setsworksweak: in 9 values no z-score can reach 3
Usual limit1.5 IQR (3 IQR for "far out")3 (sometimes 2.5 or 2)
Typical weaknessin a skewed column it marks many real valuesmisses 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.

upper limit 23lower limit 7010203040506070809065

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

With the limit 3 the z-score missed one of the six wrong weights. Calculate the z-scores of 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
Python
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

(a) A column has Q1=40Q_1 = 40 and Q3=60Q_3 = 60. What is the lower limit of the IQR rule? (b) What is the upper limit? (c) Is the value 95 an outlier by this rule? (d) Another column has the mean 50 and the standard deviation 10. What is the z-score of the value 85?

Show a hint
The IQR is Q3−Q1Q_3 - Q_1, and the limits lie 1.5 IQR outside the quartiles. A z-score is the distance from the mean, divided by the standard deviation.
Show the solution

Answer: (a) 10; (b) 90; (c) yes; (d) 3.5.

IQR=60−40=201.5×20=30lower limit=40−30=10upper limit=60+30=90z=85−5010=3.5\begin{aligned} & \text{IQR} = 60 - 40 = 20 \qquad 1.5 \times 20 = 30 \\[6pt] & \text{lower limit} = 40 - 30 = 10 \\[4pt] & \text{upper limit} = 60 + 30 = 90 \\[10pt] & z = \frac{85 - 50}{10} = 3.5 \end{aligned}

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

Five options
OptionWhat is doneFits when
Repairthe wrong value is replaced by the right onethe value is a mistake and its cause is known (a wrong unit, a shifted decimal point)
Removethe row is deletedthe value is a mistake and the right value is not known; there are few such rows
Capa value beyond a limit is replaced by the limitthe value is real but so extreme that it would dominate; the row itself is worth keeping
Transformthe whole column is changed, for example with the logarithm (Topic 24)the column has a long tail of real, large values
Keepnothingthe 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.

Python, continues from the cells above
df = df[df["price"] < 9000]

print(df.shape)

Output

(294, 12)

Six rows less: 294 laptops. The model again, with the same recipe:

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
train, test = train_test_split(df, test_size=0.2, random_state=42)

scores(train, test, numbers)

Output

0.542
0.527
Cleaning the mistakes
The dataTest score
as it came−0.618-0.618
the six wrong prices removed0.405
the six wrong weights repaired too0.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:

Python, continues from the cells above
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:

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Question 2: before or after the split?
The training dataTest score
all rows kept0.527
the three most expensive laptops removed0.522
their prices capped at the limit0.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?

Question 3: in the training data, in the test data, or in both?
MistakesReal extreme values
Training dataclean themmay be removed or capped, if that helps
Test dataclean themleave 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 (clip with 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:

Python, continues from the cells above
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

The answers side by side
QuestionAnswer
Is every outlier a mistake?No. A rule finds candidates; you decide what they are.
MistakesRepair them if the cause is known, remove the rows if not. In the whole table, before the split.
Real extreme valuesOften 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 targetMistakes: clean them everywhere. Real ones: at most out of the training data.
Every column?No. Selected columns with continuous measurements.
Other ways than removingCap, 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

Repair the weights that were typed in grams: divide every 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
Python
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

(a) IQR limits are used to remove extreme rows from the training data. From which rows are the limits calculated? (b) A real, very expensive laptop is in the test data. What is done with it? (c) Is the IQR rule a good idea for a column 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
Whatever learns from the rows learns from the training rows. The test data stands for the real world. A rule of knowledge is applied to the whole table.
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.

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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:

The kinds of categorical columns
ColumnValuesKindEncoding
touchscreen2: yes, nobinary: two values0 and 1
condition4: used, good, like new, newordinal: the values have an orderlabel (ordinal) encoding
type3: office, gaming, ultrabooknominal: no order, few valuesone-hot encoding
brand12nominal: no order, many valuestarget 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

Python, continues from the cells above
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.

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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

Encode 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
Python
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

A column 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
The order of the sizes is S, M, L, XL. In the order of the alphabet, count from 0.
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.

One column becomes three. Every row has a 1 in the column of its own type and a 0 in the two others. No type is larger than another.

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

Python, continues from the cells above
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:

Python, continues from the cells above
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

Python, continues from the cells above
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:

The score
How type is given to the modelTest score
not at all0.699
label encoding: gaming 0, office 1, ultrabook 20.695
one-hot encoding0.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:

Python, continues from the cells above
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=False returns an ordinary array.
  • fit learns the list of categories. That is its advantage over get_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

One-hot encode 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
Python
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

A column 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
One column for every category. 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:

Target encoding
brandprice
Altra1,500
Altra1,700
Boreal1,000
Boreal1,200
Boreal1,400
Cirro2,000
Altra:1500+17002=1600Boreal:1000+1200+14003=1200Cirro:20001=2000\begin{aligned} \text{Altra:}\quad & \frac{1500 + 1700}{2} = 1600 \\[6pt] \text{Boreal:}\quad & \frac{1000 + 1200 + 1400}{3} = 1200 \\[6pt] \text{Cirro:}\quad & \frac{2000}{1} = 2000 \end{aligned}

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:

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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):

Python, continues from the cells above
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).

All the encodings of the brand side by side
How brand is given to the modelColumnsTest score
not at all00.760
frequency encoding10.769
target encoding10.941
one-hot encoding110.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

Which encoding for which column
The columnEncodingIn Python
two values0 and 1df[c].map({"no": 0, "yes": 1})
ordered categorieslabel (ordinal) encoding, in your orderdf[c].map(order) or OrdinalEncoder(categories=[[...]])
no order, few categories (up to about 10 or 15)one-hot encodingpd.get_dummies(df, columns=[c], drop_first=True, dtype=int) or OneHotEncoder
no order, many categoriestarget encoding (from the training data)train.groupby(c)[target].mean(), then map
no order, many categories, and how common a category is mattersfrequency encodingtrain[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.

typepricetype_gamingtype_officetype_ultrabook
office1,000010
gaming1,500100
ultrabook2,000001
office1,200010
gaming1,300100
office1,100010

One column for every type. Every row has exactly one 1.

Try it yourself

A frequency encoding of 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
Python
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

Five training rows: the colour red with the prices 10 and 20, and the colour blue with the prices 30, 50 and 70. (a) What does target encoding make of red? (b) Of blue? (c) What does a test row with the unknown colour green get? (d) What is the frequency encoding (the share) of blue?

Show a hint
The mean price of every colour. An unknown colour gets the mean of all training rows. The share is the number of rows of the colour divided by the number of all rows.
Show the solution

Answer: (a) 15; (b) 50; (c) 36; (d) 0.6.

red:10+202=15blue:30+50+703=50green:10+20+30+50+705=1805=36share of blue:35=0.6\begin{aligned} \text{red:}\quad & \frac{10 + 20}{2} = 15 \\[6pt] \text{blue:}\quad & \frac{30 + 50 + 70}{3} = 50 \\[6pt] \text{green:}\quad & \frac{10 + 20 + 30 + 50 + 70}{5} \\[4pt] & = \frac{180}{5} = 36 \\[6pt] \text{share of blue:}\quad & \frac{3}{5} = 0.6 \end{aligned}

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. 1. Drop

    the ID, the name, the constant

  2. 2. Clean

    repair or remove the mistakes

  3. 3. Encode by rule

    0 and 1, ordinal, one-hot

  4. 4. Split

    training data and test data

Learned from the training data only

  1. 5. Learn from the training data

    target encoding, the selection of features, the scaler

  2. 6. Model

    fit on the training data, score on the test data

The order of the steps. Steps 1 to 3 learn nothing from the rows, so they are done on the whole table. After the split, everything that learns from the rows learns from the training data only and is then applied to 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.

Python
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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:

Python, continues from the cells above
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_ports has a correlation of practically zero with the price (it prints as -0.00): it says nothing. It is dropped.
  • screen_inch and screen_cm have exactly the same correlation with the price. That is suspicious:
Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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.

Python, continues from the cells above
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

From the first model to the last
StepTest score
the numerical columns as they came−0.618-0.618
the wrong prices removed0.405
the wrong weights repaired0.527
condition and touchscreen encoded0.699
type one-hot encoded0.760
brand target encoded0.941
two columns dropped, features scaled0.939
The test score of the same model, LinearRegression, after each step. The first bar points to the left of zero: with the wrong values in the data the model was worse than always answering with the mean price.

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

Before the split or after it? (a) Dropping an identification number. (b) Encoding yes and no as 1 and 0 with a dictionary. (c) Target encoding of a column. (d) Fitting a StandardScaler. (e) Repairing weights that were typed in the wrong unit.

Show a hint
Does the step learn something from the rows? If it does, it comes after the split and learns from the training data.
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

Common mistakes
MistakeWhy it is wrongRight
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 1+(n−1)×p1 + (n - 1) \times p (Part 4).

Q1:position 1+8×0.25=3the third value: Q1=3Q3:position 1+8×0.75=7the seventh value: Q3=5IQR=5−3=21.5×IQR=3lower limit=3−3=0upper limit=5+3=8\begin{aligned} Q_1:\quad & \text{position } 1 + 8 \times 0.25 = 3 \\ & \text{the third value: } Q_1 = 3 \\[6pt] Q_3:\quad & \text{position } 1 + 8 \times 0.75 = 7 \\ & \text{the seventh value: } Q_3 = 5 \\[10pt] & \text{IQR} = 5 - 3 = 2 \\[4pt] & 1.5 \times \text{IQR} = 3 \\[10pt] & \text{lower limit} = 3 - 3 = 0 \\[4pt] & \text{upper limit} = 5 + 3 = 8 \end{aligned}

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. z=x−meanstandard deviationz = \frac{x - \text{mean}}{\text{standard deviation}} (Part 4).

94:94−708=350:50−708=−2.598:98−708=3.5\begin{aligned} 94:\quad & \frac{94 - 70}{8} = 3 \\[4pt] 50:\quad & \frac{50 - 70}{8} = -2.5 \\[4pt] 98:\quad & \frac{98 - 70}{8} = 3.5 \end{aligned}

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?

Solved problems
districtprice
North90
North110
South150
South170
South160
West200

Idea. The mean of the target in every category; an unknown category gets the mean of all training rows (Part 9).

North:90+1102=100South:150+170+1603=160West:2001=200all rows:90+110+150+170+160+2006=8806=146.667\begin{aligned} \text{North:}\quad & \frac{90 + 110}{2} = 100 \\[6pt] \text{South:}\quad & \frac{150 + 170 + 160}{3} = 160 \\[6pt] \text{West:}\quad & \frac{200}{1} = 200 \\[10pt] \text{all rows:}\quad & \frac{90 + 110 + 150 + 170 + 160 + 200}{6} \\[4pt] & = \frac{880}{6} = 146.667 \end{aligned}

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).

Python
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).

Python
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).

Python
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).

Python
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:

Python, continues from the cells above
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).

Python
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).

Python
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).

Python
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:

Python, continues from the cells above
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).

Python
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:

Python, continues from the cells above
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).

Python
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:

Python, continues from the cells above
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:

Python
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:

Python, continues from the cells above
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:

Python, continues from the cells above
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. 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
    Q1Q_1 is the third value and Q3Q_3 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.

    Q1=23Q3=27IQR=27−23=41.5×4=6lower limit=23−6=17upper limit=27+6=33\begin{aligned} & Q_1 = 23 \qquad Q_3 = 27 \\[4pt] & \text{IQR} = 27 - 23 = 4 \qquad 1.5 \times 4 = 6 \\[8pt] & \text{lower limit} = 23 - 6 = 17 \\[4pt] & \text{upper limit} = 27 + 6 = 33 \end{aligned}

    Only 58 lies outside the limits.

  2. 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
    z=x−meanstandard deviationz = \frac{x - \text{mean}}{\text{standard deviation}}.
    Show one possible solution

    Answer: (a) 3.5; (b) −2.5-2.5; (c) the parcel of 26 kg.

    (a)26−124=3.5(b)2−124=−2.5\begin{aligned} \text{(a)}\quad & \frac{26 - 12}{4} = 3.5 \\[6pt] \text{(b)}\quad & \frac{2 - 12}{4} = -2.5 \end{aligned}

    (c) Only 3.5 lies beyond 3. The z-score −2.5-2.5 is far from the mean, but inside the limits.

  3. 3.Choose the encoding. (a) size of a shirt: S, M, L, XL. (b) colour of a shirt: red, blue, green, black. (c) gift_wrap: yes, no. (d) postcode of 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. 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.

    (a)10+142=12(b)20+22+243=22(c)10+14+20+22+245=905=18\begin{aligned} \text{(a)}\quad & \frac{10 + 14}{2} = 12 \\[6pt] \text{(b)}\quad & \frac{20 + 22 + 24}{3} = 22 \\[6pt] \text{(c)}\quad & \frac{10 + 14 + 20 + 22 + 24}{5} = \frac{90}{5} = 18 \end{aligned}

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.

The columns of phones.csv
ColumnMeaning
phone_idthe identification number of the phone
seller_namethe first name of the seller
currencythe currency of the price
brandthe maker (10 invented brands)
materialthe material of the body: plastic, glass or metal
conditionused, good, like new or new
dual_simyes or no
ram_gbthe memory in gigabytes
storage_gbthe storage in gigabytes
screen_inchthe size of the screen in inches
screen_cmthe size of the screen in centimetres
weight_gthe weight in grams
camera_mpthe megapixels of the camera
age_monthsthe age in months
pricethe 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.

Download

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.

  1. 5.Read phones.csv into df and drop the columns phone_id, seller_name and currency. Print the shape of the table.
    Show a hint
    df = pd.read_csv("phones.csv"), df = df.drop(columns=["phone_id", "seller_name", "currency"]), then print(df.shape).
    Show one possible solution
    Python
    import pandas as pd
    
    df = pd.read_csv("phones.csv")
    df = df.drop(columns=["phone_id", "seller_name", "currency"])
    
    print(df.shape)

    Output

    (260, 12)
  2. 6.Calculate the upper limit of the IQR rule for price into the variable upper. 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 with 0.75 for q3, then upper = 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 above
    q1 = 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
  3. 7.Calculate the z-scores of price and 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(), then print(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 above
    z = (df["price"] - df["price"].mean()) / df["price"].std()
    
    print(df[z > 3]["price"].sort_values().tolist())

    Output

    [6040, 9900, 10560, 10920, 13880]
  4. 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], then print(df.shape) and print(df["price"].max()).
    Show one possible solution
    Python, continues from the cells above
    df = df[df["price"] <= upper]
    
    print(df.shape)
    print(df["price"].max())

    Output

    (255, 12)
    1770
  5. 9.Some weights were typed in kilograms (0.19 where 190 was meant). Print how many values of weight_g are 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()), then df.loc[df["weight_g"] < 10, "weight_g"] = df["weight_g"] * 1000 and print(df["weight_g"].min()).
    Show one possible solution
    Python, continues from the cells above
    print((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.

  1. 10.Encode dual_sim as 0 (no) and 1 (yes), and condition in 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 for condition, then print(df[["dual_sim", "condition"]].head(3)).
    Show one possible solution
    Python, continues from the cells above
    df["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
  2. 11.One-hot encode material inside the table, with drop_first=True and dtype=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), then print(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 above
    df = 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']
  3. 12.Split df into train and test with test_size=0.25 and random_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, then train, test = train_test_split(df, test_size=0.25, random_state=7), train = train.copy() and test = test.copy().
    Show one possible solution
    Python, continues from the cells above
    from 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)
  4. 13.Target-encode brand into a new column brand_price in train and test, with the mean prices of train. Then drop brand from 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(), then train["brand_price"] = train["brand"].map(brand_means) and the same for test (a gap in test is filled with .fillna(train["price"].mean())). Drop with train = train.drop(columns=["brand"]). Print brand_means.round(0).
    Show one possible solution
    Python, continues from the cells above
    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(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
  5. 14.Print the correlation of every column of train with price, 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_mp has the weakest correlation; screen_inch and screen_cm are one measurement in two units. Both camera_mp and screen_cm are left out in the next step.
    Show one possible solution
    Python, continues from the cells above
    print(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.

  1. 15.The list features is in the editor. Make X_train and X_test from these columns of train and test, and y_train and y_test from price. Print the shapes of X_train and X_test on one line. This step continues from Step 13.
    Show a hint
    X_train = train[features] and y_train = train["price"], and the same for test.
    Show one possible solution
    Python, continues from the cells above
    features = ["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)
  2. 16.Scale the features with a StandardScaler called scaler into X_train_scaled and X_test_scaled. Print the column means of X_test_scaled, rounded to 2 decimals. This step continues from Step 15.
    Show a hint
    from sklearn.preprocessing import StandardScaler, then scaler.fit_transform(X_train) for the training data and scaler.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, check test_size=0.25 and random_state=7 in Step 12.
    Show one possible solution
    Python, continues from the cells above
    from sklearn.preprocessing import StandardScaler
    
    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)
    
    print(X_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]
  3. 17.Train a LinearRegression called model on the scaled training data. Print the training score, then the test score, each rounded to 3 decimals. This step continues from Step 16.
    Show a hint
    from sklearn.linear_model import LinearRegression, model.fit(X_train_scaled, y_train), then model.score(X_train_scaled, y_train) and model.score(X_test_scaled, y_test).
    Show one possible solution
    Python, continues from the cells above
    from sklearn.linear_model import LinearRegression
    
    model = LinearRegression()
    model.fit(X_train_scaled, y_train)
    
    print(round(model.score(X_train_scaled, y_train), 3))
    print(round(model.score(X_test_scaled, y_test), 3))

    Output

    0.946
    0.947
  4. 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 loop print(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 above
    for 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.

Question 1

1.What is an outlier?

Question 2

2.A column has Q1=20Q_1 = 20 and Q3=30Q_3 = 30. What is the upper limit of the IQR rule?

Question 3

3.Why can the z-score rule miss an outlier?

Question 4

4.Which rule is the usual first choice for finding outliers, also in skewed columns?

Question 5

5.A weight of 1,850 kg stands in the column of laptop weights, clearly typed in grams. What is the best way to handle it?

Question 6

6.IQR limits are used to remove extreme rows. From which data are the limits calculated?

Question 7

7.Real, rare, expensive laptops are in the test data. What is done with them?

Question 8

8.Why must a column such as type (office, gaming, ultrabook) be encoded?

Question 9

9.Which column is right for label (ordinal) encoding?

Question 10

10.A column fuel has the values petrol, diesel and electric. What does one-hot encoding with drop_first=True make of it?

Question 11

11.What does target encoding replace a category with?

Question 12

12.A column street has 400 different values and no order. Why is one-hot encoding a poor choice?

0 of 12 answered.

15Summary

Summary
Outliers
IQR rulebelow Q1−1.5×IQRQ_1 - 1.5 \times \text{IQR} or above Q3+1.5×IQRQ_3 + 1.5 \times \text{IQR}; the usual first choice
z-scorebelow −3-3 or above 3; for bell-shaped columns with many rows
Mistakesrepair (cause known) or remove; whole table, before the split
Real extreme valuesoften keep; otherwise cap or remove in the training data, with limits from the training data
Test dataonly mistakes are cleaned; real values stay
Columnsselected ones with continuous measurements, never all
Summary
The columnEncoding
two values0 and 1
ordered categorieslabel (ordinal) encoding in your own order
no order, few categoriesone-hot (dummy) encoding, drop_first=True for linear models
no order, many categoriestarget encoding, from the training data
no order, many categories, frequency mattersfrequency encoding
Summary
CodeWhat 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] / 1000repairs 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

  1. Drop the columns without information.
  2. Clean the mistakes: repair or remove.
  3. Encode what needs no learning: 0 and 1, ordinal, one-hot.
  4. Split.
  5. Learn from the training data: limits for real extreme values, target or frequency encoding, the selection of features, the scaler.
  6. Train on the training data, judge on the test data.

Rules to keep

  1. A rule finds outliers. You decide whether they are mistakes.
  2. Mistakes are cleaned everywhere. Real extreme values stay in the test data.
  3. Whatever learns from the rows learns from the training rows only.
  4. Never drop a text column that carries information: encode it.
  5. Numbers in order only for categories in order. Without order: one column per category.
  6. Target encoding only with the means of the training data.
  7. 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.