Skip to main content

06 - Feature Engineering and Preprocessing: Data Ready for ML

Impute, encode, scale and detect outliers in scikit-learn, then measure data leakage (0.79 against 0.50 on pure noise) and fix it with a Pipeline.

What do you think about this article?

At a Glance

Impute, encode, scale and detect outliers in scikit-learn, then measure data leakage (0.79 against 0.50 on pure noise) and fix it with a Pipeline.

Why the model depends on how you prepare the data

A Machine Learning algorithm sees only numbers in a table. If an income is written in euros and an age in years, if a value is missing, if a city is a string, it is up to your code to decide how to translate all this before fit, and every choice changes the result. In this article you build that layer with scikit-learn: missing values, categories, different scales, outliers, and finally the Pipeline that avoids the most insidious mistake, data leakage. Every choice is tested with a listing you can rerun. It assumes the basics of the introduction to the series, and it helps to have seen distances at work, for example with K-Nearest Neighbors.

A sentence you read everywhere says that 80% of the time of a project goes into data preparation: I did not find it in any primary source, so I do not repeat it. What can be demonstrated is the effect: in this article scaling alone, the choice between mean and median alone, or a step in the wrong place of the procedure change the result by twenty or thirty points.

Missing values: drop, impute, or flag

Faced with a missing value you have three paths. Dropping the row (or the column) is the simplest option, but with 25% of missing values, as in our example, you throw away a quarter of the data. Imputing means filling the hole with an estimate: the mean, the median, the most frequent value for categories, or a value inferred from nearby points. The third path, often forgotten, is to keep track of the fact that the datum was missing, because the absence can be informative: someone who does not declare their income is not a random sample. The listing uses eight people, two missing values per column, and an extreme income (900,000 euros) to bring out the difference between mean and median.

Python - Imputation: mean, median, neighbors and indicator
import numpy as np
import pandas as pd
from sklearn.impute import KNNImputer, SimpleImputer

df = pd.DataFrame({
    "eta":     [25, 30, np.nan, 45, 35, np.nan, 28, 50],
    "reddito": [30000, np.nan, 45000, 60000, np.nan, 55000, 32000, 900000],   # the last one is an extreme value
})
print("missing per column:", df.isnull().sum().to_dict())
print("missing percentage:", (df.isnull().mean() * 100).round(1).to_dict())

media = SimpleImputer(strategy="mean").fit(df[["reddito"]])
mediana = SimpleImputer(strategy="median").fit(df[["reddito"]])
print("value imputed with the mean:   ", round(float(media.statistics_[0])))
print("value imputed with the median: ", round(float(mediana.statistics_[0])))

knn = KNNImputer(n_neighbors=2).fit_transform(df)
print("KNNImputer, income of the two rows with missing values:", knn[[1, 4], 1].round())

con_indicatore = SimpleImputer(strategy="median", add_indicator=True).fit_transform(df[["reddito"]])
print("with add_indicator, columns:", con_indicatore.shape[1], "- last column (1 = was missing):", con_indicatore[:, 1].astype(int))

# Output:
# missing per column: {'eta': 2, 'reddito': 2}
# missing percentage: {'eta': 25.0, 'reddito': 25.0}
# value imputed with the mean:    187000
# value imputed with the median:  50000
# KNNImputer, income of the two rows with missing values: [31000. 46000.]
# with add_indicator, columns: 2 - last column (1 = was missing): [0 1 0 0 1 0 0 0]

The output says it clearly: with the extreme income the mean of the present values is 187,000, a number that resembles none of the people in the sample, while the median is 50,000, a plausible value. That is why, with skewed distributions such as incomes, the median is almost always the best choice. KNNImputer with two neighbors looks at the most similar rows on the other columns and estimates 31,000 and 46,000, different values for each row because it takes the age into account; it is more expensive but exploits the correlation between variables. With add_indicator=True the imputer adds a second column that is 1 where the datum was missing, so the model can also learn from the absence. A warning about the point at which you impute: median and mean must be computed on the training set only. If you compute them on the whole dataset before the split, the section on leakage shows how much it costs.

Categorical variables: numbers without inventing an order

