我目前在App的内容推荐系统中使用的是ALS协同过滤方式。它似乎工作得很好,预测部分很快,但训练模型部分需要20秒以上。我需要它至少是1秒或更少,因为我需要几乎实时的建议。我目前使用的是一个有3台机器的spark集群,每个节点有17 has。我也使用datastax,但这不会有任何影响。
我真的不知道为什么以及如何改进这一点?很高兴有任何建议,谢谢。
下面是基本的spark代码:
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
# Load and parse the data
data = sc.textFile("data/mllib/als/test.data")
ratings = data.map(lambda l: l.split(','))\
.map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))这部分需要超过20秒,但应该只需要不到1秒。
# Build the recommendation model using Alternating Least Squares
rank = 10
numIterations = 10
model = ALS.train(ratings, rank, numIterations)
# Evaluate the model on training data
testdata = ratings.map(lambda p: (p[0], p[1]))
predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))
ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)
MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1])**2).mean()
print("Mean Squared Error = " + str(MSE))
# Save and load model
model.save(sc, "target/tmp/myCollaborativeFilter")
sameModel = MatrixFactorizationModel.load(sc, "target/tmp/myCollaborativeFilter")发布于 2020-02-19 17:44:50
这可能需要时间的原因之一是因为RDDs。对于RDDs,没有特定的结构/模式。因此,这些往往会有点慢。当调用ALS.train()时,在RDD的幕后发生的一些操作,如平面映射、计数、映射,将不得不考虑嵌套结构,因此速度很慢。
相反,您可以尝试使用Dataframe而不是RDDs。Dataframe操作是最佳的,因为模式/类型是已知的。但是为了让ALS在数据帧上工作,你必须从"ml.recommendation“导入ALS。我也有同样的问题,当我尝试使用数据帧而不是RDDs时,它工作得非常好。
当您的数据变得非常大时,您也可以尝试检查点。
https://stackoverflow.com/questions/36709379
复制相似问题