运行交叉验证的隐式 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: ", ____[____])