Sau lý thuyết information gain, bài này xây decision tree Python với sklearn.tree.DecisionTreeClassifier — train, visualize, và kiểm soát overfitting qua max_depth, min_samples_leaf. Kungfutech Chương 3 dùng Iris và plot_tree để bạn "nhìn thấy" model học gì.
Mục tiêu
- Train
DecisionTreeClassifierend-to-end trên Iris. - Visualize cây bằng
plot_treevàexport_text. - Tune hyperparameter chống overfitting.
Lý thuyết
DecisionTreeClassifier API
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(
criterion='gini', # hoặc 'entropy'
max_depth=None, # None = grow until pure/leaves min
min_samples_split=2,
min_samples_leaf=1,
random_state=42
)
tree.fit(X_train, y_train)
Không cần StandardScaler — tree so sánh threshold trên giá trị gốc.
Hyperparameters chống overfitting
| Parameter | Effect |
|---|---|
max_depth |
Giới hạn độ sâu — giảm complexity mạnh nhất |
min_samples_split |
Node cần ít nhất N mẫu mới được split |
min_samples_leaf |
Mỗi leaf ít nhất N mẫu |
max_leaf_nodes |
Giới hạn số lá |
ccp_alpha |
Cost-complexity pruning (post-pruning) |
Kungfutech so sánh max_depth=3 vs unlimited — depth 3 thường generalize tốt hơn trên Iris.
Feature importance
Sau fit, tree.feature_importances_ cho biết feature đóng góp bao nhiêu vào giảm impurity (weighted by samples). Petal features thường dominate trên Iris.
Visualization tools
sklearn.tree.plot_tree— matplotlib graphexport_graphviz+ Graphviz — đẹp hơn cho reportexport_text— ASCII tree cho terminal
Docs: DecisionTreeClassifier
Code Python
Workflow Kungfutech Chương 3 đầy đủ:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.tree import DecisionTreeClassifier, plot_tree, export_text
from sklearn.metrics import accuracy_score, classification_report
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
class_names = iris.target_names
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
# Unrestricted tree — dễ overfit
tree_full = DecisionTreeClassifier(random_state=42)
tree_full.fit(X_train, y_train)
# Pruned tree — Kungfutech recommends max_depth=3
tree_pruned = DecisionTreeClassifier(max_depth=3, random_state=42)
tree_pruned.fit(X_train, y_train)
for name, model in [('Full', tree_full), ('Pruned (depth=3)', tree_pruned)]:
tr = model.score(X_train, y_train)
te = model.score(X_test, y_test)
print(f"{name}: train={tr:.3f} test={te:.3f}")
print("\nFeature importances (pruned):")
for fname, imp in zip(feature_names, tree_pruned.feature_importances_):
print(f" {fname}: {imp:.3f}")
# Visualize
fig, axes = plt.subplots(1, 2, figsize=(20, 8))
for ax, model, title in zip(axes, [tree_full, tree_pruned],
['Full tree', 'max_depth=3']):
plot_tree(model, feature_names=feature_names,
class_names=class_names, filled=True, ax=ax, fontsize=8)
ax.set_title(title)
plt.tight_layout()
plt.show()
# Text export
print(export_text(tree_pruned, feature_names=feature_names))
# Cross-validation tune max_depth
depths = range(1, 11)
cv_scores = []
for d in depths:
clf = DecisionTreeClassifier(max_depth=d, random_state=42)
scores = cross_val_score(clf, X, y, cv=5)
cv_scores.append(scores.mean())
plt.figure(figsize=(6, 3))
plt.plot(depths, cv_scores, 'o-')
plt.xlabel('max_depth')
plt.ylabel('5-fold CV accuracy')
plt.title('Depth tuning — Iris')
plt.show()
print(f"Best depth: {depths[np.argmax(cv_scores)]}")
Decision boundary (2 features)
X_2d = X[:, [2, 3]] # petal only
tree_2d = DecisionTreeClassifier(max_depth=3, random_state=42)
tree_2d.fit(X_2d, y)
# Reuse plot_decision_regions từ bài Perceptron
from sklearn.datasets import load_iris
# ... (train/test split on X_2d, plot với meshgrid)
Lỗi thường gặp
- Train accuracy 100%, test thấp — không prune. Giảm
max_depthhoặc tăngmin_samples_leaf. - Scale feature không cần thiết nhưng vẫn làm — không sai, chỉ thừa. Tree invariant với monotonic transform từng feature.
plot_treechữ quá nhỏ. Tăngfigsize, giảmmax_depthkhi visualize.- Leakage qua feature có thứ tự thời gian. Tree không biết temporal — shuffle train/test đúng cách.
- So sánh tree depth trên train accuracy. Dùng CV như code trên.
Bài tập
Train tree với
criterion='entropy'vs'gini'. Test accuracy khác nhau không? Cây structure giống nhau không?Vẽ CV accuracy vs
max_depth(1–15). Chọn depth tối ưu. Train final model và inclassification_report.Export cây
max_depth=3bằngexport_graphviz(cài graphviz). Mô tả rule đầu tiên bằng tiếng Việt.
Tóm tắt
Decision tree Python với sklearn = fit không cần scale + plot_tree để interpret + tune max_depth chống overfitting. Đây là building block của Random Forest — bài tiếp theo.
Tiếp tục tại Khóa Machine Learning cơ bản trên KungfuTech.