ฝึกโมเดล decision tree
Random forest เป็นโมเดลยอดนิยมสำหรับการพยากรณ์ ใช้งานได้ดีโดยไม่ต้องปรับแต่งมาก แต่ก่อนอื่นมาทำความเข้าใจกับ building block ของ random forest ซึ่งก็คือ decision tree กันก่อน
Decision tree แบ่งข้อมูลออกเป็นกลุ่มตาม features โดยเริ่มจาก root node แล้วแตกกิ่งลงมาเรื่อย ๆ จนถึง leaf node

สามารถใช้ sklearn ในการฝึก decision tree ได้ด้วย DecisionTreeRegressor และ .fit(features, targets)
หากไม่จำกัดความลึก (depth) ของ tree โมเดลจะแตกกิ่งต่อไปเรื่อย ๆ จนแต่ละ leaf มีข้อมูลเพียง 1 ตัวอย่าง ซึ่งเป็นตัวอย่างที่ชัดเจนมากของ overfitting เราจะศึกษาเรื่อง overfitting เพิ่มเติมในบทถัดไป
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับการเงินด้วย Python
คำแนะนำการฝึกหัด
- ใช้ class
DecisionTreeRegressorที่ import มาแล้ว โดยไม่ระบุอาร์กิวเมนต์ใด ๆ เพื่อสร้างโมเดล decision tree ชื่อdecision_tree - ฝึกโมเดลโดยใช้
train_featuresและtrain_targetsที่เตรียมไว้ก่อนหน้านี้ (ซึ่งตอนนี้มี features ของวันในสัปดาห์และปริมาณการซื้อขาย) - แสดงค่า score บน training features และ targets รวมถึง
test_featuresและtest_targets
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
from sklearn.tree import DecisionTreeRegressor
# Create a decision tree regression model with default arguments
decision_tree = ____
# Fit the model to the training features and targets
decision_tree.fit(____)
# Check the score on train and test
print(decision_tree.score(train_features, train_targets))
print(decision_tree.score(____))