python - 针对使用 Pyspark mllib ALS/MatrixFactorizationModel 的用户子集的建议

标签 python pyspark distribution apache-spark-mllib matrix-factorization

我使用以下代码构建了一个模型:

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/

相关文章:

python - pydub在音频段大文件时能不导致内存错误吗?

python - 如何在 Python 中创建类似 echo 的全局命令,并通过 pip 进行安装?

apache-spark - 通过 PySpark 在 Kafka-Spark Structured Streaming 集成中遇到 NoClassDefFoundError 错误

c# - 使用 Math.NET 计算临界值 T-Score

javascript - 如何从Google自定义搜索下载搜索结果?

python - 在Python中计算位图中两点之间的最短路径

python - PySpark HDFS 数据流读/写

python - 在 Spark 中加入 DF 后删除重复的列

python - matplotlib.mlab.normpdf() 的正确用法是什么?

iPhone 应用程序崩溃且没有日志(仅具有分发配置文件)