Encoding — OneHot vs Label vs Target vs Frequency vs Embedding
Categorical encoding is NOT just pd.get_dummies(). 5 strategies, each for a different situation. Pick wrong = garbage model.
The output will appear here.
5 encoding strategies — pick by cardinality + order: ONEHOT — low cardinality (<10), nominal (no order). drop='first' to avoid multicollinearity. ORDINAL — when categories HAVE a natural order (Low < Med < High). Specify the order explicitly! FREQUENCY — high cardinality (10-100). Replace category with its frequency. Good for trees. TARGET — high cardinality + predictive target. Replace category with mean target. HIGH overfit risk — use smoothing + CV. DROP — cardinality > 95% (e.g., user_id, email). Useless for ML. RULE OF THUMB: < 10 unique values → OneHot. 10-100 → Frequency or Target. > 100 with predictive power → Target (with smoothing). > 95% unique → Drop. Has natural order → Ordinal. Common mistake: using LabelEncoder on nominal data. LabelEncoder implies order (red=0 < blue=1 < green=2) which is FALSE.
-
Remove drop='first' from OneHotEncoder→ creates 3 columns instead of 2 — multicollinearity risk for linear models -
Use OrdinalEncoder WITHOUT specifying categories (default alphabetical)→ Bachelor=0, High School=1, Master=2, PhD=3 — WRONG order! -
Increase city cardinality to 200: np.random.choice([f'city_{i}' for i in range(200)], n)→ OneHot would create 200 columns — frequency/target encoding better -
Change smoothing factor from 10 to 100→ more smoothing — rare cities pulled harder toward global mean