When working with categorical variables, the main goal is to improve model accuracy and reliability. Metrics like accuracy, precision, and recall matter because they show how well the model understands categories after encoding. Poor handling of categories can cause wrong predictions, so these metrics help check if the encoding method helps the model learn correctly.
Handling categorical variables in ML Python - Model Metrics & Evaluation
Suppose we have a model classifying fruits based on encoded color categories. Here is a confusion matrix from predictions:
| | Predicted Apple | Predicted Orange | Predicted Banana |
|-----------------|-----------------|------------------|------------------|
| Actual Apple | 50 (TP) | 5 (FP) | 0 |
| Actual Orange | 3 (FN) | 45 (TP) | 2 (FP) |
| Actual Banana | 0 | 4 (FN) | 46 (TP) |
Totals: TP=141, FP=14, FN=14. This shows how well the model predicts categories after encoding.
Imagine a model classifying customer types (e.g., 'new', 'returning', 'VIP').
- High precision means when the model says a customer is VIP, it is usually correct. This avoids wrongly giving VIP perks.
- High recall means the model finds most VIP customers, even if some non-VIPs are included. This avoids missing real VIPs.
Choosing encoding methods affects this tradeoff. For example, one-hot encoding might help precision but hurt recall if categories are many and sparse.
Good: Accuracy above 85%, precision and recall balanced above 80% for each category. This means the model understands categories well.
Bad: Accuracy below 70%, or very low precision/recall for some categories (e.g., 40%). This suggests poor encoding or ignored categories causing confusion.
- Ignoring rare categories: Leads to poor recall on those classes.
- Data leakage: Using target information in encoding (like target mean encoding without care) inflates accuracy falsely.
- High cardinality: Too many categories can cause overfitting or sparse data, hurting generalization.
- Accuracy paradox: High accuracy but poor precision/recall on minority categories due to imbalance.
Your model has 98% accuracy but only 12% recall on a rare category after encoding categorical variables. Is it good for production? Why or why not?
Answer: No, it is not good. The low recall means the model misses most instances of that rare category, which could be critical depending on the use case. High accuracy is misleading because the rare category is small compared to others.
Practice
Solution
Step 1: Understand machine learning input requirements
Most machine learning models work with numerical data and cannot process text or categories directly.Step 2: Reason why conversion is necessary
Converting categories to numbers allows models to perform calculations and learn patterns from the data.Final Answer:
Because most machine learning algorithms only understand numbers, not words. -> Option AQuick Check:
Machine learning needs numbers = D [OK]
- Thinking categorical variables are continuous data
- Believing conversion is just for memory saving
- Assuming conversion is for aesthetics
color?Solution
Step 1: Recall pandas one-hot encoding method
Pandas providesget_dummies()to convert categorical columns into one-hot encoded columns.Step 2: Match correct syntax
The correct syntax ispd.get_dummies(df['color']). Other options are not valid pandas methods.Final Answer:
pd.get_dummies(df['color']) -> Option DQuick Check:
Use pd.get_dummies for one-hot encoding [OK]
- Using non-existent pandas methods
- Confusing label encoding with one-hot encoding
- Calling methods on dataframe incorrectly
from sklearn.preprocessing import LabelEncoder le = LabelEncoder() df['size_encoded'] = le.fit_transform(df['size']) print(df['size_encoded'].tolist())
If
df['size'] contains ['small', 'medium', 'large', 'medium'], what will be the printed output?Solution
Step 1: Understand LabelEncoder mapping
LabelEncoder assigns integers in alphabetical order: 'large'->0, 'medium'->1, 'small'->2.Step 2: Map each value in the list
Input list: ['small', 'medium', 'large', 'medium'] maps to [2, 1, 0, 1].Final Answer:
[2, 1, 0, 1] -> Option BQuick Check:
Alphabetical order encoding = A [OK]
- Assuming encoding follows input order
- Mixing up label encoding with one-hot encoding
- Forgetting zero-based indexing
ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). What is the most likely cause and fix?Solution
Step 1: Analyze the error message
The error mentions NaN (missing) or infinite values, which cause encoding to fail.Step 2: Identify fix for missing values
Fill missing values with a placeholder or drop rows before encoding to avoid errors.Final Answer:
The column has missing values; fill or drop them before encoding. -> Option AQuick Check:
Handle missing data before encoding [OK]
- Ignoring missing values in categorical columns
- Trying to encode numeric columns as categories
- Assuming dataset size causes this error
education_level having values: ['high school', 'bachelor', 'master', 'phd']. You want to use this feature in a regression model where order matters. Which encoding method should you choose and why?Solution
Step 1: Understand the nature of the feature
Education levels have a natural order: high school < bachelor < master < phd.Step 2: Choose encoding that preserves order
Label encoding assigns numbers reflecting order, suitable for regression models that consider magnitude.Final Answer:
Label encoding, because it preserves the order of categories as numbers. -> Option CQuick Check:
Ordered categories use label encoding [OK]
- Using one-hot encoding for ordered categories
- Ignoring order importance in encoding
- Trying to use strings directly in models
Ready to prove it?
Pass the test and this pattern moves unknown
