One-hot encoding biến mỗi category nominal thành vector binary — chỉ một bit bật tại vị trí tương ứng, mọi bit khác bằng 0. Đây là cách chuẩn encode categorical feature không có thứ tự cho linear model, SVM và neural network. Kungfutech Chương 4 phần One-hot encoding triển khai qua OneHotEncoder.
Mục tiêu
- Hiểu cơ chế one-hot và ma trận dummy variables.
- Dùng OneHotEncoder với
handle_unknown,drop, sparse output. - Tích hợp one-hot vào ColumnTransformer cùng numeric pipeline.
Lý thuyết
Dummy variable encoding
Feature color với 3 categories {Red, Green, Blue}:
| color | color_Red | color_Green | color_Blue |
|---|---|---|---|
| Red | 1 | 0 | 0 |
| Green | 0 | 1 | 0 |
| Blue | 0 | 0 | 1 |
Mỗi hàng đúng một cột bằng 1 — one-hot. Không có quan hệ thứ tự giữa Red(1,0,0) và Green(0,1,0) như giữa số 0 và 1 theo trục thứ tự.
Dummy trap và tham số drop
Với $K$ categories, ma trận one-hot đầy đủ có rank deficiency nếu thêm intercept trong linear regression — multicollinearity (dummy variable trap).
Giải pháp: bỏ một category làm baseline:
OneHotEncoder(drop="first") # K categories → K-1 cột
Category bị drop (theo thứ tự categories_) được encode implicit khi mọi cột = 0.
drop |
Hành vi |
|---|---|
None |
K cột (OK cho tree, RF) |
"first" |
K−1 cột, baseline = category đầu |
"if_binary" |
Chỉ drop khi đúng 2 categories |
Kungfutech thường dùng full one-hot cho classification pipeline với LogisticRegression không intercept issue khi dùng regularization — vẫn nên biết drop.
OneHotEncoder tham số quan trọng
sparse_output=True(mặc định): ma trận sparse tiết kiệm RAM khi cardinality cao.handle_unknown='infrequent_if_exist'hoặc'ignore': category test chưa thấy → vector toàn 0.min_frequency: gom category hiếm (sklearn ≥1.1).categories='auto': học unique từ train — fit trên train only.
Cardinality cao
Feature zipcode 10,000 giá trị → 10,000 cột. Giải pháp:
- Gom tail thành
"Other"trước encode - Feature hashing (
FeatureHasher) - Embedding (deep learning)
Kungfutech tập trung cardinality thấp-trung bình — Wine, Iris mở rộng.
One-hot + Linear model
Sau one-hot, feature space tăng chiều. Cùng StandardScaler trên numeric — không scale cột one-hot (đã 0/1). ColumnTransformer xử lý riêng từng nhánh.
So sánh với Label / Ordinal encoding
| Encoding | Output dim | Nominal X | Ordinal X |
|---|---|---|---|
| Label | 1 | ❌ | ⚠️ |
| Ordinal | 1 | ❌ | ✅ |
| One-hot | K (hoặc K−1) | ✅ | ⚠️ mất thứ tự |
Tree model có thể split trên label-encoded nominal nhưng interpretation kém — one-hot hoặc native categorical (HistGradientBoosting) an toàn hơn.
Code Python
One-hot encoding nominal feature kết hợp numeric Wine trong ColumnTransformer:
import numpy as np
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
wine = load_wine()
df = pd.DataFrame(wine.data, columns=wine.feature_names)
df["target"] = wine.target
rng = np.random.default_rng(42)
df["region"] = rng.choice(
["Bordeaux", "Tuscany", "Rioja", "Napa", "Burgundy"], size=len(df)
)
df["vineyard_type"] = rng.choice(["Organic", "Conventional"], size=len(df))
numeric_features = wine.feature_names
nominal_features = ["region", "vineyard_type"]
X = df[numeric_features + nominal_features]
y = df["target"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
preprocessor = ColumnTransformer(
transformers=[
("num", StandardScaler(), numeric_features),
("cat", OneHotEncoder(drop="first", sparse_output=False, handle_unknown="ignore"),
nominal_features),
]
)
pipe = Pipeline([
("prep", preprocessor),
("clf", LogisticRegression(max_iter=2000, random_state=42)),
])
pipe.fit(X_train, y_train)
acc = accuracy_score(y_test, pipe.predict(X_test))
print(f"Accuracy (one-hot + numeric): {acc:.3f}")
# Inspect one-hot columns
ohe = pipe.named_steps["prep"].named_transformers_["cat"]
feature_names = ohe.get_feature_names_out(nominal_features)
print(f"\nOne-hot columns ({len(feature_names)}):", list(feature_names))
# Shape transform
X_train_transformed = pipe.named_steps["prep"].transform(X_train)
print(f"X_train shape: {X_train.shape} → transformed: {X_train_transformed.shape}")
# Demo unknown category ở test
X_test_unknown = X_test.copy()
X_test_unknown.loc[X_test_unknown.index[0], "region"] = "UnknownRegion"
pred = pipe.predict(X_test_unknown)
print(f"\nPredict với unknown region — không crash (handle_unknown='ignore').")
drop="first" giảm 5 region → 4 cột + 2 vineyard → 1 cột = 5 cột categorical thay vì 7.
Lỗi thường gặp
- One-hot fit trên train+test: Categories test lọt vào
categories_— leakage; fit ColumnTransformer chỉ trên train. - Scale cột one-hot: StandardScaler làm hỏng giá trị 0/1 — tách nhánh trong ColumnTransformer.
- Quên sparse vs dense: Pipeline step sau cần
sparse_output=Falsenếu estimator không hỗ trợ sparse (một số cũ). - Dummy trap với LinearRegression không regularization: Dùng
drop='first'hoặc bỏ intercept.
Bài tập
- Cardinality: Thêm cột
region20 giá trị unique vào Iris (178 mẫu). Đo số cột sau one-hot với/khôngdrop='first'. Overfit có tăng không (so CV accuracy)? - Unknown: Fit với
handle_unknown='error', đưa category mới vào test — bắt exception. Đổi sang'ignore'và giải thích vector encode. - Đọc docs:
OneHotEncoder— tham sốmin_frequencygiải quyết vấn đề gì?
Tóm tắt
One hot encoding biến nominal categorical thành vector binary — không gán thứ tự giả. Dùng OneHotEncoder trong ColumnTransformer cùng numeric scaling; cân nhắc drop='first' tránh dummy trap và handle_unknown cho production. Phù hợp linear model, SVM, NN; cardinality cao cần kỹ thuật bổ sung.
Tiếp tục tại khóa Machine Learning cơ bản — bài tiếp theo: Train/Test Split.