Chương 3 Kungfutech kết thúc bằng việc đặt các classifier cạnh nhau trên cùng dataset — không để chọn "thuật toán thắng" tuyệt đối, mà để bạn so sánh thuật toán phân loại theo accuracy, thời gian, interpretability và giả định mô hình. Bài lab này tổng hợp toàn bộ Ch.3 trên Iris và một dataset phi tuyến.
Mục tiêu
- Chạy comparison lab với 6+ classifiers sklearn từ Ch.3.
- Xây bảng so sánh metric, train time, và đặc tính mô hình.
- Rút ra quy tắc chọn thuật toán thực tế sau chương.
Lý thuyết
Classifiers đã học trong Ch.3
| Thuật toán | Loại | Scale? | Nonlinear? | Interpretable? |
|---|---|---|---|---|
| Perceptron | Linear | Có | Không | Trung bình |
| Logistic Regression | Linear probabilistic | Có | Không (linear) | Cao (coef) |
| SVM (linear/RBF) | Margin / kernel | Có | RBF: có | Trung bình |
| Decision Tree | Tree | Không | Có (axis) | Cao |
| Random Forest | Ensemble | Không | Có | Trung bình (importance) |
| k-NN | Instance-based | Có | Có (local) | Thấp |
Tiêu chí so sánh trong lab
- Test accuracy (hoặc F1 nếu imbalance)
- 5-fold CV mean ± std — ổn định hơn một split
- Train time — quan trọng khi retrain thường xuyên
- Hyperparameter sensitivity — SVM/RBF cần tune; RF ít hơn
- Giả định: linear data → logistic/SVM linear; noisy boundaries → RF/k-NN
Workflow comparison lab
Cùng train/test split (stratified)
→ Pipeline (Scaler nếu cần + Model)
→ fit / predict / score
→ Ghi lại bảng kết quả
→ Visualize decision boundary (2D)
Kết luận thường gặp trên Iris
Iris gần linearly separable (đặc biệt Setosa):
- Logistic, Linear SVM, RF đều ~95–100% test
- k-NN với k hợp lý tương đương
- Perceptron có thể hội tụ chậm hơn nhưng đủ trên Iris binary
Trên moons/circles (nonlinear):
- Linear models thua
- RBF SVM, RF, k-NN (k nhỏ) thắng
Bước tiếp sau Ch.3
Kungfutech Chương 4+: data preprocessing sâu hơn, model evaluation, dimensionality reduction. Ch.3 cho toolbox — Ch.4+ cho workflow production.
Code Python
Comparison lab hoàn chỉnh:
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris, make_moons
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Perceptron, LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
def run_comparison(X, y, dataset_name, test_size=0.3):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=test_size, random_state=42, stratify=y
)
models = {
'Perceptron': Pipeline([
('scaler', StandardScaler()),
('clf', Perceptron(max_iter=1000, random_state=42))
]),
'Logistic Regression': Pipeline([
('scaler', StandardScaler()),
('clf', LogisticRegression(max_iter=1000, random_state=42))
]),
'SVM (linear)': Pipeline([
('scaler', StandardScaler()),
('clf', SVC(kernel='linear', C=1.0, random_state=42))
]),
'SVM (RBF)': Pipeline([
('scaler', StandardScaler()),
('clf', SVC(kernel='rbf', gamma='scale', C=1.0, random_state=42))
]),
'Decision Tree': DecisionTreeClassifier(max_depth=5, random_state=42),
'Random Forest': RandomForestClassifier(n_estimators=100, max_depth=5,
random_state=42, n_jobs=-1),
'k-NN (k=5)': Pipeline([
('scaler', StandardScaler()),
('clf', KNeighborsClassifier(n_neighbors=5))
]),
}
rows = []
for name, model in models.items():
t0 = time.perf_counter()
model.fit(X_train, y_train)
fit_time = time.perf_counter() - t0
test_acc = model.score(X_test, y_test)
cv_mean = cross_val_score(model, X, y, cv=5).mean()
rows.append({
'Dataset': dataset_name,
'Model': name,
'Test Acc': round(test_acc, 4),
'CV Mean': round(cv_mean, 4),
'Fit Time (ms)': round(fit_time * 1000, 2)
})
return pd.DataFrame(rows)
# --- Iris (multiclass) ---
iris = load_iris()
df_iris = run_comparison(iris.data, iris.target, 'Iris (4 features)')
# --- Moons (nonlinear) ---
X_moon, y_moon = make_moons(n_samples=300, noise=0.2, random_state=42)
df_moons = run_comparison(X_moon, y_moon, 'Moons (2 features)')
results = pd.concat([df_iris, df_moons], ignore_index=True)
print(results.to_string(index=False))
# Pivot cho dễ đọc
pivot = results.pivot(index='Model', columns='Dataset', values='Test Acc')
print("\n=== Test Accuracy Pivot ===")
print(pivot)
# Bar chart — Iris
df_iris_sorted = df_iris.sort_values('Test Acc', ascending=True)
plt.figure(figsize=(8, 5))
plt.barh(df_iris_sorted['Model'], df_iris_sorted['Test Acc'], color='steelblue')
plt.xlabel('Test Accuracy')
plt.title('Classifier Comparison — Iris')
plt.xlim(0.8, 1.05)
plt.tight_layout()
plt.show()
Decision boundary gallery (2D Iris petal)
from sklearn.datasets import load_iris
X = load_iris().data[:, [2, 3]]
y = load_iris().target
# ... train models trên X, y
# Vẽ subplot 2x4 với plot_decision_regions cho mỗi model
# (reuse hàm từ bài Perceptron)
Ghi chú reproducibility
# Đặt random_state cho mọi estimator
# Cùng random_state=42 cho train_test_split
# Ghi version: sklearn.__version__
import sklearn
print("sklearn version:", sklearn.__version__)
Lỗi thường gặp
- So sánh không fair — tree không scale, SVM có scale. Dùng Pipeline thống nhất hoặc ghi chú khác biệt có chủ ý.
- Một random split duy nhất. CV mean quan trọng hơn một test acc.
- Không tune hyperparameter rồi kết luận SVM kém RF. Fair comparison = GridSearchCV cho mỗi model (tốn thời gian nhưng đúng).
- Iris quá dễ — kết luận sai cho mọi bài toán. Luôn thử dataset thứ hai (moons, wine, breast cancer).
- Chỉ nhìn accuracy với imbalance. Thêm F1 macro.
Bài tập
Chạy comparison lab trên
load_wine()(multiclass). Model nào #1 test acc? Model nào #1 CV stability (std thấp)?Thêm
GridSearchCVcho SVM RBF và k-NN vào lab. Bảng accuracy thay đổi thế nào?Viết decision guide 1 trang: "Nếu dữ liệu ..., chọn ..., vì ..." — ít nhất 5 scenario thực tế (fraud, image tabular features, medical, v.v.).
Tóm tắt
So sánh thuật toán phân loại là kỹ năng kết thúc Ch.3: cùng data, cùng metric, cùng protocol — rồi chọn theo accuracy và constraints (speed, explainability, data size). Không có champion vĩnh viễn; có tool phù hợp ngữ cảnh.
Bạn đã hoàn thành tour Kungfutech Chương 3 — từ Perceptron đến k-NN. Tiếp tục hành trình tại Khóa Machine Learning cơ bản trên KungfuTech — chương tiếp theo về tiền xử lý dữ liệu và đánh giá mô hình sâu hơn.