Encoding Categories and Scaling Numbers
Converting categorical variables into numbers and putting numeric features on comparable scales, and knowing which models care.
Intermediate · about 5 hours · difficulty 2/5
Learn first: Feature Engineering
Models need numeric input, and many are sensitive to feature scale. The right encoding and scaling depends on the model family.
Categorical encoding
- One-hot encoding: the safe default for low-cardinality categories; set
handle_unknown='ignore'for unseen values at inference. - Ordinal encoding: for truly ordered categories (small, medium, large) and often fine for tree models.
- Target (mean) encoding: powerful for high-cardinality columns like ZIP codes but leaks unless computed out-of-fold.
- Hashing and embeddings: for very high cardinality or deep learning models.
Scaling
- StandardScaler (zero mean, unit variance): default for linear models, SVMs, kNN, neural networks.
- MinMaxScaler: bounded ranges, common for images and some neural nets.
- RobustScaler: uses medians and IQR, better with outliers.
- Tree-based models do not need scaling; splits are invariant to monotonic transforms.
Rule
Fit encoders and scalers on the training fold only. Use ColumnTransformer to apply different preprocessing to numeric and categorical columns in one object.
Good enough to move on when you can explain which preprocessing a kNN model, a logistic regression and a random forest each require, and implement it without leakage.
Key concepts
- One-hot encoding
- Ordinal encoding
- Target encoding: Compute out-of-fold
- Standard, min-max and robust scaling
- ColumnTransformer
- Feature hashing
Mini project
Compare one-hot, ordinal and target encoding for the high-cardinality columns of the UCI Adult dataset using logistic regression and a gradient boosted model, reporting cross-validated scores for each.
Check yourself
Why does kNN performance change drastically when you forget to scale features, while a decision tree does not change at all?
Free resources
- scikit-learn: Preprocessing data (scikit-learn)
- Kaggle Learn: Intermediate Machine Learning (Kaggle)