Learning path: Prepare Data for a Machine Learning Model · Step 6 of 7
Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
More columns can hurt. See the curse of dimensionality in numbers (farthest over nearest falls from 46.78 to 1.10), then keep the best columns with SelectKBest inside a pipeline: 5 of 115 columns score 0.83 against 0.849 for all.
What you will learn
- Measure the curse of dimensionality: why near and far blur together as columns grow
- Rank number columns against the target with corrwith on the train rows
- Keep the top k columns with SelectKBest and f_classif inside a Pipeline
- Compare test scores for k = 5, 20 and all, and read which columns were kept
Before you start
- Pipelines and ColumnTransformer
- Correlation and Heatmaps
Pack a weekend bag: passport, charger, jacket, shoes, toothbrush. Five items, the bag is light, and the charger is easy to find. Now pack everything you own, 115 items. The bag is heavy, and the charger is buried somewhere.
In your data, every item is a column. Choosing which columns to pack is feature selection. A smaller set is simpler to train, and the useful columns are easier for the model to find. In this lesson you'll see why too many columns can hurt, then let SelectKBest pick the best ones inside a pipeline.
The curse of dimensionality
Many models rely on "near" and "far". Let's measure what happens to near and far as the number of columns grows. Take 500 random points, each with d numbers (like a row with d columns). Measure the distance from the first point to the other 499, and divide the farthest by the nearest:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(42)
for d in [2, 10, 100, 1000]:
points = rng.random((500, d))
diff = points - points[0]
dist = np.linalg.norm(diff, axis=1)[1:]
ratio = dist.max() / dist.min()
print(f"{d:5} dims: {ratio:.2f}")
2 dims: 46.78
10 dims: 3.20
100 dims: 1.41
1000 dims: 1.10
In 2 dimensions the farthest point is 46.78 times farther than the nearest. In 1,000 dimensions, only 1.10 times. Near and far are almost the same. That's the curse of dimensionality: when everything is about equally far away, "near" stops meaning anything, and every extra column of noise pushes you that way.
Our rain data: 21 columns become 115
Split first, as always:
df = pd.read_csv("weatherAUS.csv")
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = df["RainTomorrow"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape)
(113754, 21)
num_cols = X.select_dtypes("number").columns
cat_cols = X.select_dtypes(exclude="number").columns
print(len(num_cols), "number,", len(cat_cols), "text")
16 number, 5 text
But the model never sees 21 columns. This is the same preprocess step from Pipelines and ColumnTransformer: fill the gaps, scale the numbers, one-hot encode the text.
num_steps = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())])
cat_steps = Pipeline([
("impute", SimpleImputer(
strategy="most_frequent")),
("onehot", OneHotEncoder(
handle_unknown="ignore"))])
preprocess = ColumnTransformer([
("num", num_steps, num_cols),
("cat", cat_steps, cat_cols)])
preprocess.fit(X_train)
names = preprocess.get_feature_names_out()
print(len(names), "columns after encoding")
115 columns after encoding
115 columns. Which of them really matter?
Start by hand: correlation with the target
Turn the answer into 0 and 1 and score each number column against it with corrwith, on the train rows only. (More on correlation in Correlation and Heatmaps.)
y01 = (y_train == "Yes").astype(int)
corr = X_train[num_cols].corrwith(y01).abs()
top = corr.sort_values(ascending=False)
print(top.head(5).round(2))
Sunshine 0.45
Humidity3pm 0.45
Cloud3pm 0.38
Cloud9am 0.32
Humidity9am 0.26
dtype: float64
Sunshine and Humidity3pm lead with 0.45. Doing this by hand for all 115 columns, including the one-hot ones, would be slow. SelectKBest does it for you.
SelectKBest: score every column, keep the best k
SelectKBest gives every column a score against the answer and keeps the k highest. The scorer here is f_classif, an ANOVA F-test for classification. (Chi-squared and mutual information are other scorers; f_classif is enough for us.)
The scores must come from the train rows only, like every other fit. So the selector goes inside the pipeline, between preprocess and the model:
Build the same pipeline three times, keeping 5 columns, 20 columns and all of them:
for k in [5, 20, "all"]:
model = Pipeline([
("preprocess", preprocess),
("select", SelectKBest(f_classif, k=k)),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
print(k, round(acc, 3))
5 0.83
20 0.844
all 0.849
| Columns kept (k) | Test accuracy |
|---|---|
| 5 | 0.83 |
| 20 | 0.844 |
| all 115 | 0.849 |
Dropping 110 of the 115 columns costs about two points. Keeping 20 costs only half a point. A much simpler model, with almost the same score.
Which five did it keep?
Ask the select step. get_support() marks the kept columns, and scores_ holds every column's score:
model.set_params(select__k=5)
model.fit(X_train, y_train)
select = model.named_steps["select"]
keep = select.get_support()
scores = select.scores_[keep]
for name, score in zip(names[keep], scores):
print(f"{name:22} {score:8.0f}")
num__Sunshine 13238
num__Humidity3pm 27137
num__Cloud3pm 10860
cat__RainToday_No 11731
cat__RainToday_Yes 11731
The columns print in their original order, not by score. Humidity3pm has the highest score, 27,137, then Sunshine. Both led the correlation too. select__k is how you reach a parameter inside a pipeline step: step name, two underscores, parameter name.
Notice RainToday_No and RainToday_Yes have the same score. They say the same thing, so one of them is spare. SelectKBest scores each column on its own, so it can't see that and keeps both.
Common mistakes
- Selecting columns on all rows before the split. The test answers then help choose the columns. Keep the selector inside the pipeline.
- Expecting SelectKBest to remove duplicates. It scores each column alone, so two copies of the same information both survive.
- Picking k without checking the score. Try a few values and compare, like 5, 20 and all here.
- Reading the printed list as a ranking.
get_support()keeps the original column order.
Quick recap
| Idea | Code | Here |
|---|---|---|
| Too many columns blur distances | farthest / nearest | 46.78 in 2 dims, 1.10 in 1,000 |
| One-hot adds columns | get_feature_names_out() | 21 become 115 |
| Rank by hand | corrwith(y01) | Sunshine, Humidity3pm 0.45 |
| Keep the top k | SelectKBest(f_classif, k=5) | Humidity3pm top score |
| Fewer columns, similar score | inside the Pipeline | 0.83, 0.844, 0.849 |
Try it yourself
Change k=5 to k=10 in the pipeline and print the test score. Compare it with the scores for 5 and 20 columns.
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
Next →Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Train-Test Split and Data Leakage: Split First, Learn After
Why the train-test split comes before everything else: an 80/20 split with stratify and random_state, a scaler that leaks test rows, and a column that secretly holds the answer. Shown on Rain in Australia.
Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
Count the blanks with isnull().sum(), see why dropna() would throw away 60% of the rows, and fill the gaps with SimpleImputer: median for numbers, most frequent for text, learned from the train rows only. Shown on Rain in Australia.
Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
Models only understand numbers. Encode T-shirt sizes with OrdinalEncoder, colours with OneHotEncoder, avoid the dummy variable trap, handle a colour the encoder never saw, tame a date with 3,436 values, and encode the answer with LabelEncoder.
Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
Put features on the same scale so each one gets a fair say. StandardScaler and MinMaxScaler fitted on the train rows, the formula checked by hand, and a wine test where KNN jumps from 0.806 to 0.972 while a decision tree stays at 0.944.