"Coming up with features is difficult, time-consuming, and requires expert knowledge. Applied machine learning is basically feature engineering." — Prof. Andrew Ng. In this class, we master Categorical Encodings, Feature Scaling, and ColumnTransformers.
| Encoding Method | Best For | Dimensionality Impact | Key Pitfall |
|---|---|---|---|
| One-Hot Encoding (OHE) | Nominal categories with low cardinality (< 15 unique values). | Expands to \(k\) or \(k-1\) binary columns. | Causes sparse matrix explosion on high cardinality columns. |
| Ordinal Encoding | Categories with inherent ranked order (e.g., Low, Medium, High). | Maintains 1 single numeric column. | Imposing arbitrary numeric orders on unordered nominal data. |
| Target / WoE Encoding | High cardinality categories (e.g., 500 city names, 1,000 product SKUs). | Maintains 1 single numeric column. | Extreme risk of target leakage without m-estimate smoothing. |
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
# Sample feature dataset
df = pd.DataFrame({
'age': [25, 45, 35, 52, 23, 40, 60, 48],
'income': [50000, 110000, 75000, 130000, 42000, 85000, 160000, 95000],
'education': ['Bachelors', 'PhD', 'Masters', 'Masters', 'HighSchool', 'Bachelors', 'PhD', 'Masters'],
'country': ['US', 'UK', 'CA', 'US', 'US', 'UK', 'CA', 'US'],
'purchased': [0, 1, 1, 1, 0, 0, 1, 1]
})
X = df.drop(columns=['purchased'])
y = df['purchased']
# Define feature subsets
numeric_cols = ['age', 'income']
categorical_cols = ['education', 'country']
# Build ColumnTransformer (Zero Data Leakage Pipeline)
preprocessor = ColumnTransformer(transformers=[
('num', StandardScaler(), numeric_cols),
('cat', OneHotEncoder(drop='first', sparse_output=False), categorical_cols)
])
# Full scikit-learn pipeline
clf_pipeline = Pipeline(steps=[
('preprocessor', preprocessor),
('classifier', LogisticRegression())
])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
clf_pipeline.fit(X_train, y_train)
print(f"Test Accuracy: {clf_pipeline.score(X_test, y_test) * 100:.1f}%")
By wrapping feature preprocessing and estimator fitting inside a Scikit-Learn Pipeline, cross-validation automatically re-fits the scalers and encoders only on the training folds, preventing statistical contamination of validation sets.
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Clean and sanitize raw attributes prior to feature transformations.
Dimensionality reduction using Principal Component Analysis.
Assemble ColumnTransformers inside scikit-learn Pipeline objects.
Engineer interaction terms and behavioural aggregations for churn prediction.