- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用以下代码构建了一个模型:
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
model1 = ALS.train(ratings=ratingsR, rank=model_params['rank'], \
iterations=model_params['iterations'], lambda_=model_params['lambda'], \
blocks=model_params['blocks'], nonnegative=model_params['nonnegative'], \
seed=model_params['seed'])
现在我想使用 Spark 提供的分布式环境来预测所有用户(或一部分用户)的事件。
我尝试了 recommendProductsForUsers
,这花了很长时间才让我获得 3200 万用户 X 4000 个产品。
preds = model1.recommendProductsForUsers(num=4000)
我真的不需要为所有 3200 万用户提供推荐。我也可以接受 10 万到 20 万用户。
因此为了修改我的流程,我尝试了spark udf方式为每个用户一一处理,但使用spark集群的分发机制:
import pyspark.sql.functions as F
def udf_preds(sameModel):
return F.udf(lambda x: get_predictions(x, sameModel))
def get_predictions(x, sameModel):
preds = sameModel.recommendProducts(user=x, num=4000) # per user it takes around 4s
return preds
test.withColumn('predictions', udf_preds(model1)(F.col('user_id')))
测试包含大约 200,000 个用户。上述失败并出现以下错误:
PicklingError: Could not serialize object: Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.
如何更好地为一小部分用户执行推荐?
(编辑)
摘自@piscall 的回复。我尝试使用 RDD 做同样的事情。
preds_rdd = test.rdd.map(lambda x: (x.user_id, sameModel.recommendProducts(x.user_id, 4000)))
preds_rdd.take(2)
File "/usr/hdp/current/spark2-client/python/pyspark/context.py", line 330, in __getnewargs__
"It appears that you are attempting to reference SparkContext from a broadcast "
Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.
PicklingErrorTraceback (most recent call last)
<ipython-input-17-e114800a26e7> in <module>()
----> 1 preds_rdd.take(2)
/usr/hdp/current/spark2-client/python/pyspark/rdd.py in take(self, num)
1356
1357 p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts))
-> 1358 res = self.context.runJob(self, takeUpToNumLeft, p)
1359
1360 items += res
/usr/hdp/current/spark2-client/python/pyspark/context.py in runJob(self, rdd, partitionFunc, partitions, allowLocal)
1038 # SparkContext#runJob.
1039 mappedRDD = rdd.mapPartitions(partitionFunc)
-> 1040 sock_info = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)
1041 return list(_load_from_socket(sock_info, mappedRDD._jrdd_deserializer))
1042
/usr/hdp/current/spark2-client/python/pyspark/rdd.py in _jrdd(self)
2470
2471 wrapped_func = _wrap_function(self.ctx, self.func, self._prev_jrdd_deserializer,
-> 2472 self._jrdd_deserializer, profiler)
2473 python_rdd = self.ctx._jvm.PythonRDD(self._prev_jrdd.rdd(), wrapped_func,
2474 self.preservesPartitioning)
/usr/hdp/current/spark2-client/python/pyspark/rdd.py in _wrap_function(sc, func, deserializer, serializer, profiler)
2403 assert serializer, "serializer should not be empty"
2404 command = (func, profiler, deserializer, serializer)
-> 2405 pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
2406 return sc._jvm.PythonFunction(bytearray(pickled_command), env, includes, sc.pythonExec,
2407 sc.pythonVer, broadcast_vars, sc._javaAccumulator)
/usr/hdp/current/spark2-client/python/pyspark/rdd.py in _prepare_for_python_RDD(sc, command)
2389 # the serialized command will be compressed by broadcast
2390 ser = CloudPickleSerializer()
-> 2391 pickled_command = ser.dumps(command)
2392 if len(pickled_command) > (1 << 20): # 1M
2393 # The broadcast will have same life cycle as created PythonRDD
/usr/hdp/current/spark2-client/python/pyspark/serializers.py in dumps(self, obj)
573
574 def dumps(self, obj):
--> 575 return cloudpickle.dumps(obj, 2)
576
577
/usr/hdp/current/spark2-client/python/pyspark/cloudpickle.py in dumps(obj, protocol)
916
917 cp = CloudPickler(file,protocol)
--> 918 cp.dump(obj)
919
920 return file.getvalue()
/u
I have built a model using the below code:
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
sr/hdp/current/spark2-client/python/pyspark/cloudpickle.py in dump(self, obj)
247 msg = "Could not serialize object: %s: %s" % (e.__class__.__name__, emsg)
248 print_exec(sys.stderr)
--> 249 raise pickle.PicklingError(msg)
250
251
PicklingError: Could not serialize object: Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.
最佳答案
我会做的是使用 predictAll方法。假设df_products是包含所有4,000个产品的数据框,df_users是包含100-200K选定用户的数据框,然后进行crossJoin以找到两个数据集的所有组合以形成测试数据,然后使用 PredictAll 它将生成 4000 个产品中选定用户的评级对象:
from pyspark.sql.functions import broadcast
from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating
testdata = broadcast(df_products).crossJoin(df_users).select('user', 'product').rdd.map(tuple)
model.predictAll(testdata).collect()
使用 documentation 中的示例其中有 4 个产品(1,2,3,4)和 4 个用户(1,2,3,4):
df_products.collect()
# [Row(product=1), Row(product=3), Row(product=2), Row(product=4)]
# a subset of all users:
df_users.collect()
# [Row(user=1), Row(user=3)]
testdata.collect()
# [(1, 1), (1, 3), (1, 2), (1, 4), (3, 1), (3, 3), (3, 2), (3, 4)]
model.predictAll(testdata).collect()
#[Rating(user=1, product=4, rating=0.9999459747142155),
# Rating(user=3, product=4, rating=4.99555263974573),
# Rating(user=1, product=1, rating=4.996821463543848),
# Rating(user=3, product=1, rating=1.000199620693615),
# Rating(user=1, product=3, rating=4.996821463543848),
# Rating(user=3, product=3, rating=1.000199620693615),
# Rating(user=1, product=2, rating=0.9999459747142155),
# Rating(user=3, product=2, rating=4.99555263974573)]
注意:在创建测试数据
之前,您可能希望筛选出不在现有模型中的用户并单独处理它们。
关于python - 针对使用 Pyspark mllib ALS/MatrixFactorizationModel 的用户子集的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58969157/
我有 MatrixFactorizationModel 对象。如果我在通过 ALS.train(...) 构建模型后立即尝试向单个用户推荐产品,则需要 300 毫秒(对于我的数据和硬件)。但是如果我将
给定一个 MatrixFactorizationModel返回完整的用户产品预测矩阵的最有效方法是什么(实际上,通过某个阈值过滤以保持稀疏性)? 通过当前的 API,曾经可以将用户产品的笛卡尔积传递给
我正在尝试使用 Spark 协同过滤来实现推荐系统。 首先我准备模型并保存到磁盘: MatrixFactorizationModel model = trainModel(inputDataRdd);
我使用以下代码构建了一个模型: from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating model
我为 MovieLens DB 构建了一个简单的推荐系统,灵感来自 https://databricks-training.s3.amazonaws.com/movie-recommendation-
我训练了一个 MatrixFactorizationModel 模型使用 ALS.train() 现在使用 model.recommendProducts(user, num) 获得最推荐的产品,但代
我有 9 个节点集群,每个节点都有以下配置, 我正在尝试使用 ' recommendProductsForUsers 为 MatrixFactorizationModel 中的所有用户生成建议' 功能
我是一名优秀的程序员,十分优秀!