Tutorial 2: Feature Selection & PCA
numpy · sklearn · matplotlib · Submit as dm02t[RR].py
Submission
Name your file dm02t[RR].py where RR = last two digits of your roll number. All tasks in one file with # Task N comments. Submit by the deadline announced in class.
Background
Real datasets often have many features, most of which add noise rather than signal. Feature selection identifies which features are most informative for a classification task. PCA goes further: it constructs new axes (principal components) that record maximum variance using fewer dimensions. Both are essential preprocessing steps before any large-scale mining pipeline.
We use the Iris dataset (4 features, 3 classes, 150 samples): small enough to understand fully.
Tasks
Task 1 Load and Explore the Dataset
- Import:
numpy as np,from sklearn.datasets import load_iris,from sklearn.preprocessing import StandardScaler - Load:
data = load_iris(). Store features asXand labels asy - Print the shape of X
- Print the feature names:
data.feature_names - Print the mean and standard deviation of each feature using
np.mean(X, axis=0)andnp.std(X, axis=0)
Task 2 Standardise the Features
PCA is sensitive to feature scale. Standardise each feature to have mean 0 and standard deviation 1 before applying PCA.
- Create a
StandardScalerand fit-transform:X_scaled = scaler.fit_transform(X) - Print the mean and std of each column of
X_scaledto verify (means ≈ 0, stds ≈ 1)
Task 3 Compute the Covariance Matrix
The covariance matrix records how features vary together and is the foundation of PCA.
- Compute:
cov_matrix = np.cov(X_scaled.T) - Print the 4×4 covariance matrix
- Identify the two features with the highest covariance (look at off-diagonal values)
- Write your answer as a comment:
# Feature X and Feature Y have the highest covariance: Z
Task 4 Apply PCA: Reduce to 2 Components
- Import:
from sklearn.decomposition import PCA - Create
pca = PCA(n_components=2)and fit-transformX_scaled - Print the shape of the result
X_pca - Print
pca.explained_variance_ratio_ - Print the total variance retained (sum of explained variance ratios) as a percentage
Task 5 Information Gain: Which Feature is Most Informative?
Information Gain (mutual information) measures how much a feature reduces uncertainty about the class label.
- Import:
from sklearn.feature_selection import mutual_info_classif - Compute:
ig = mutual_info_classif(X, y, random_state=5) - Print each feature name and its score, sorted from highest to lowest
- State which feature is most informative as a comment in your code
Task 6 Extension: How Many Components Do You Need?
Apply PCA with all 4 components. Print the cumulative explained variance. At what number of components do you reach 99% variance retained? Write your answer as a comment.
np.cumsum(pca.explained_variance_ratio_) on a PCA fitted with all components.