Skip to content

Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 42 of 62 · 35 min

Feature selection, leakage and pipelines

Explanation

Feature selection keeps the features that help and drops the ones that add noise, cost or risk. Leakage features must always go. A scikit-learn Pipeline chains preprocessing and the model so every step is fitted on training data only, which prevents leakage and makes deployment simple.

Why select features?

More features are not always better. Useless or duplicate features slow training, make overfitting easier, make models harder to explain, and cost money to collect in production. Some features are dangerous: they leak the answer or bring in unfair bias. Feature selection is the habit of keeping only what earns its place.

Three families of methods

  • Filter methods: score each feature on its own, before modelling. Drop near-constant columns (very low variance), and drop one of two features that are almost perfectly correlated, such as "price incl. GST" and "price excl. GST".
  • Wrapper methods: try subsets of features with the model and keep the best by cross-validation (for example, recursive feature elimination). Accurate but slow.
  • Embedded methods: the model selects while training. Lasso (L1) pushes useless weights to zero; tree ensembles give importances.

Leakage features: the ones that must go

Ask of every feature: "Would I know this value at the moment I make the prediction?" Features filled in after the outcome, such as "loan_closed_date", "refund_amount" or "final_diagnosis_code", leak the answer. Also watch for ids that encode time or the outcome, and for aggregates computed over the future. When a single feature gives an amazing score on its own, investigate it before celebrating.

Pipelines: preprocessing done right

A Pipeline is a chain of steps, such as "fill missing values → scale → model", treated as one model. When you call fit, each step is fitted on the training data only; when you call predict, the same fitted steps are applied to new data. Inside cross-validation, the whole pipeline is refitted in each fold, so no information leaks across folds. And in production you save one object instead of five.

python
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = ["age", "income", "existing_loans"]
categorical = ["city", "employment_type"]

prep = ColumnTransformer([
    ("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
ColumnTransformer applies different steps to different columns. The whole thing can go into cross_val_score or GridSearchCV. Shown only.

Feature stores, briefly

In larger companies, a feature store is a shared system that computes and serves features (like "orders in the last 7 days") the same way for training and for live prediction, so the two never drift apart.

Common mistakes

  • Selecting features using the whole dataset, then cross-validating. The selection itself leaked. Fix: put selection inside the pipeline.
  • Dropping a feature only because it has low correlation with the target; it may matter in combination with others.
  • Keeping an id column because it "improved" the score. It is usually leakage or chance.
  • Writing preprocessing twice, once in a notebook and once in the app, and getting different results. Fix: one pipeline object.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Feature selection, leakage and pipelines · 1/6

Feature selection

More features are not always better. Keep only those that earn their place.

Prefer a video by a teacher? Find free videos on “scikit-learn pipeline column transformer feature selection data leakage” on YouTube ↗

In real life: One pipeline from notebook to app

A team building a loan pre-approval model kept their median-filling, scaling and one-hot encoding in a single scikit-learn Pipeline. When the app went live, engineers loaded the saved pipeline and passed raw application data straight in. A competing team that had re-written the preprocessing by hand in the app spent weeks chasing a bug where the app filled missing incomes with 0 instead of the median.

Practice (0/2 done)

Task 1 · Code · Python

Write drop_correlated(columns, threshold) where columns is a dict (in a fixed order) mapping feature names to lists of numbers. Walk through the features in order and keep a feature unless the absolute Pearson correlation (statistics.correlation) between it and ANY already-kept feature is greater than threshold. Return the list of kept names.

Task 2 · Practice

A hospital model predicts whether a patient will be admitted to the ICU within 24 hours of arriving at the emergency room. Candidate features: age, oxygen_level_at_arrival, heart_rate_at_arrival, icu_bed_number, triage_category, total_bill_amount, patient_id, arrival_hour. Which features would you drop and why? Which preprocessing steps would go in the pipeline?

Quick quiz

Question 1

1.Which is an embedded feature-selection method?

Question 2

2.What is the main benefit of a scikit-learn Pipeline in cross-validation?

Question 3

3.Which feature leaks the answer when predicting customer churn next month?

Question 4

4.You pick the top 20 features using the whole dataset, then run cross-validation. What is wrong?

Question 5

5.What does ColumnTransformer do?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which is an embedded feature-selection method?

Answer: Lasso pushing weights to zero

Selection happens during model training.

What is the main benefit of a scikit-learn Pipeline in cross-validation?

Answer: Preprocessing is refitted on each training fold, preventing leakage

Each fold's scaler and imputer see only that fold's training data.

Which feature leaks the answer when predicting customer churn next month?

Answer: "account_cancelled_on" date

It only exists after the customer has left.

You pick the top 20 features using the whole dataset, then run cross-validation. What is wrong?

Answer: Feature selection saw the validation folds, so the CV score is optimistic

Selection is part of training and must happen inside the folds.

What does ColumnTransformer do?

Answer: Applies different preprocessing to different groups of columns

For example scaling for numbers and one-hot for categories.

You scale features using the mean and standard deviation of the WHOLE dataset before splitting. What is the problem?Related

Answer: Test-set information leaks into training

Fit preprocessing on the training set only, then apply it to the test set.

From Train, validation and test sets

In scikit-learn, which method learns from training data?Related

Answer: fit

fit(X, y) trains the model; predict uses it.

From The ML workflow end to end

Which model does NOT need feature scaling?Related

Answer: Random forest

Trees split one feature at a time on thresholds.

From Scaling and transforming numbers

In 5-fold cross-validation, how many times is the model trained?Related

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Clustering, dimensionality reduction and feature engineering”. The module exam comes next.
  2. Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.

← Previous: Scaling and transforming numbers