使用 MSE 進行模型評估
在使用 ALS 模型對測試資料產生預測評分之後,這個練習的最後部分要準備資料,以計算模型的均方誤差(Mean Square Error,MSE)。MSE 是所有使用者的 (original rating – predicted rating)**2 的平均值,用來表示模型對資料的絕對擬合程度。
為此,你會先把 ratings_final 和 predictions 這兩個 RDD 都整理成 ((user, product), rating) 的格式。兩個 RDD 的欄位對應為:
0: user
1: product
2: rating
接著將轉換後的 RDD 進行 join,最後套用平方差函式並搭配 mean() 來取得 MSE。
請記得,你的工作區中已可使用 SparkContext sc。此外,ratings_final 與 predictions 這兩個 RDD 也已經在你的工作區中可用。
本練習屬於課程
使用 PySpark 的 Big Data 基礎
練習說明
- 整理
ratingsRDD,轉為((user, product), rating)。 - 整理
predictionsRDD,轉為((user, product), rating)。 - 將 prediction RDD 與 ratings RDD 進行 join。
- 使用原始評分與預測評分之間的 MSE 來評估模型,並印出結果。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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(____))