A model does not know what "red" is. One-hot encoding creates one column per category, with 1 where the category is present: no order is introduced, but with a high-cardinality variable (thousands of postal codes) you get thousands of columns. Ordinal encoding assigns integers in order, and it is correct only when an order exists, as in the sizes S < M < L < XL; applying it to colors would tell the model that green is worth twice blue. Target encoding replaces the category with the mean of the target in that category: scikit-learn offers it with TargetEncoder and computes it in fit_transform with a cross-fitting scheme precisely to reduce the risk that the variable "sees" the target it has to predict. The listing shows one-hot and ordinal and then a production situation: a color never seen in training arrives. The data values stay in Italian, as in the code (rosso is red, blu blue, verde green, giallo yellow).

Python - One-hot, ordinal and a category never seen
import pandas as pd
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder

df = pd.DataFrame({
    "colore": ["rosso", "blu", "verde", "rosso", "blu"],
    "taglia": ["S", "M", "L", "XL", "M"],
})

ohe = OneHotEncoder(sparse_output=False)
colonne = ohe.fit_transform(df[["colore"]])
print(ohe.get_feature_names_out().tolist())
print(colonne.astype(int))

oe = OrdinalEncoder(categories=[["S", "M", "L", "XL"]])
print("ordinal size:", oe.fit_transform(df[["taglia"]]).ravel().astype(int))

# What happens with a category never seen in training?
nuovo = pd.DataFrame({"colore": ["giallo"]})
try:
    ohe.transform(nuovo)
except ValueError as errore:
    print("error:", str(errore).splitlines()[0])
tollerante = OneHotEncoder(sparse_output=False, handle_unknown="ignore").fit(df[["colore"]])
print("with handle_unknown='ignore':", tollerante.transform(nuovo).astype(int))

# Output:
# ['colore_blu', 'colore_rosso', 'colore_verde']
# [[0 1 0]
#  [1 0 0]
#  [0 0 1]
#  [0 1 0]
#  [1 0 0]]
# ordinal size: [0 1 2 3 1]
# error: Found unknown categories ['giallo'] in column 0 during transform
# with handle_unknown='ignore': [[0 0 0]]

The columns are in alphabetical order (colore_blu, colore_rosso, colore_verde) and each row has a single 1: the first row is "rosso" (red), the second "blu" (blue). The ordinal size becomes 0, 1, 2, 3, 1 only because we listed the order ourselves in categories; without that argument the order would be alphabetical (L, M, S, XL), that is wrong. The part that interests whoever has to put a model into production is the end: a "giallo" (yellow) the encoder was not trained on causes a ValueError and the service stops, while with handle_unknown='ignore' the new category becomes a row of zeros and the prediction goes on. Both choices are right in different contexts: during development the error warns you that the data have changed, in production you usually want tolerance.

Scaling: a choice that depends on outliers, not on "normality"

Many algorithms (KNN, SVM, regularized regressions, neural networks) compare variables with each other and get confused when one is in grams and another in kilometers; trees, instead, do not need it. Three scalers cover almost all cases. StandardScaler subtracts the mean and divides by the standard deviation. MinMaxScaler brings the values into the interval [0, 1] using minimum and maximum. RobustScaler uses the median and the interquartile range. The rule you often read, "StandardScaler for normal distributions, MinMax for the others", is not the one that matters in practice: the criterion is the presence of extreme values, and the scikit-learn guide says so, to use RobustScaler when the data contain many outliers. In the listing there are six weights, one of them anomalous.

Python - Three scalers compared with an outlier
import numpy as np
from sklearn.preprocessing import MinMaxScaler, RobustScaler, StandardScaler

peso = np.array([[100], [120], [130], [150], [170], [3000]], dtype=float)   # grams; the last one is an outlier

for nome, scaler in (("StandardScaler", StandardScaler()), ("MinMaxScaler", MinMaxScaler()), ("RobustScaler", RobustScaler())):
    print(f"{nome:15s}", scaler.fit_transform(peso).ravel().round(2))

# Output:
# StandardScaler  [-0.48 -0.46 -0.45 -0.43 -0.41  2.24]
# MinMaxScaler    [0.   0.01 0.01 0.02 0.02 1.  ]
# RobustScaler    [-0.94 -0.47 -0.24  0.24  0.71 67.29]

