2013-12-25 00:08:05 -05:00
|
|
|
#
|
|
|
|
# Licensed to the Apache Software Foundation (ASF) under one or more
|
|
|
|
# contributor license agreements. See the NOTICE file distributed with
|
|
|
|
# this work for additional information regarding copyright ownership.
|
|
|
|
# The ASF licenses this file to You under the Apache License, Version 2.0
|
|
|
|
# (the "License"); you may not use this file except in compliance with
|
|
|
|
# the License. You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
#
|
|
|
|
|
2015-04-16 19:20:57 -04:00
|
|
|
import array
|
[SPARK-4396] allow lookup by index in Python's Rating
In PySpark, ALS can take an RDD of (user, product, rating) tuples as input. However, model.predict outputs an RDD of Rating. So on the input side, users can use r[0], r[1], r[2], while on the output side, users have to use r.user, r.product, r.rating. We should allow lookup by index in Rating by making Rating a namedtuple.
davies
<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/apache/spark/3261)
<!-- Reviewable:end -->
Author: Xiangrui Meng <meng@databricks.com>
Closes #3261 from mengxr/SPARK-4396 and squashes the following commits:
543aef0 [Xiangrui Meng] use named tuple to implement ALS
0b61bae [Xiangrui Meng] Merge remote-tracking branch 'apache/master' into SPARK-4396
d3bd7d4 [Xiangrui Meng] allow lookup by index in Python's Rating
2014-11-18 13:35:29 -05:00
|
|
|
from collections import namedtuple
|
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
from pyspark import SparkContext
|
2014-01-04 19:23:17 -05:00
|
|
|
from pyspark.rdd import RDD
|
2015-03-01 19:26:57 -05:00
|
|
|
from pyspark.mllib.common import JavaModelWrapper, callMLlibFunc, inherit_doc
|
2015-03-03 01:27:01 -05:00
|
|
|
from pyspark.mllib.util import JavaLoader, JavaSaveable
|
2015-04-21 19:44:52 -04:00
|
|
|
from pyspark.sql import DataFrame
|
2013-12-25 00:08:05 -05:00
|
|
|
|
[SPARK-4396] allow lookup by index in Python's Rating
In PySpark, ALS can take an RDD of (user, product, rating) tuples as input. However, model.predict outputs an RDD of Rating. So on the input side, users can use r[0], r[1], r[2], while on the output side, users have to use r.user, r.product, r.rating. We should allow lookup by index in Rating by making Rating a namedtuple.
davies
<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/apache/spark/3261)
<!-- Reviewable:end -->
Author: Xiangrui Meng <meng@databricks.com>
Closes #3261 from mengxr/SPARK-4396 and squashes the following commits:
543aef0 [Xiangrui Meng] use named tuple to implement ALS
0b61bae [Xiangrui Meng] Merge remote-tracking branch 'apache/master' into SPARK-4396
d3bd7d4 [Xiangrui Meng] allow lookup by index in Python's Rating
2014-11-18 13:35:29 -05:00
|
|
|
__all__ = ['MatrixFactorizationModel', 'ALS', 'Rating']
|
2014-09-03 14:49:45 -04:00
|
|
|
|
2014-05-25 20:15:01 -04:00
|
|
|
|
[SPARK-4396] allow lookup by index in Python's Rating
In PySpark, ALS can take an RDD of (user, product, rating) tuples as input. However, model.predict outputs an RDD of Rating. So on the input side, users can use r[0], r[1], r[2], while on the output side, users have to use r.user, r.product, r.rating. We should allow lookup by index in Rating by making Rating a namedtuple.
davies
<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/apache/spark/3261)
<!-- Reviewable:end -->
Author: Xiangrui Meng <meng@databricks.com>
Closes #3261 from mengxr/SPARK-4396 and squashes the following commits:
543aef0 [Xiangrui Meng] use named tuple to implement ALS
0b61bae [Xiangrui Meng] Merge remote-tracking branch 'apache/master' into SPARK-4396
d3bd7d4 [Xiangrui Meng] allow lookup by index in Python's Rating
2014-11-18 13:35:29 -05:00
|
|
|
class Rating(namedtuple("Rating", ["user", "product", "rating"])):
|
|
|
|
"""
|
|
|
|
Represents a (user, product, rating) tuple.
|
2014-09-19 18:01:11 -04:00
|
|
|
|
[SPARK-4396] allow lookup by index in Python's Rating
In PySpark, ALS can take an RDD of (user, product, rating) tuples as input. However, model.predict outputs an RDD of Rating. So on the input side, users can use r[0], r[1], r[2], while on the output side, users have to use r.user, r.product, r.rating. We should allow lookup by index in Rating by making Rating a namedtuple.
davies
<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/apache/spark/3261)
<!-- Reviewable:end -->
Author: Xiangrui Meng <meng@databricks.com>
Closes #3261 from mengxr/SPARK-4396 and squashes the following commits:
543aef0 [Xiangrui Meng] use named tuple to implement ALS
0b61bae [Xiangrui Meng] Merge remote-tracking branch 'apache/master' into SPARK-4396
d3bd7d4 [Xiangrui Meng] allow lookup by index in Python's Rating
2014-11-18 13:35:29 -05:00
|
|
|
>>> r = Rating(1, 2, 5.0)
|
|
|
|
>>> (r.user, r.product, r.rating)
|
|
|
|
(1, 2, 5.0)
|
|
|
|
>>> (r[0], r[1], r[2])
|
|
|
|
(1, 2, 5.0)
|
|
|
|
"""
|
2014-09-19 18:01:11 -04:00
|
|
|
|
[SPARK-4396] allow lookup by index in Python's Rating
In PySpark, ALS can take an RDD of (user, product, rating) tuples as input. However, model.predict outputs an RDD of Rating. So on the input side, users can use r[0], r[1], r[2], while on the output side, users have to use r.user, r.product, r.rating. We should allow lookup by index in Rating by making Rating a namedtuple.
davies
<!-- Reviewable:start -->
[<img src="https://reviewable.io/review_button.png" height=40 alt="Review on Reviewable"/>](https://reviewable.io/reviews/apache/spark/3261)
<!-- Reviewable:end -->
Author: Xiangrui Meng <meng@databricks.com>
Closes #3261 from mengxr/SPARK-4396 and squashes the following commits:
543aef0 [Xiangrui Meng] use named tuple to implement ALS
0b61bae [Xiangrui Meng] Merge remote-tracking branch 'apache/master' into SPARK-4396
d3bd7d4 [Xiangrui Meng] allow lookup by index in Python's Rating
2014-11-18 13:35:29 -05:00
|
|
|
def __reduce__(self):
|
|
|
|
return Rating, (int(self.user), int(self.product), float(self.rating))
|
2014-09-19 18:01:11 -04:00
|
|
|
|
|
|
|
|
2015-03-01 19:26:57 -05:00
|
|
|
@inherit_doc
|
2015-03-03 01:27:01 -05:00
|
|
|
class MatrixFactorizationModel(JavaModelWrapper, JavaSaveable, JavaLoader):
|
2014-08-06 15:58:24 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
"""A matrix factorisation model trained by regularized alternating
|
|
|
|
least-squares.
|
|
|
|
|
|
|
|
>>> r1 = (1, 1, 1.0)
|
|
|
|
>>> r2 = (1, 2, 2.0)
|
|
|
|
>>> r3 = (2, 1, 2.0)
|
|
|
|
>>> ratings = sc.parallelize([r1, r2, r3])
|
2014-11-08 01:53:01 -05:00
|
|
|
>>> model = ALS.trainImplicit(ratings, 1, seed=10)
|
2015-02-03 02:49:09 -05:00
|
|
|
>>> model.predict(2, 2)
|
2015-04-01 19:47:18 -04:00
|
|
|
0.4...
|
2014-09-19 18:01:11 -04:00
|
|
|
|
2014-01-06 15:19:43 -05:00
|
|
|
>>> testset = sc.parallelize([(1, 2), (1, 1)])
|
2015-02-03 02:49:09 -05:00
|
|
|
>>> model = ALS.train(ratings, 2, seed=0)
|
2014-11-08 01:53:01 -05:00
|
|
|
>>> model.predictAll(testset).collect()
|
2015-02-03 02:49:09 -05:00
|
|
|
[Rating(user=1, product=1, rating=1.0...), Rating(user=1, product=2, rating=1.9...)]
|
2014-10-21 14:49:39 -04:00
|
|
|
|
2014-11-08 01:53:01 -05:00
|
|
|
>>> model = ALS.train(ratings, 4, seed=10)
|
|
|
|
>>> model.userFeatures().collect()
|
2015-02-03 02:49:09 -05:00
|
|
|
[(1, array('d', [...])), (2, array('d', [...]))]
|
2014-10-21 14:49:39 -04:00
|
|
|
|
2015-05-01 02:51:00 -04:00
|
|
|
>>> model.recommendUsers(1, 2)
|
|
|
|
[Rating(user=2, product=1, rating=1.9...), Rating(user=1, product=1, rating=1.0...)]
|
|
|
|
>>> model.recommendProducts(1, 2)
|
|
|
|
[Rating(user=1, product=2, rating=1.9...), Rating(user=1, product=1, rating=1.0...)]
|
|
|
|
>>> model.rank
|
|
|
|
4
|
|
|
|
|
2014-10-21 14:49:39 -04:00
|
|
|
>>> first_user = model.userFeatures().take(1)[0]
|
|
|
|
>>> latents = first_user[1]
|
|
|
|
>>> len(latents) == 4
|
|
|
|
True
|
|
|
|
|
2014-11-08 01:53:01 -05:00
|
|
|
>>> model.productFeatures().collect()
|
2015-02-03 02:49:09 -05:00
|
|
|
[(1, array('d', [...])), (2, array('d', [...]))]
|
2014-10-21 14:49:39 -04:00
|
|
|
|
|
|
|
>>> first_product = model.productFeatures().take(1)[0]
|
|
|
|
>>> latents = first_product[1]
|
|
|
|
>>> len(latents) == 4
|
|
|
|
True
|
2014-11-08 01:53:01 -05:00
|
|
|
|
|
|
|
>>> model = ALS.train(ratings, 1, nonnegative=True, seed=10)
|
2015-04-21 19:44:52 -04:00
|
|
|
>>> model.predict(2, 2)
|
|
|
|
3.8...
|
|
|
|
|
|
|
|
>>> df = sqlContext.createDataFrame([Rating(1, 1, 1.0), Rating(1, 2, 2.0), Rating(2, 1, 2.0)])
|
|
|
|
>>> model = ALS.train(df, 1, nonnegative=True, seed=10)
|
|
|
|
>>> model.predict(2, 2)
|
2015-02-03 02:49:09 -05:00
|
|
|
3.8...
|
2014-11-08 01:53:01 -05:00
|
|
|
|
|
|
|
>>> model = ALS.trainImplicit(ratings, 1, nonnegative=True, seed=10)
|
2015-04-21 19:44:52 -04:00
|
|
|
>>> model.predict(2, 2)
|
2015-04-01 19:47:18 -04:00
|
|
|
0.4...
|
2015-03-01 19:26:57 -05:00
|
|
|
|
|
|
|
>>> import os, tempfile
|
|
|
|
>>> path = tempfile.mkdtemp()
|
|
|
|
>>> model.save(sc, path)
|
|
|
|
>>> sameModel = MatrixFactorizationModel.load(sc, path)
|
2015-04-21 19:44:52 -04:00
|
|
|
>>> sameModel.predict(2, 2)
|
2015-04-01 19:47:18 -04:00
|
|
|
0.4...
|
2015-03-28 18:08:05 -04:00
|
|
|
>>> sameModel.predictAll(testset).collect()
|
|
|
|
[Rating(...
|
2015-03-01 19:26:57 -05:00
|
|
|
>>> try:
|
|
|
|
... os.removedirs(path)
|
2015-03-03 01:27:01 -05:00
|
|
|
... except OSError:
|
2015-03-01 19:26:57 -05:00
|
|
|
... pass
|
2013-12-25 00:08:05 -05:00
|
|
|
"""
|
|
|
|
def predict(self, user, product):
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
|
|
|
Predicts rating for the given user and product.
|
|
|
|
"""
|
2014-11-11 01:26:16 -05:00
|
|
|
return self._java_model.predict(int(user), int(product))
|
2013-12-25 00:08:05 -05:00
|
|
|
|
2014-09-19 18:01:11 -04:00
|
|
|
def predictAll(self, user_product):
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
|
|
|
Returns a list of predicted ratings for input user and product pairs.
|
|
|
|
"""
|
2014-09-19 18:01:11 -04:00
|
|
|
assert isinstance(user_product, RDD), "user_product should be RDD of (user, product)"
|
|
|
|
first = user_product.first()
|
2014-10-31 01:25:18 -04:00
|
|
|
assert len(first) == 2, "user_product should be RDD of (user, product)"
|
2015-04-16 19:20:57 -04:00
|
|
|
user_product = user_product.map(lambda u_p: (int(u_p[0]), int(u_p[1])))
|
2014-10-31 01:25:18 -04:00
|
|
|
return self.call("predict", user_product)
|
2014-01-04 19:23:17 -05:00
|
|
|
|
2014-10-21 14:49:39 -04:00
|
|
|
def userFeatures(self):
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
|
|
|
Returns a paired RDD, where the first element is the user and the
|
|
|
|
second is an array of features corresponding to that user.
|
|
|
|
"""
|
2015-04-16 19:20:57 -04:00
|
|
|
return self.call("getUserFeatures").mapValues(lambda v: array.array('d', v))
|
2014-10-21 14:49:39 -04:00
|
|
|
|
|
|
|
def productFeatures(self):
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
|
|
|
Returns a paired RDD, where the first element is the product and the
|
|
|
|
second is an array of features corresponding to that product.
|
|
|
|
"""
|
2015-04-16 19:20:57 -04:00
|
|
|
return self.call("getProductFeatures").mapValues(lambda v: array.array('d', v))
|
2014-10-21 14:49:39 -04:00
|
|
|
|
2015-05-01 02:51:00 -04:00
|
|
|
def recommendUsers(self, product, num):
|
|
|
|
"""
|
|
|
|
Recommends the top "num" number of users for a given product and returns a list
|
|
|
|
of Rating objects sorted by the predicted rating in descending order.
|
|
|
|
"""
|
|
|
|
return list(self.call("recommendUsers", product, num))
|
|
|
|
|
|
|
|
def recommendProducts(self, user, num):
|
|
|
|
"""
|
|
|
|
Recommends the top "num" number of products for a given user and returns a list
|
|
|
|
of Rating objects sorted by the predicted rating in descending order.
|
|
|
|
"""
|
|
|
|
return list(self.call("recommendProducts", user, num))
|
|
|
|
|
|
|
|
@property
|
|
|
|
def rank(self):
|
|
|
|
return self.call("rank")
|
|
|
|
|
2015-03-28 18:08:05 -04:00
|
|
|
@classmethod
|
|
|
|
def load(cls, sc, path):
|
|
|
|
model = cls._load_java(sc, path)
|
|
|
|
wrapper = sc._jvm.MatrixFactorizationModelWrapper(model)
|
|
|
|
return MatrixFactorizationModel(wrapper)
|
|
|
|
|
2014-05-25 20:15:01 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
class ALS(object):
|
2014-08-06 15:58:24 -04:00
|
|
|
|
2014-09-19 18:01:11 -04:00
|
|
|
@classmethod
|
|
|
|
def _prepare(cls, ratings):
|
2015-04-21 19:44:52 -04:00
|
|
|
if isinstance(ratings, RDD):
|
|
|
|
pass
|
|
|
|
elif isinstance(ratings, DataFrame):
|
|
|
|
ratings = ratings.rdd
|
|
|
|
else:
|
|
|
|
raise TypeError("Ratings should be represented by either an RDD or a DataFrame, "
|
|
|
|
"but got %s." % type(ratings))
|
2014-09-19 18:01:11 -04:00
|
|
|
first = ratings.first()
|
2015-04-21 19:44:52 -04:00
|
|
|
if isinstance(first, Rating):
|
|
|
|
pass
|
|
|
|
elif isinstance(first, (tuple, list)):
|
|
|
|
ratings = ratings.map(lambda x: Rating(*x))
|
|
|
|
else:
|
|
|
|
raise TypeError("Expect a Rating or a tuple/list, but got %s." % type(first))
|
2014-11-21 18:02:31 -05:00
|
|
|
return ratings
|
2014-09-19 18:01:11 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
@classmethod
|
2014-11-08 01:53:01 -05:00
|
|
|
def train(cls, ratings, rank, iterations=5, lambda_=0.01, blocks=-1, nonnegative=False,
|
|
|
|
seed=None):
|
2014-10-31 01:25:18 -04:00
|
|
|
model = callMLlibFunc("trainALSModel", cls._prepare(ratings), rank, iterations,
|
2014-11-08 01:53:01 -05:00
|
|
|
lambda_, blocks, nonnegative, seed)
|
2014-10-31 01:25:18 -04:00
|
|
|
return MatrixFactorizationModel(model)
|
2013-12-25 00:08:05 -05:00
|
|
|
|
|
|
|
@classmethod
|
2014-11-08 01:53:01 -05:00
|
|
|
def trainImplicit(cls, ratings, rank, iterations=5, lambda_=0.01, blocks=-1, alpha=0.01,
|
|
|
|
nonnegative=False, seed=None):
|
2014-10-31 01:25:18 -04:00
|
|
|
model = callMLlibFunc("trainImplicitALSModel", cls._prepare(ratings), rank,
|
2014-11-08 01:53:01 -05:00
|
|
|
iterations, lambda_, blocks, alpha, nonnegative, seed)
|
2014-10-31 01:25:18 -04:00
|
|
|
return MatrixFactorizationModel(model)
|
2013-12-25 00:08:05 -05:00
|
|
|
|
2014-05-25 20:15:01 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
def _test():
|
|
|
|
import doctest
|
2014-09-19 18:01:11 -04:00
|
|
|
import pyspark.mllib.recommendation
|
2015-04-21 19:44:52 -04:00
|
|
|
from pyspark.sql import SQLContext
|
2014-09-19 18:01:11 -04:00
|
|
|
globs = pyspark.mllib.recommendation.__dict__.copy()
|
2015-04-21 19:44:52 -04:00
|
|
|
sc = SparkContext('local[4]', 'PythonTest')
|
|
|
|
globs['sc'] = sc
|
|
|
|
globs['sqlContext'] = SQLContext(sc)
|
2014-05-25 20:15:01 -04:00
|
|
|
(failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS)
|
2013-12-25 00:08:05 -05:00
|
|
|
globs['sc'].stop()
|
|
|
|
if failure_count:
|
|
|
|
exit(-1)
|
|
|
|
|
2014-05-25 20:15:01 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
if __name__ == "__main__":
|
|
|
|
_test()
|