Decision Tree Classifier เป็นอัลกอริทึม Classification ที่เข้าใจง่าย ใช้โครงสร้าง Tree แบ่งข้อมูลตาม Feature Values จนแต่ละ Leaf มี Class เดียว
จุดแข็ง: Interpret ได้ (White Box), รองรับ Numerical/Categorical, ไม่ต้อง Scale Features, จัดการ Non-linear ได้ดี
จุดอ่อน: Overfitting ง่าย, Unstable (ข้อมูลเปลี่ยนเล็กน้อย Tree เปลี่ยนมาก), Biased ท่อ Class ที่มี Sample มาก
ไวยากรณ์
class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', ...)
criterion: 'gini' (Gini Impurity - Default) หรือ 'entropy' (Information Gain)
ตัวอย่างโค้ด
from sklearn import tree
from sklearn.model_selection import train_test_split
# Features: [Feature_1, Feature_2] (ตัวอย่าง: Height, Weight?)
my_data = [
[16,19], [17,32], [13,3], [14,5], [141,28],
[13,34], [186,2], [126,25], [176,28], [131,32],
[166,6], [128,32], [79,110], [12,38], [19,91],
[71,136], [116,25], [17,200], [15,25], [14,32], [13,35]
]
# Target: 'Man' หรือ 'Woman'
target_vals = [
'Man','Woman','Man','Woman','Woman','Man','Woman','Woman',
'Woman','Woman','Woman','Man','Man','Man','Woman',
'Woman','Woman','Woman','Man','Woman','Woman'
]
data_feature_names = ['Feature_1', 'Feature_2']
# แบ่ง Train/Test
X_train, X_test, y_train, y_test = train_test_split(
my_data, target_vals, test_size=0.2, random_state=1
)
# สร้างและฝึกโมเดล
clf = tree.DecisionTreeClassifier()
print("The decision tree classifier is being called")
DTclf = clf.fit(my_data, target_vals) # หมายเหตุ: ควรใช้ X_train, y_train
# ทำนาย
prediction = DTclf.predict([[135, 29]])
print("The predicted value is")
print(prediction)
ผลลัพธ์
The decision tree classifier is being called
The predicted value is ['Woman']
คำอธิบาย
นำเข้า DecisionTreeClassifier และ train_test_split
กำหนด Features (2 มิติ) และ Target Labels
แบ่งข้อมูล Train/Test 80:20
สร้าง Classifier และ Fit ด้วยข้อมูลทั้งหมด (โค้ดต้นฉบับใช้ my_data, target_vals ไม่ใช่ Train Set)
ทำนาย Class ของ [135, 29] ได้ 'Woman'
แนวทางปฏิบัติที่ดี (Best Practices)
# 1. ใช้ Train Set เท่านั้นสำหรับ Fit
clf = DecisionTreeClassifier(
max_depth=5, # จำกัดความลึก ป้องกัน Overfitting
min_samples_split=5, # Min samples เพื่อ Split
min_samples_leaf=2, # Min samples ใน Leaf
random_state=42
)
clf.fit(X_train, y_train)
# 2. ประเมินด้วย Test Set
from sklearn.metrics import accuracy_score, classification_report
y_pred = clf.predict(X_test)
print(accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
# 3. Cross-Validation
from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, X, y, cv=5)
print(f"CV Accuracy: {scores.mean():.3f} (+/- {scores.std():.3f})")
# 4. Visualize Tree
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
plt.figure(figsize=(12,8))
plot_tree(clf, feature_names=data_feature_names, class_names=['Man','Woman'], filled=True)
plt.show()
Feature Importance
print(dict(zip(data_feature_names, clf.feature_importances_)))
# {'Feature_1': 0.XX, 'Feature_2': 0.YY}