With the anomalous weight of 3000 g, StandardScaler brings the five normal weights between -0.48 and -0.41, an interval of 0.07 in which the model struggles to tell them apart, and the outlier to 2.24. MinMaxScaler is worse: the five weights end up between 0.00 and 0.02, crushed against zero, because the maximum is defined by the outlier. RobustScaler preserves the structure of the five normal values (from -0.94 to 0.71) and sends the outlier to 67.29: it isolates it instead of letting it deform the scale. This does not mean it is always better: the outlier remains an enormous number for a model sensitive to distances, and the real decision is whether to keep it, correct it or discard it, the subject of the next section.

Outliers: three methods, and a trap in the threshold 3

An outlier can be a measurement error, a corrupted datum or a real and rare case, and the fix depends on the cause. To find them there are three approaches. The z-score counts how many standard deviations separate a value from the mean, with a typical threshold of 3. The IQR method considers anomalous whatever lies beyond 1.5 times the interquartile range from the first or the third quartile. The Isolation Forest isolates points with random trees: anomalous points require fewer questions to be separated. The listing applies them to eight measurements, one of which (400) is plainly wrong.

Python - Z-score, IQR and Isolation Forest on the same eight values
import numpy as np
from sklearn.ensemble import IsolationForest

x = np.array([50, 52, 51, 49, 53, 48, 50, 400], dtype=float)    # eight measurements, one obviously wrong

z = (x - x.mean()) / x.std()
print("maximum z-score:", z.max().round(2), "- mathematical limit with n=8:", round(float(np.sqrt(len(x) - 1)), 2))
print("beyond threshold 3:", int(np.sum(np.abs(z) > 3)), "points")

q1, q3 = np.percentile(x, [25, 75])
iqr = q3 - q1
fuori = x[(x < q1 - 1.5 * iqr) | (x > q3 + 1.5 * iqr)]
print(f"IQR: Q1={q1}, Q3={q3}, limiti [{q1 - 1.5 * iqr}, {q3 + 1.5 * iqr}] -> outside:", fuori)

iso = IsolationForest(random_state=0, contamination=1 / 8).fit(x.reshape(-1, 1))
print("IsolationForest (-1 = anomalia):", iso.predict(x.reshape(-1, 1)))

# Output:
# maximum z-score: 2.65 - mathematical limit with n=8: 2.65
# beyond threshold 3: 0 points
# IQR: Q1=49.75, Q3=52.25, limiti [46.0, 56.0] -> outside: [400.]
# IsolationForest (-1 = anomalia): [ 1  1  1  1  1  1  1 -1]

The result is surprising: the z-score flags nothing. The reason is mathematical and not a bug in the code: with n values and the standard deviation computed on the population (np.std), no standardized deviation can exceed √(n−1). With eight values the maximum possible is 2.65, and our 400 practically reaches it (2.65): being the only distant value, it drags the mean and the standard deviation along with it and "hides" itself. As a consequence the threshold 3 can never trigger with fewer than ten observations. The IQR method, which uses quartiles and is therefore not influenced by the extreme value, finds the 400 (limits 46 and 56), and the Isolation Forest isolates it as well. Before using the z-score, then, check how much data you have, and prefer IQR or median and MAD with small samples.

Data leakage, measured

Data leakage is the use, during training, of information that you would not have in production: the classic case is computing on the whole dataset a step that learns from the data (the scaler's mean, the imputer's median, variables chosen by a selection) and only afterwards splitting into train and test. The test set has already influenced the model, and the score is optimistic. The scikit-learn guide on common pitfalls gives precisely the example of variable selection. The listing recreates the experiment in its purest form: 100 samples, 1000 variables and a randomly drawn label, so there is nothing to learn and the right accuracy is 0.5. It repeats the test on 20 random datasets and compares two procedures.

Python - Variable selection inside and outside cross-validation
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

