Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Decision Tree สำหรับการถดถอย (Regressor) ใน Python

Decision Tree (ต้นไม้ตัดสินใจ) เป็นโครงสร้างพื้นฐานของอัลกอริทึม Random Forest และเป็นหนึ่งในอัลกอริทึม Machine Learning ที่ได้รับความนิยมสูง สามารถใช้ได้ทั้งงาน Classification และ Regression (ถดถอย) ซึ่งเรียกอีกชื่อว่า CART (Classification And Regression Trees)

โครงสร้าง Decision Tree สามารถมอง像เป็น Binary Tree ที่แต่ละโหนด (Node) แทนตัวแปรนำเข้า (Feature) เดียว และโหนดใบ (Leaf Nodes) จะเก็บค่าตัวแปรเป้าหมาย (Target Variable) ใช้สำหรับทำนายผลลัพธ์

หลักการสร้าง Decision Tree คือการแบ่งพื้นที่ข้อมูล (Feature Space) ออกเป็นหลายส่วน โดยลองแบ่ง (Split) ด้วยค่าต่างๆ เพื่อให้ได้ Cost ต่ำสุด และค่าทำนายที่ดีที่สุด การเลือกการแบ่งทำแบบ Greedy (เลือกที่ดีที่สุดในขณะนั้น) และทำซ้ำจนถึงความลึกสูงสุด (Max Depth) ที่กำหนด

DecisionTreeRegressor ใน scikit-learn ใช้เกณฑ์ (Criterion) เริ่มต้นเป็น 'mse' (Mean Squared Error) สำหรับงาน Regression

ไวยากรณ์

class sklearn.tree.DecisionTreeRegressor(*, criterion='mse', ...)

ตัวอย่างโค้ด

from sklearn import tree

my_data = [[1, 1], [5, 5], [2, 3], [7, 11]]
target_vals = [0.1, 1.5, 0.75, 1.73]

clf = tree.DecisionTreeRegressor()
print("The decision tree regressor has been called")

DTreg = clf.fit(my_data, target_vals)
print("Data has been fit")

pred_val = DTreg.predict([[4, 7]])
print("The predicted data is ")
print(pred_val)

ผลลัพธ์

The decision tree regressor has been called
Data has been fit
The predicted data is [1.5]

คำอธิบาย

  • นำเข้าโมดูล tree จาก scikit-learn

  • กำหนด Feature Vector (my_data) และ Target Values (target_vals)

  • สร้างอ็อบเจกต์ DecisionTreeRegressor และฝึกโมเดลด้วย fit()

  • ใช้ฟังก์ชัน predict() ทำนายค่าสำหรับข้อมูลใหม่ [4, 7]

  • แสดงผลลัพธ์การทำนายบนคอนโซล

ข้อควรพิจารณา: Decision Tree Regressor อาจเกิด Overfitting ได้ง่ายหากไม่จำกัดความลึกของต้นไม้ (max_depth) หรือจำนวนตัวอย่างขั้นต่ำในโหนดใบ (min_samples_leaf) ควรใช้ Cross-Validation เพื่อปรับ Hyperparameters ให้เหมาะสม