ML Notes
Complete guide to feature scaling techniques including standardization, normalization, and when to use each method with practical sklearn implementations.
Feature scaling transforms numeric features to a common range, ensuring no single feature dominates the learning process due to its larger magnitude. It's essential for distance-based algorithms and gradient descent optimization.
Why Scaling Matters
| Without Scaling | With Scaling: |
| Feature | Age (20-80) Age: normalized to [0,1] |
| Feature | Salary ($20k-$200k) Salary: normalized to [0,1] |
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_wine
# Demonstrate impact of scaling on KNN
wine = load_wine()
X, y = wine.data, wine.target
# Without scaling
knn = KNeighborsClassifier(n_neighbors=5)
scores_raw = cross_val_score(knn, X, y, cv=5)
# With scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
scores_scaled = cross_val_score(knn, X_scaled, y, cv=5)
print("KNN Performance:")
print(f" Without scaling: {scores_raw.mean():.4f}")
print(f" With scaling: {scores_scaled.mean():.4f}")
print(f" Improvement: {(scores_scaled.mean()-scores_raw.mean())*100:.1f}%")
print("\nScaling is CRITICAL for distance-based algorithms!")Standardization (Z-Score Normalization)
Transforms features to have mean=0 and standard deviation=1.
Formula: z = (x - μ) / σ
Min-Max Normalization
Scales features to a fixed range, typically [0, 1].
Formula: x_scaled = (x - x_min) / (x_max - x_min)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
X_minmax = scaler.fit_transform(X)
print("Min-Max Normalized:")
print(f" Min values: {X_minmax.min(axis=0)}")
print(f" Max values: {X_minmax.max(axis=0)}")
print(f"\nScaled data:\n{X_minmax.round(3)}")Robust Scaling
Uses median and IQR instead of mean and std — resistant to outliers.
When to Use Each Scaler
| Scaler | Best For | Algorithm Examples |
|---|---|---|
| StandardScaler | Most cases, Gaussian-like data | SVM, Logistic Regression, PCA |
| MinMaxScaler | Neural networks, bounded features | Neural Networks, KNN |
| RobustScaler | Data with outliers | Any algorithm with outliers |
| MaxAbsScaler | Sparse data | Text classification (TF-IDF) |
| None needed | Tree-based models | Random Forest, XGBoost, Decision Trees |
Algorithms That Need Scaling
Correct Pipeline Implementation
Interview Questions
- Why do tree-based models not need feature scaling?
Trees make decisions based on feature thresholds (splits), not distances or magnitudes. The split point adjusts to whatever scale the feature has, making scaling irrelevant.
- What happens if you use MinMaxScaler and test data has values outside training range?
Values will fall outside [0,1]. For example, if training max is 100 and test has 120, it maps to 1.2. This can cause issues with models expecting bounded inputs.
- Should you scale the target variable in regression?
Generally no, but it can help when the target has very large values and you're using neural networks or regularized models. Always inverse-transform predictions for interpretation.
- What is the difference between normalization and standardization?
Normalization (MinMax) scales to [0,1] range. Standardization (Z-score) centers to mean=0, std=1. Standardization doesn't bound values; normalization does.
- How do you handle scaling with mixed feature types?
Use ColumnTransformer to apply different scalers to different column groups. Scale numeric features, one-hot encode categoricals, and leave binary features as-is.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Feature Scaling.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Machine Learning topic.
Search Terms
machine-learning, machine learning, machine, learning, data, preprocessing, feature, scaling
Related Machine Learning Topics