sbagliato, giusto = [], []
for seme in range(20):
    rng = np.random.default_rng(seme)
    X = rng.normal(size=(100, 1000))          # 100 samples, 1000 variables: pure noise
    y = rng.integers(0, 2, size=100)          # random labels: no signal to find

    # Wrong: I pick the 10 "best" variables on ALL the data, and only afterwards do the cross-validation
    X_scelte = SelectKBest(f_classif, k=10).fit_transform(X, y)
    sbagliato.append(cross_val_score(LogisticRegression(), X_scelte, y, cv=5).mean())

    # Right: the selection is inside the Pipeline, so it is redone in every fold on the training part only
    modello = make_pipeline(SelectKBest(f_classif, k=10), LogisticRegression())
    giusto.append(cross_val_score(modello, X, y, cv=5).mean())

print(f"selection outside the cross-validation: mean accuracy {np.mean(sbagliato):.2f} on 20 random datasets")
print(f"selection inside the Pipeline:          mean accuracy {np.mean(giusto):.2f} on 20 random datasets")

# Output:
# selection outside the cross-validation: mean accuracy 0.79 on 20 random datasets
# selection inside the Pipeline:          mean accuracy 0.50 on 20 random datasets

With the selection done before the cross-validation the model gets 0.79 on average on data that are pure noise: it has "discovered" a signal that does not exist, because among 1000 random variables there are always some correlated by chance with the labels, and having chosen them by looking at the labels of the whole dataset brought that information into the test. With the selection inside the Pipeline the average is 0.50, the correct value. Almost thirty points of difference are not a statistical detail: it is the difference between delivering a model that works and one that collapses on the first day. The rule that follows is mechanical: every step that uses fit on the data (imputers, scalers, encoders, selection) goes inside the pipeline, so that cross-validation redoes it on the training part of each fold only.

A complete pipeline with ColumnTransformer

The ColumnTransformer applies different transformations to groups of columns: here the numeric ones go through median imputation and scaling, the categorical ones through a tolerant one-hot. The outer pipeline ties the preprocessing to the model. Unlike many examples that use random labels (and therefore produce an accuracy of 0.5 that proves nothing), the listing generates a target that really depends on income and city, so as to be able to measure that the pipeline learns something, and compares it with the baseline that always predicts the most frequent class.

Python - Pipeline with imputation, scaling, one-hot and model
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

rng = np.random.default_rng(42)
n = 600
df = pd.DataFrame({
    "eta": rng.integers(18, 70, n).astype(float),
    "reddito": rng.normal(40000, 15000, n),
    "citta": rng.choice(["Milano", "Roma", "Napoli", "Torino"], n),
})
# The target really depends on the data: high income and Milano or Torino raise the probability of 1
punteggio = (df["reddito"] - 40000) / 15000 + np.where(df["citta"].isin(["Milano", "Torino"]), 0.8, 0.0)
df["target"] = (punteggio + rng.normal(0, 0.8, n) > 0.4).astype(int)
for colonna in ("eta", "reddito"):                                # 10% of the numeric values are missing
    df.loc[rng.random(n) < 0.1, colonna] = np.nan

numeriche, categoriche = ["eta", "reddito"], ["citta"]
prep = ColumnTransformer([
    ("num", Pipeline([("imputer", SimpleImputer(strategy="median")), ("scaler", StandardScaler())]), numeriche),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categoriche),
])
modello = Pipeline([("prep", prep), ("rf", RandomForestClassifier(n_estimators=200, random_state=0))])

X, y = df[numeriche + categoriche], df["target"]
base = cross_val_score(DummyClassifier(strategy="most_frequent"), X, y, cv=5).mean()
punti = cross_val_score(modello, X, y, cv=5)
print(f"baseline: {base:.3f}   pipeline: {punti.mean():.3f} (+/- {punti.std():.3f})")
modello.fit(X, y)
print("columns after preprocessing:", modello[:-1].get_feature_names_out().tolist())

# Output:
# baseline: 0.552   pipeline: 0.728 (+/- 0.050)
# columns after preprocessing: ['num__eta', 'num__reddito', 'cat__citta_Milano', 'cat__citta_Napoli', 'cat__citta_Roma', 'cat__citta_Torino']

