เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ฝึกโมเดล decision tree

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

Decision tree แบ่งข้อมูลออกเป็นกลุ่มตาม features โดยเริ่มจาก root node แล้วแตกกิ่งลงมาเรื่อย ๆ จนถึง leaf node

decision tree

สามารถใช้ 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(____))
แก้ไขและรันโค้ด