Feature Engineering: One-Hot Encoding, StandardScaler & MinMax
Feature Engineering: One-Hot Encoding, StandardScaler & MinMax
Raw business data (text strings, timestamps, disparate numerical scales) cannot be ingested directly into mathematical estimators like Linear Regression, Logistic Regression, or Support Vector Machines. Feature Engineering & Preprocessing transforms raw columns into numerical representations while eliminating numerical scale distortion through feature scaling.
1. Encoding Categorical Variables
Algorithms require numeric matrices. Categorical strings must be converted systematically:
A. One-Hot Encoding (Nominal Categories)
Used for unordered categories (e.g., Department: ['Sales', 'HR', 'Engineering']).
- Creates binary dummy indicator columns (0 or 1).
- Dummy Variable Trap: When using linear models, set
drop='first'to remove perfect collinearity!
B. Ordinal Encoding (Ordered Categories)
Used when categories have an inherent rank (e.g., ['Junior', 'Mid', 'Senior', 'Lead'] or ['Low', 'Medium', 'High']).
2. Numerical Feature Scaling
When features have radically different scales (e.g., Age ranging from 18 to 70 vs Annual_Salary ranging from $30,000 to $300,000), distance-based algorithms (KNN, K-Means) and gradient descent algorithms (Logistic Regression, Neural Nets) will treat salary as 10,000 times more important than age!
Scaling Methods Comparison
| Scaler | Formula | Resulting Distribution | Best Used When |
|---|---|---|---|
| StandardScaler (Z-score) | $z = rac{x - mu}{sigma}$ | Mean $mu = 0$, Std $sigma = 1$ | Data is Gaussian/normal; default for ML |
| MinMaxScaler | $x_{norm} = rac{x - x_{min}}{x_{max} - x_{min}}$ | Bounded strictly between $[0, 1]$ | Neural nets, image pixels, non-Gaussian |
| RobustScaler | $x_{rob} = rac{x - Q_2}{IQR}$ | Median 0, scaled by IQR | Dataset has severe uncleaned outliers |
3. Implementing Scalers with Scikit-Learn
fit() or fit_transform() on the entire dataset or test dataset! Scalers must learn parameters ($mu, sigma, x_{min}, x_{max}$) solely from X_train. Calling fit() on test data causes Data Leakage.4. Tree-Based Algorithms Exception
Multiple Choice Questions
scaler.fit_transform() be called on X_train, but only scaler.transform() on X_test?Train-Test Split, Cross-Validation & Avoiding Data Leakage
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.