開始使用免費開始

執行交叉驗證的隱式 ALS 模型

現在我們已經有多個 ALS 模型,每個都有不同的超參數組合。你可以用交叉驗證把它們訓練在 msd 資料集的訓練部分,接著在測試集上評估效能,並用前面介紹的 ROEM 函式來比較表現。不過,這個步驟在本練習中會花費太多時間,因此我們已經事先跑好。但供你參考,你可以用下面的迴圈來評估你的 model_list(此處使用的是 msd 資料集):

# Split the data into training and test sets
(training, test) = msd.randomSplit([0.8, 0.2])

#Building 5 folds within the training set.
train1, train2, train3, train4, train5 = training.randomSplit([0.2, 0.2, 0.2, 0.2, 0.2], seed = 1)
fold1 = train2.union(train3).union(train4).union(train5)
fold2 = train3.union(train4).union(train5).union(train1)
fold3 = train4.union(train5).union(train1).union(train2)
fold4 = train5.union(train1).union(train2).union(train3)
fold5 = train1.union(train2).union(train3).union(train4)

foldlist = [(fold1, train1), (fold2, train2), (fold3, train3), (fold4, train4), (fold5, train5)]

# Empty list to fill with ROEMs from each model
ROEMS = []

# Loops through all models and all folds
for model in model_list:
    for ft_pair in foldlist:

        # Fits model to fold within training data
        fitted_model = model.fit(ft_pair[0])

        # Generates predictions using fitted_model on respective CV test data
        predictions = fitted_model.transform(ft_pair[1])

        # Generates and prints a ROEM metric CV test data
        r = ROEM(predictions)
        print ("ROEM: ", r)

    # Fits model to all of training data and generates preds for test data
    v_fitted_model = model.fit(training)
    v_predictions = v_fitted_model.transform(test)
    v_ROEM = ROEM(v_predictions)

    # Adds validation ROEM to ROEM list
    ROEMS.append(v_ROEM)
    print ("Validation ROEM: ", v_ROEM)

為了帶你走過整個流程,我們已經替 192 個模型產生了測試預測,並計算好各自的 ROEM。這些數值已放在提供給你的 ROEMS 清單中。由於清單不是 Pyspark 特有的型別,而且 numpy 對清單操作很方便,我們這裡會用 numpy。請依照下方說明找出最佳的 ROEM,以及產生它的模型。

本練習屬於課程

使用 PySpark 打造推薦引擎

檢視課程

練習說明

  • 匯入 numpy
  • 使用 numpy.argmin() 從提供的 ROEMS 清單中取出最小的 ROEM。.argmin() 會回傳清單中最小值的索引。把結果命名為 i,並印出 i
  • 使用清單索引,在 ROEMS 清單中取得索引 i 的值。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import numpy
import numpy

# Find the index of the smallest ROEM
i = numpy.____(____)
print("Index of smallest ROEM:", ____)

# Find ith element of ROEMS
print("Smallest ROEM: ", ____[____])
編輯並執行程式碼