Sub topic 13
Measuring whether a feature helps
This chapter assumes you can build a scikit-learn Pipeline with ColumnTransformer (previous chapter), you know what a train/test split is, and you understand data leakage as described earlier. Here you will learn how to decide whether a new feature or preprocessing step improves a model, and how to avoid fooling yourself.
Why a single score is not enough
You add a feature, retrain, and the validation score goes from 0.81 to 0.82. Did the feature help? Possibly. But a single split gives a noisy estimate. A different random split could move the score by more than 0.01. Without a measure of that noise, you cannot tell a real gain from luck.
Cross-validation addresses this. It splits the training data into k folds, trains on k−1 folds, scores on the held-out fold, and repeats so each fold is held out once. You get k scores. Their mean estimates performance, and their spread estimates how much that estimate varies.
Put the whole pipeline inside cross-validation
The most common error is to preprocess the full dataset first and then cross-validate only the model. The imputer's medians, the scaler's means and the encoder's categories would then be computed using rows that later act as validation rows. That is leakage, and it inflates the score.
The fix is to pass the entire pipeline to the cross-validation function. Every fold refits each step on that fold's training rows only.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
numeric_cols = ["age", "income"]
categorical_cols = ["city"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric_cols),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical_cols),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
# X is a DataFrame with the columns above, y is the target
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(scores.mean(), scores.std())scores.mean() is your estimate. scores.std() tells you how much it moves between folds.
Choose the right splitter
The default cv=5 is not always correct. The splitter must reflect how the model will be used.
| Situation | Splitter | Reason |
|---|---|---|
| Classification, balanced or imbalanced | `StratifiedKFold` | Keeps class proportions similar in each fold. |
| Regression, independent rows | `KFold` with `shuffle=True` | Avoids order effects in sorted data. |
| Several rows per customer, device or patient | `GroupKFold` | Keeps all rows of one entity in the same fold. |
| Data ordered in time | `TimeSeriesSplit` | Always trains on the past and validates on the future. |
For classifiers, passing an integer to cv already uses stratification. For regressors it uses plain, unshuffled KFold.
Grouped data deserves special attention. If the same customer appears in both training and validation folds, a feature such as "customer ID frequency" or a high-cardinality encoding can let the model memorise the customer. The score looks excellent, but new customers will not behave that way. Time-based data has the same issue in another form: a random split lets the model see the future.
Compare variants fairly
To judge a feature, build two pipelines that differ only in that feature, and score both with identical folds. Reusing the same splitter object with a fixed random_state ensures the comparison is paired: both variants see the same train and validation rows.
import numpy as np
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
scores_base = cross_val_score(model_base, X, y, cv=cv, scoring="roc_auc")
scores_new = cross_val_score(model_new, X, y, cv=cv, scoring="roc_auc")
diff = scores_new - scores_base
print("mean gain:", diff.mean())
print("std of gain:", diff.std())
print("folds improved:", (diff > 0).sum(), "of", len(diff))Here model_base and model_new are two pipelines of the kind shown above. Repeating the 5-fold split three times gives 15 scores per model, which smooths out the effect of any one split.
Look at the gain in each fold, not only the averages. A feature that improves 14 of 15 folds is more convincing than one with the same mean gain that improves 8 of 15. As a rough guide, treat a mean gain as meaningful when it is larger than the standard deviation of the differences divided by the square root of the number of folds. Fold scores are not fully independent, so this check is a sanity test, not a formal significance test.
Choose a metric that matches the goal
The metric decides what "helps" means.
- Accuracy hides problems when classes are imbalanced. A model that always predicts the majority class can score 95% accuracy with 5% positives.
- ROC AUC measures ranking quality across thresholds. It is useful when you care about ordering, but it can look good on very imbalanced data.
- Average precision (
"average_precision") focuses on the positive class and is often more informative for rare events. - Log loss (
"neg_log_loss") rewards well-calibrated probabilities, which matters if you use the probabilities directly. - For regression,
"neg_root_mean_squared_error"penalises large errors, while"neg_mean_absolute_error"treats all errors equally.
scikit-learn scorers follow a "higher is better" convention, which is why error metrics have a neg_ prefix. A score of −0.40 is better than −0.55.
Keep a final test set untouched
Cross-validation guides your decisions, and every decision you make from it leaks a little information about the validation folds into your choices. After dozens of feature experiments, the best cross-validated score is optimistically biased. This is selection bias, and it grows with the number of variants you try.
The standard protocol is:
- Split off a test set at the start, before any exploration.
- Do all feature work, tuning and model comparison with cross-validation on the remaining training data.
- Fit the chosen pipeline on all training data and score it once on the test set.
If the test score is much lower than the cross-validated score, suspect leakage or overfitting to the validation folds. Do not go back and keep tuning against the test set, or it stops being a test set.
Other checks beyond the score
A score gain is the main evidence, but a few other checks catch problems.
- Suspiciously large gains. If one new feature lifts AUC from 0.75 to 0.99, suspect leakage. Ask whether the feature would be known at prediction time. A field such as "refund issued" in a churn model is a typical culprit.
- Permutation importance. After fitting,
sklearn.inspection.permutation_importanceshuffles one column at a time on held-out data and measures the drop in score. A feature whose shuffling changes nothing is not contributing. Compute it on validation data, not training data, so it reflects generalisation. - Ablation. Remove a feature, or a group of related features, and re-run the cross-validation. If the score does not fall, the feature is not earning its place. Fewer features mean a simpler pipeline and less to maintain in production.
- Variance across folds. If one fold is far worse than the others, look at what is different in it. Rare categories, a different time period, or a group with unusual values often explain it.
Common errors
- Fitting imputers, scalers or encoders on the full dataset before cross-validating.
- Using random folds on time-ordered or grouped data.
- Comparing two variants on different splits, so differences in the split are mistaken for differences in the feature.
- Reporting the best of many cross-validated trials as the expected performance.
- Choosing a metric such as accuracy that does not match the cost of errors.
- Reading a 0.003 difference as real when the fold standard deviation is 0.02.
Exercise
You add a "customer lifetime average order value" feature, computed over all of each customer's orders, to a model that predicts whether an order will be returned. Cross-validated AUC jumps from 0.78 to 0.94. Name two reasons to be suspicious, and say which splitter you would use to check.
Show answer
First, the feature is computed from all of a customer's orders, including the order being predicted and orders that come after it, so it may use information that is not available at prediction time (leakage). Second, if the same customer appears in both training and validation folds, the model can learn customer-specific patterns that will not transfer to new customers. Recompute the feature using only past orders, and evaluate with GroupKFold on customer ID (or TimeSeriesSplit if order time matters) so each customer's rows stay in one fold.
Exercise
A colleague scales the whole dataset with StandardScaler, then calls crossvalscore on a logistic regression, and reports AUC 0.86 for the validation folds. What should change, and why might the real score be lower?
Show answer
Put the StandardScaler and the model in one Pipeline and pass that pipeline to crossvalscore. With the scaler fitted on all rows, each validation fold's mean and standard deviation influenced the scaling, which is a mild form of leakage. The effect is usually small for scaling but can be large for target encoding, feature selection or imputation based on the target. Refitting inside each fold gives an honest estimate, which may be a little lower.