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.
|
|
|
|
#
|
|
|
|
|
[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
|
2014-10-31 01:25:18 -04:00
|
|
|
from pyspark.mllib.common import JavaModelWrapper, callMLlibFunc, _to_java_object_rdd
|
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
|
|
|
|
|
|
|
|
2014-10-31 01:25:18 -04:00
|
|
|
class MatrixFactorizationModel(JavaModelWrapper):
|
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)
|
|
|
|
>>> model.predict(2,2)
|
|
|
|
0.4473...
|
2014-09-19 18:01:11 -04:00
|
|
|
|
2014-01-06 15:19:43 -05:00
|
|
|
>>> testset = sc.parallelize([(1, 2), (1, 1)])
|
2014-11-08 01:53:01 -05:00
|
|
|
>>> model = ALS.train(ratings, 1, seed=10)
|
|
|
|
>>> model.predictAll(testset).collect()
|
[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
|
|
|
[Rating(user=1, product=1, rating=1.0471...), Rating(user=1, product=2, rating=1.9679...)]
|
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()
|
|
|
|
[(2, array('d', [...])), (1, array('d', [...]))]
|
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()
|
|
|
|
[(2, array('d', [...])), (1, 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)
|
|
|
|
>>> model.predict(2,2)
|
|
|
|
3.735...
|
|
|
|
|
|
|
|
>>> model = ALS.trainImplicit(ratings, 1, nonnegative=True, seed=10)
|
|
|
|
>>> model.predict(2,2)
|
|
|
|
0.4473...
|
2013-12-25 00:08:05 -05:00
|
|
|
"""
|
|
|
|
def predict(self, user, 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):
|
|
|
|
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)"
|
|
|
|
user_product = user_product.map(lambda (u, p): (int(u), int(p)))
|
|
|
|
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):
|
2014-10-31 01:25:18 -04:00
|
|
|
return self.call("getUserFeatures")
|
2014-10-21 14:49:39 -04:00
|
|
|
|
|
|
|
def productFeatures(self):
|
2014-10-31 01:25:18 -04:00
|
|
|
return self.call("getProductFeatures")
|
2014-10-21 14:49:39 -04:00
|
|
|
|
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):
|
|
|
|
assert isinstance(ratings, RDD), "ratings should be RDD"
|
|
|
|
first = ratings.first()
|
|
|
|
if not isinstance(first, Rating):
|
|
|
|
if isinstance(first, (tuple, list)):
|
|
|
|
ratings = ratings.map(lambda x: Rating(*x))
|
|
|
|
else:
|
|
|
|
raise ValueError("rating should be RDD of Rating or tuple/list")
|
2014-10-31 01:25:18 -04:00
|
|
|
return _to_java_object_rdd(ratings, True)
|
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
|
|
|
|
globs = pyspark.mllib.recommendation.__dict__.copy()
|
2014-11-04 02:56:14 -05:00
|
|
|
globs['sc'] = SparkContext('local[4]', 'PythonTest')
|
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()
|