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

สร้างโมเดล Random Forest

กลับมาทำงานกับชุดข้อมูล Pima Indians อีกครั้ง คราวนี้จะใช้ Random Forest Classifier เพื่อทำนายว่าบุคคลนั้นเป็นเบาหวานหรือไม่ โดยจะฝึกโมเดลบนข้อมูลชุด training หลังจากแบ่ง train-test split แล้ว และดูค่าความสำคัญของแต่ละ feature

ชุดข้อมูล feature และ target ถูกโหลดไว้ให้แล้วในชื่อ X และ y รวมถึงแพ็กเกจและฟังก์ชันที่จำเป็นด้วย

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การลดมิติข้อมูลใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • กำหนด test size เป็น 25% เพื่อแบ่งข้อมูลแบบ 75%-25% train-test split
  • ฝึก Random Forest Classifier บนข้อมูลชุด training
  • คำนวณความแม่นยำบนชุดข้อมูล test
  • แสดงค่าความสำคัญของแต่ละ feature

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Perform a 75% training and 25% test data split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=____, random_state=0)

# Fit the random forest model to the training data
rf = RandomForestClassifier(random_state=0)
rf.____(____, ____)

# Calculate the accuracy
acc = accuracy_score(____, ____)

# Print the importances per feature
print(dict(zip(X.columns, rf.____.round(2))))

# Print accuracy
print(f"{acc:.1%} accuracy on test set.") 
แก้ไขและรันโค้ด