The baseline is 0.552 (the most frequent class weighs 55%); the pipeline reaches 0.728 with a standard deviation of 0.050 across the folds, so it gains about seventeen points over the floor. The last line prints the column names after preprocessing: get_feature_names_out is the way to check that the one-hot produced one column per city and that the numeric ones kept their names. The result is not exceptional by design: the target has a lot of noise, and a model must not obtain more than the data allow. If you get 99% on a real and difficult problem, suspect a leakage before celebrating.

Feature engineering: using what you know about the domain

Feature engineering creates new variables from existing ones, and its value lies in bringing into the data what you know and the model cannot discover by itself. Common examples: the ratio between two columns (price per square meter), seniority computed from a date, the day of the week of a purchase, the logarithm of a highly skewed quantity. The listing shows the most instructive case: revenue that is the product of visitors, conversion rate and average basket. A linear model adds up the contributions, and a multiplicative relationship cannot be represented by it. The logarithm turns the product into a sum, and the linear model becomes adequate.

Python - The logarithm turns a product into a sum
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score

# Revenue of an online shop = visitors x conversion rate x average basket (multiplicative relationship)
rng = np.random.default_rng(1)
n = 400
visitatori = rng.lognormal(8, 0.8, n)
conversione = rng.uniform(0.01, 0.05, n)
scontrino = rng.uniform(20, 120, n)
fatturato = visitatori * conversione * scontrino * rng.lognormal(0, 0.05, n)

X_grezze = np.column_stack([visitatori, conversione, scontrino])
X_log = np.log(X_grezze)                       # the logarithm turns the product into a sum
r2_grezze = cross_val_score(LinearRegression(), X_grezze, fatturato, cv=5, scoring="r2").mean()
r2_log = cross_val_score(LinearRegression(), X_log, np.log(fatturato), cv=5, scoring="r2").mean()
print(f"R2 with the raw variables:         {r2_grezze:.3f}")
print(f"R2 after the logarithm (on log y): {r2_log:.3f}")
print("coefficients on the logarithm:", LinearRegression().fit(X_log, np.log(fatturato)).coef_.round(2))

# Output:
# R2 with the raw variables:         0.783
# R2 after the logarithm (on log y): 0.997
# coefficients on the logarithm: [1. 1. 1.]

With the raw variables linear regression obtains an R² of 0.783 in cross-validation; after the logarithm, of both the variables and the revenue, it rises to 0.997. The three coefficients are 1.00, 1.00, 1.00: they are exactly the exponents of the relationship revenue = visitors × conversion × basket with which I generated the data, and the model found them again. It is not a trick to repeat everywhere, but the example shows the general lesson: the right transformation is worth more than a more powerful algorithm. On real data you do not know the relationship, but you can test it with cross-validation, always comparing with the version without transformation.

One last note on variable selection: methods such as VarianceThreshold (discards nearly constant columns) and SelectKBest (keeps the K best according to a statistical test) are described in the scikit-learn guide and the same rules seen above apply: they go inside the pipeline. The correlation between variables is checked beforehand, but the removal of a redundant column, such as that of a variable highly correlated with another, must be decided with cross-validation, not by eye.

What you can do now

You can choose between mean, median and neighbors to impute, and you know why an extreme income brings the mean to almost four times the median. You can encode nominal and ordinal categories and handle those never seen. You can choose the scaler by looking at the outliers and detect anomalous values without falling into the trap of the threshold 3. Above all, you can put everything in a Pipeline so that cross-validation does not know the test set. The next step is knowing how far to trust the number that comes out: the evaluation metrics.

Preprocessing returns at three points of the series: in regression (scaling to make gradient descent converge), in ensembles (where the pipeline makes the comparison honest) and in the end-to-end pipeline that takes it to production.

Frequently asked questions

When is it better to impute with the median instead of the mean?

When the distribution is skewed or contains extreme values, such as incomes: a single value of 900,000 euros brings the mean of the example to 187,000, while the median stays at 50,000.

How do you avoid data leakage in scikit-learn?

By putting every step that uses fit on the data (imputation, scaling, encoding, variable selection) inside a Pipeline, so that cross-validation reruns it on the training part of each fold only.

Which scaler to choose in the presence of outliers?

RobustScaler, which uses the median and the interquartile range: in the example it preserves the difference between the five normal weights, while StandardScaler and MinMaxScaler compress them into an interval of a few hundredths.

Sources

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects