Majority vote. Mục tiêu: thực hành được trên sklearn hiện đại, có thể chạy trong môi trường Python 3.10+.
Mục tiêu
- Nắm khái niệm cốt lõi trong mục sách tương ứng.
- Chạy được ví dụ code minh họa và biến thể tham số.
- Liên hệ với bài trước/sau trong cùng chương theo MANIFEST.
Lý thuyết
Tóm tắt lý thuyết
Nội dung chi tiết bám sát mục Kungfutech đã ghi trong bookRef. Khi triển khai production, luôn bọc tiền xử lý + model trong Pipeline và dùng cross-validation để ước lượng hiệu năng.
Tham chiếu chính thức
Ưu tiên đọc scikit-learn User Guide cho API cụ thể; mỗi estimator có trang doc riêng liên kết từ hướng dẫn.
Code Python
from sklearn.datasets import make_classification
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(n_samples=500, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
vc = VotingClassifier(
estimators=[
("lr", LogisticRegression(max_iter=1000)),
("svc", SVC(probability=False)),
("dt", DecisionTreeClassifier(max_depth=4, random_state=42)),
],
voting="hard",
)
vc.fit(X_train, y_train)
print("Train acc:", round(vc.score(X_train, y_train), 3), "Test acc:", round(vc.score(X_test, y_test), 3))
Lỗi thường gặp
- Data leakage: fit vectorizer/scaler trên toàn bộ dữ liệu trước khi split.
- Random state không cố định: kết quả khó reproduce.
Bài tập
- Chạy lại ví dụ với
random_statekhác và so sánh metric. - Thêm một bước trong
Pipeline(ví dụ scaling nếu phù hợp) và đo lại.
Tóm tắt
Majority Vote — hoàn thành mục Kungfutech — Ch.7 — Majority vote trong lộ trình batch 3.
Tiếp tục lộ trình tại khóa Machine Learning cơ bản — bài tiếp theo: Cài đặt Majority Vote và VotingClassifier sklearn.