Feature selection
- Machine Learning course
- Beginner
- Lesson 82/112
- 5 min
Feature selection simplifies the model by choosing the most informative features.
Why select features?
Not every feature is useful. Unnecessary features slow the model down, push it to learn noise and make interpretation harder. A model built with fewer but good features often generalises better.
from sklearn.feature_selection import VarianceThreshold
X = np.array([[1, 0, 3], [2, 0, 1], [3, 0, 2]])
print(VarianceThreshold(0.0).fit_transform(X)) # constant 2nd column droppedThe simplest selection is dropping columns that never change (variance 0).
Filtering by correlation
Features with no relationship to the target and features that are near-copies of each other are candidates for removal:
r = [abs(np.corrcoef(X[:, j], y)[0, 1]) for j in range(X.shape[1])]
print(np.round(r, 2)) # strength of relation to target
print(np.corrcoef(X, rowvar=False).round(2)) # between featuresCorrelation measures only linear relationships; at a later level you'll see model-based selection methods.
Practice Relation to the target
Compute the absolute correlation of each column with y as a list and print it with np.round(..., 2). Then print the index of the most strongly related column.
Starter code
import numpy as np
X = np.array([[1, 5, 2], [2, 3, 2], [3, 6, 2.1], [4, 2, 1.9], [5, 4, 2]])
y = np.array([2, 4, 6, 8, 10])
# buraya yazSample solution
import numpy as np
X = np.array([[1, 5, 2], [2, 3, 2], [3, 6, 2.1], [4, 2, 1.9], [5, 4, 2]])
y = np.array([2, 4, 6, 8, 10])
r = [abs(np.corrcoef(X[:, j], y)[0, 1]) for j in range(X.shape[1])]
print(np.round(r, 2))
print(int(np.argmax(r)))Expected output
[1. 0.3 0.22] 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the most likely harm of unnecessary features?
- Better generalisation
- Faster training
- There is no harm
- The model learning noise and overfitting Correct answer
Explanation: As the number of features grows, so does the chance of finding coincidental patterns.
2 Drop columns with variance below 0.1.
sec = VarianceThreshold(____=0.1)
sec = VarianceThreshold(threshold=0.1)
Explanation: Features with variance below threshold are dropped.
3 Match the situations.
| Term | Meaning |
|---|---|
Constant column |
Drop with variance threshold |
Unrelated to the target |
Filter by correlation |
Two duplicate columns |
Drop one |
A few good features |
Better generalisation |