Pickles
ถึงเวลาแล้วที่จะนำโมเดลแรกของคุณขึ้น production โมเดลที่ใช้คือ random forest classifier ซึ่งจะทำหน้าที่เป็น baseline ในขณะที่กำลังพัฒนาทางเลือกที่ดีกว่า คุณมีข้อมูลที่แบ่งเป็นชุด train และ test พร้อมชื่อตัวแปรตามปกติ ได้แก่ X_train, X_test, y_train และ y_test รวมถึงโมดูล RandomForestClassifier() และ pickle ซึ่งมีเมธอด .load() และ .dump() ที่จะใช้ในแบบฝึกหัดนี้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การออกแบบ Machine Learning Workflows ด้วย Python
คำแนะนำการฝึกหัด
- Fit random forest classifier กับข้อมูล โดยกำหนด random seed เป็น 42 เพื่อให้ผลลัพธ์ reproducible
- เขียนโมเดลลงไฟล์โดยใช้ pickle เปิดไฟล์ปลายทางด้วย syntax
with open(____) as ____ - โหลดโมเดลจากไฟล์ไปยังตัวแปรชื่อใหม่
clf_from_file - เก็บผลการพยากรณ์จากโมเดลที่โหลดมาไว้ในตัวแปร
preds
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Fit a random forest to the training set
clf = ____(____=42).____(
X_train, y_train)
# Save it to a file, to be pushed to production
with ____('model.pkl', ____) as ____:
pickle.____(clf, file=file)
# Now load the model from file in the production environment
with ____ as file:
clf_from_file = pickle.____(file)
# Predict the labels of the test dataset
preds = clf_from_file.____