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

การประเมินโมเดลด้วย MSE

หลังจากสร้างค่า rating ที่พยากรณ์ได้จากข้อมูลทดสอบด้วยโมเดล ALS แล้ว ในขั้นตอนสุดท้ายนี้ จะเตรียมข้อมูลสำหรับคำนวณ Mean Square Error (MSE) ของโมเดล โดย MSE คือค่าเฉลี่ยของ (original rating – predicted rating)**2 สำหรับผู้ใช้ทุกคน ซึ่งบ่งชี้ว่าโมเดลพอดีกับข้อมูลมากน้อยเพียงใด

ขั้นแรก จัดระเบียบ RDD ทั้ง ratings_final และ predictions ให้อยู่ในรูป tuple ของ ((user, product), rating)) โดยใน RDD ทั้งสองมีการ mapping ดังนี้:

0: user
1: product
2: rating

จากนั้น join RDD ที่แปลงแล้วเข้าด้วยกัน แล้วนำฟังก์ชันหาผลต่างยกกำลังสองมาใช้ร่วมกับ mean() เพื่อคำนวณค่า MSE

อย่าลืมว่า SparkContext sc พร้อมใช้งานใน workspace รวมถึง ratings_final และ predictions RDD ก็มีอยู่แล้วใน workspace เช่นกัน

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

Big Data Fundamentals with PySpark

ดูคอร์ส

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

  • จัดระเบียบ ratings RDD ให้อยู่ในรูป ((user, product), rating)
  • จัดระเบียบ predictions RDD ให้อยู่ในรูป ((user, product), rating)
  • Join prediction RDD เข้ากับ ratings RDD
  • ประเมินโมเดลด้วย MSE ระหว่าง rating จริงและ rating ที่พยากรณ์ได้ แล้วแสดงผลลัพธ์

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

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

# Prepare ratings data
rates = ratings_final.____(lambda r: ((r[0], r[1]), ____))

# Prepare predictions data
preds = predictions.____(lambda r: ((____, ____), ____))

# Join the ratings data with predictions data
rates_and_preds = rates.____(preds)

# Calculate and print MSE
MSE = rates_and_preds.____(lambda r: (r[1][0] - r[1]____)**2).mean()
print("Mean Squared Error of the model for the test data = {:.2f}".format(____))
แก้ไขและรันโค้ด