Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 42 of 62 · 35 min
Feature selection, leakage and pipelines
Explanation
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.
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))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
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)
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Encoding categories and datesClustering, dimensionality reduction and feature engineering · same module
- Other clustering methods and dimensionality reductionClustering, dimensionality reduction and feature engineering · same module
- Cross-validation and tuning hyperparametersEvaluating models
- Simple sorts: bubble, selection and insertionData Structures and Algorithms (DSA) for interviews · Sorting and searching
- Continuous integration, delivery and deploymentDevOps: Git, Docker, Kubernetes and CI/CD · CI/CD pipelines
- Bias and fairnessEthics, privacy and careers
Questions people ask about this
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.
In scikit-learn, which method learns from training data?Related
Which model does NOT need feature scaling?Related
Answer: Random forest
Trees split one feature at a time on thresholds.
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
- This is the last topic of “Clustering, dimensionality reduction and feature engineering”. The module exam comes next.
- Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.