pythonpysparkdistributionapache-spark-mllibmatrix-factorization

Recommendation for subset of users using Pyspark mllib ALS/MatrixFactorizationModel


I have built a model using the below code:

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'])

Now I want to predict campaigns for all users (or a subset of users) using distributed environment provided by spark.

I tried recommendProductsForUsers which is taking ages to get me 32M Users X 4000 Products.

preds = model1.recommendProductsForUsers(num=4000)

I really don't need recommendations for all 32M users. I am fine with 100k-200k users as well.

So to modify my process, I tried the spark udf way to process for each user one by one, but using distribution mechanism of spark cluster:

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')))

Test contains around 200,000 users. The above fails with the following error:

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.

How to perform the recommendations for a subset of users better?

(EDIT)

From @piscall's response. I tried to do the same using an 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.

Solution

  • what I would do is to use predictAll method. Assume that df_products is a dataframe containing all 4,000 products and df_users a dataframe with the 100-200K selected users, then do a crossJoin to find all combination of two data sets to form the testdata, then use predictAll which will yield Rating objects of selected users over the 4000 products:

    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()
    

    Use the example from the documentation which has 4 products(1,2,3,4) and 4 users (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)]
    

    Note: you might want to screen out users which are not in the existing model before creating testdata and process them separately.