Lesson 5 of 9
Empirical Impact of Scaling on Parametric vs Tree-Based Models
Different machine learning algorithm families exhibit radically different sensitivities to feature scaling. Distance-based estimators (KNN, K-Means), regularized linear models (Ridge, Lasso, Logistic Regression), and gradient-based neural networks are critically dependent on scaling. In contrast, tree-based models (Decision Trees, Random Forests, XGBoost) are strictly scale-invariant. Proving this empirically solidifies algorithm intuition.
Empirical Benchmark: Unscaled vs Scaled Performance
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
# Create synthetic dataset with massive scale disparity:
# Feature 1: Income ($20,000 to $200,000)
# Feature 2: Age (18 to 70)
np.random.seed(42)
n = 1000
income = np.random.uniform(20000, 200000, n)
age = np.random.uniform(18, 70, n)
# Target depends equally on age and income
y = ((income > 90000) & (age > 40)).astype(int)
X_unscaled = np.column_stack([income, age])
# Split
X_tr, X_te, y_tr, y_te = train_test_split(X_unscaled, y, test_size=0.25, random_state=42)
# Standardized version
scaler = StandardScaler()
X_tr_sc = scaler.fit_transform(X_tr)
X_te_sc = scaler.transform(X_te)
# Algorithms to benchmark
models = {
'Logistic Regression (L2)': (LogisticRegression(), LogisticRegression()),
'K-Nearest Neighbors (k=5)': (KNeighborsClassifier(n_neighbors=5), KNeighborsClassifier(n_neighbors=5)),
'Random Forest (Tree)': (RandomForestClassifier(n_estimators=50, random_state=42), RandomForestClassifier(n_estimators=50, random_state=42))
}
results = []
for name, (m_unscaled, m_scaled) in models.items():
# Train and evaluate on unscaled
m_unscaled.fit(X_tr, y_tr)
acc_unscaled = accuracy_score(y_te, m_unscaled.predict(X_te))
# Train and evaluate on scaled
m_scaled.fit(X_tr_sc, y_tr)
acc_scaled = accuracy_score(y_te, m_scaled.predict(X_te_sc))
results.append({
'Model Family': name,
'Unscaled Accuracy': f"{acc_unscaled*100:.2f}%",
'Scaled Accuracy': f"{acc_scaled*100:.2f}%",
'Scaling Sensitivity': 'HIGH' if abs(acc_scaled - acc_unscaled) > 0.05 else 'INVARIANT'
})
print("=== EMPIRICAL SCALING IMPACT BENCHMARK ===")
print(pd.DataFrame(results).to_string())Pro Tip: Why Ridge/Lasso Require Scaling
Regularization adds a penalty `alpha * sum(w_i^2)` to the loss function. If Feature 1 is measured in dollars (weights are ~0.00001) and Feature 2 is age (weights are ~0.5), the L2 penalty disproportionately crushes the weight of Feature 2 while ignoring Feature 1. Scaling puts all weights on equal footing.
MlFeatureScalingImpact Visual Representation
Hands-On Challenge: Support Vector Machine Margin Distortion
Train a Support Vector Classifier (`SVC(kernel='rbf')`) on the unscaled income/age dataset. Demonstrate how unscaled features distort the RBF gamma kernel into an infinitely narrow ellipse, crippling decision boundary formation.
Quick Quiz & Key Concept Checks
Common Pitfall: Assuming Tree Models Never Need Feature Engineering
While tree models do not require scaling, they cannot easily discover diagonal boundaries or non-axis-aligned feature interactions (e.g. `feature_a / feature_b`). Creating interaction ratios explicitly still dramatically boosts tree performance.