Concepts 🚀 Project 🧮 Labs
🧮 Labs / ML Advanced / Encoding — OneHot vs Label vs Target vs Frequency vs Embedding

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.

script.py v3.1
Python output click Run to execute
Click "Run" to execute the code on the left.
The output will appear here.
🧠 How it works

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.

✏️ Try these changes
  • 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