ค้นหาความลึกของ tree ที่เหมาะสมที่สุด
ในแบบฝึกหัดนี้ จะได้ปรับพารามิเตอร์ max_depth ของ decision tree เพื่อหาค่าที่ช่วยลด over-fitting ในขณะที่ยังคงประสิทธิภาพของโมเดลไว้ได้ดี โดยจะรัน for loop ผ่านค่า max_depth หลายค่า แล้ว fit decision tree สำหรับแต่ละค่า จากนั้นคำนวณค่าเมตริกประสิทธิภาพ
ลิสต์ depth_list ที่มีค่าพารามิเตอร์ที่ต้องการทดสอบถูกโหลดไว้ให้แล้ว อาร์เรย์ depth_tuning ถูกสร้างไว้ให้มี 2 คอลัมน์ โดยคอลัมน์แรกบรรจุค่า depth ที่เป็นตัวเลือก และคอลัมน์ถัดไปเป็น placeholder สำหรับ recall score นอกจากนี้ ตัวแปร features และ target ถูกโหลดเป็น train_X, train_Y สำหรับข้อมูลฝึก และ test_X, test_Y สำหรับข้อมูลทดสอบ ไลบรารี numpy และ pandas ถูกโหลดเป็น np และ pd ตามลำดับ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับการตลาดด้วย Python
คำแนะนำการฝึกหัด
- รัน
forloop ในช่วงตั้งแต่ 0 ถึงความยาวของลิสต์depth_list - สำหรับแต่ละค่า depth ที่เป็นตัวเลือก ให้ initialize และ fit decision tree classifier แล้วพยากรณ์การ churn บนข้อมูลทดสอบ
- สำหรับแต่ละค่า depth ที่เป็นตัวเลือก ให้คำนวณ recall score โดยใช้ฟังก์ชัน
recall_score()แล้วเก็บผลลัพธ์ไว้ในคอลัมน์ที่สองของdepth_tunning - สร้าง DataFrame ด้วย
pandasจากdepth_tuningพร้อมระบุชื่อคอลัมน์ที่เหมาะสม
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Run a for loop over the range of depth list length
for index in ___(0, len(depth_list)):
# Initialize and fit decision tree with the `max_depth` candidate
mytree = DecisionTreeClassifier(___=depth_list[index])
mytree.fit(___, train_Y)
# Predict churn on the testing data
pred_test_Y = mytree.predict(___)
# Calculate the recall score
depth_tuning[index,1] = ___(test_Y, ___)
# Name the columns and print the array as pandas DataFrame
col_names = ['Max_Depth','Recall']
print(pd.DataFrame(depth_tuning, columns=___))