Feature Engineering
🎯 Learning Objectives
- Apply normalization and standardization to features
- Encode categorical variables using one-hot and label encoding
- Select features using filter, wrapper, and embedded methods
- Handle missing data appropriately
- Understand the curse of dimensionality
1. Feature Scaling
Many ML algorithms (KNN, SVM, gradient-based methods, PCA) are sensitive to the scale of input features. Features with large ranges dominate those with small ranges.
Scales features to a fixed range, typically [0, 1]:
x′ = (x − x_min) / (x_max − x_min)
- Output range: [0, 1] (or any specified [a, b])
- Sensitive to outliers (outliers compress the rest of the data)
- Preserves the original distribution shape
Transforms features to have zero mean and unit variance:
z = (x − μ) / σ
- Output: mean = 0, std = 1, range is unbounded
- Less sensitive to outliers than min-max
- Preferred for algorithms assuming Gaussian input (e.g., SVM with RBF kernel, PCA)
Q: Feature values: [10, 20, 30, 40, 50]. Apply (a) min-max normalization, (b) z-score standardization.
A (a): min=10, max=50. x′ = (x−10)/40. Result: [0, 0.25, 0.5, 0.75, 1.0]
A (b): μ=30, σ=√200 = 10√2 ≈ 14.14. z = (x−30)/14.14. Result: [−1.414, −0.707, 0, 0.707, 1.414]
| Property | Min-Max | Standardization |
|---|---|---|
| Output range | [0, 1] | Unbounded |
| Outlier sensitivity | High | Moderate |
| Preserves zeros | No | Only if μ=0 |
| Best for | Neural nets, image pixels | SVM, PCA, logistic regression |
| Distribution | Preserves shape | Centers at 0 |
Always compute scaling parameters (μ, σ, min, max) on the training set only, then apply the same transformation to the validation and test sets. Otherwise, you leak information from test data.
2. Categorical Encoding
ML algorithms work with numbers. Categorical features must be converted to numerical form.
Assigns each category a unique integer: Red→0, Green→1, Blue→2.
- Problem: Implies ordinal relationship (Green > Red). Only suitable for truly ordinal features like “Low, Medium, High”.
Creates a binary column for each category. K categories → K binary columns (or K−1 with dummy variable trap avoidance).
Color {Red, Green, Blue} becomes: Red=[1,0,0], Green=[0,1,0], Blue=[0,0,1]
- No ordinal assumption
- Increases dimensionality (problematic for high-cardinality features)
When using one-hot encoding with linear models, drop one column (K−1 encoding) to avoid perfect multicollinearity. The dropped category becomes the “reference” category.
3. Feature Selection Methods
| Method | Approach | Examples | Pros | Cons |
|---|---|---|---|---|
| Filter | Evaluate features independently using statistical tests | Correlation, Chi-squared, Mutual Information, Variance Threshold | Fast, model-agnostic | Ignores feature interactions |
| Wrapper | Use a model to evaluate subsets of features | Forward Selection, Backward Elimination, Recursive Feature Elimination (RFE) | Considers interactions | Computationally expensive |
| Embedded | Feature selection built into the learning algorithm | Lasso (L1), Decision Tree feature importances, Ridge coefficients | Efficient, interaction-aware | Model-specific |
3.1 Filter Methods
Remove features that have high correlation with each other (redundant) or low correlation with the target (irrelevant).
Pearson correlation: r = Cov(X,Y) / (σ_X × σ_Y). Range: [−1, 1].
3.2 Wrapper Methods
1. Start with no features selected 2. For each remaining feature: a. Add it to the current set b. Evaluate model performance (e.g., with CV) 3. Keep the feature that gives the best improvement 4. Repeat until no improvement or desired number of features
4. Handling Missing Data
| Strategy | When to Use | Impact |
|---|---|---|
| Drop rows | Few missing values, large dataset | Loses data; can introduce bias if missing not at random |
| Drop columns | Feature has >50% missing | Loses entire feature |
| Mean/Median imputation | Numerical features, MCAR | Simple but reduces variance |
| Mode imputation | Categorical features | Simple; can distort distribution |
| KNN imputation | Moderate missing, features correlated | Better quality; computationally expensive |
| Indicator variable | Missingness itself is informative | Adds binary “is_missing” feature |
- MCAR (Missing Completely At Random): Missingness unrelated to any variable
- MAR (Missing At Random): Missingness related to observed data but not the missing value itself
- MNAR (Missing Not At Random): Missingness related to the missing value (most problematic)
5. Curse of Dimensionality
As the number of features (dimensions) increases, the volume of the feature space grows exponentially, causing data to become increasingly sparse. This has profound effects on ML algorithms:
- Distance metrics become meaningless: In high-D space, the ratio of nearest to farthest neighbour distances approaches 1
- More data needed: To maintain the same density, sample size must grow exponentially with dimensions
- Overfitting risk increases: More features → more parameters → easier to memorize training data
Q: To keep 10 samples per “cell” with 10 bins per feature: 1D needs 10×10=100 samples, 2D needs 10×100=1000. How many for 5D?
A: 10 × 10⁵ = 10 × 100000 = 1,000,000 samples. Exponential growth!
- Feature selection (reduce irrelevant features)
- Dimensionality reduction (PCA, t-SNE)
- Regularization (L1/L2)
- Domain knowledge to select meaningful features
6. Feature Importance
After training a model, understanding which features contribute most to predictions is valuable for interpretation and feature selection.
- Tree-based: Total reduction in impurity (Gini/Entropy) across all splits using that feature
- Permutation importance: Shuffle one feature, measure drop in performance
- Coefficient magnitude: |wᵢ| for linear models (after standardization)
- L1 regularization: Features with zero coefficients are unimportant