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
|
2018-03-08 06:38:34 -05:00
|
|
|
import sys
|
[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
|
|
|
|
|
2015-09-16 07:34:14 -04:00
|
|
|
from pyspark import SparkContext, since
|
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
|
|
|
|
2020-11-24 20:24:41 -05:00
|
|
|
.. versionadded:: 1.2.0
|
|
|
|
|
|
|
|
Examples
|
|
|
|
--------
|
[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.
|
|
|
|
|
2020-11-24 20:24:41 -05:00
|
|
|
.. versionadded:: 0.9.0
|
|
|
|
|
|
|
|
Examples
|
|
|
|
--------
|
2013-12-25 00:08:05 -05:00
|
|
|
>>> 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]
|
2015-10-09 17:16:13 -04:00
|
|
|
>>> len(latents)
|
|
|
|
4
|
2014-10-21 14:49:39 -04:00
|
|
|
|
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]
|
2015-10-09 17:16:13 -04:00
|
|
|
>>> len(latents)
|
|
|
|
4
|
|
|
|
|
|
|
|
>>> products_for_users = model.recommendProductsForUsers(1).collect()
|
|
|
|
>>> len(products_for_users)
|
|
|
|
2
|
|
|
|
>>> products_for_users[0]
|
|
|
|
(1, (Rating(user=1, product=2, rating=...),))
|
|
|
|
|
|
|
|
>>> users_for_products = model.recommendUsersForProducts(1).collect()
|
|
|
|
>>> len(users_for_products)
|
|
|
|
2
|
|
|
|
>>> users_for_products[0]
|
|
|
|
(1, (Rating(user=2, product=1, rating=...),))
|
2014-11-08 01:53:01 -05:00
|
|
|
|
2019-03-23 12:26:09 -04:00
|
|
|
>>> model = ALS.train(ratings, 1, nonnegative=True, seed=123456789)
|
2015-04-21 19:44:52 -04:00
|
|
|
>>> model.predict(2, 2)
|
2015-11-06 15:06:24 -05:00
|
|
|
3.73...
|
2015-04-21 19:44:52 -04:00
|
|
|
|
|
|
|
>>> df = sqlContext.createDataFrame([Rating(1, 1, 1.0), Rating(1, 2, 2.0), Rating(2, 1, 2.0)])
|
2019-03-23 12:26:09 -04:00
|
|
|
>>> model = ALS.train(df, 1, nonnegative=True, seed=123456789)
|
2015-04-21 19:44:52 -04:00
|
|
|
>>> model.predict(2, 2)
|
2015-11-06 15:06:24 -05:00
|
|
|
3.73...
|
2014-11-08 01:53:01 -05:00
|
|
|
|
2019-03-23 12:26:09 -04:00
|
|
|
>>> model = ALS.trainImplicit(ratings, 1, nonnegative=True, seed=123456789)
|
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-06-22 14:53:11 -04:00
|
|
|
>>> from shutil import rmtree
|
2015-03-01 19:26:57 -05:00
|
|
|
>>> try:
|
2015-06-22 14:53:11 -04:00
|
|
|
... rmtree(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
|
|
|
"""
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("0.9.0")
|
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
|
|
|
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("0.9.0")
|
2014-09-19 18:01:11 -04:00
|
|
|
def predictAll(self, user_product):
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
Returns a list of predicted ratings for input user and product
|
|
|
|
pairs.
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
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
|
|
|
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("1.2.0")
|
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
|
|
|
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("1.2.0")
|
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-09-16 07:34:14 -04:00
|
|
|
@since("1.4.0")
|
2015-05-01 02:51:00 -04:00
|
|
|
def recommendUsers(self, product, num):
|
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
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.
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
|
|
|
return list(self.call("recommendUsers", product, num))
|
|
|
|
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("1.4.0")
|
2015-05-01 02:51:00 -04:00
|
|
|
def recommendProducts(self, user, num):
|
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
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.
|
2015-05-01 02:51:00 -04:00
|
|
|
"""
|
|
|
|
return list(self.call("recommendProducts", user, num))
|
|
|
|
|
2015-10-09 17:16:13 -04:00
|
|
|
def recommendProductsForUsers(self, num):
|
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
Recommends the top "num" number of products for all users. The
|
|
|
|
number of recommendations returned per user may be less than "num".
|
2015-10-09 17:16:13 -04:00
|
|
|
"""
|
|
|
|
return self.call("wrappedRecommendProductsForUsers", num)
|
|
|
|
|
|
|
|
def recommendUsersForProducts(self, num):
|
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
Recommends the top "num" number of users for all products. The
|
|
|
|
number of recommendations returned per product may be less than
|
|
|
|
"num".
|
2015-10-09 17:16:13 -04:00
|
|
|
"""
|
|
|
|
return self.call("wrappedRecommendUsersForProducts", num)
|
|
|
|
|
2015-05-01 02:51:00 -04:00
|
|
|
@property
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("1.4.0")
|
2015-05-01 02:51:00 -04:00
|
|
|
def rank(self):
|
2015-09-16 07:34:14 -04:00
|
|
|
"""Rank for the features in this model"""
|
2015-05-01 02:51:00 -04:00
|
|
|
return self.call("rank")
|
|
|
|
|
2015-03-28 18:08:05 -04:00
|
|
|
@classmethod
|
2015-09-16 07:34:14 -04:00
|
|
|
@since("1.3.1")
|
2015-03-28 18:08:05 -04:00
|
|
|
def load(cls, sc, path):
|
2015-09-16 07:34:14 -04:00
|
|
|
"""Load a model from the given path"""
|
2015-03-28 18:08:05 -04:00
|
|
|
model = cls._load_java(sc, path)
|
2016-07-05 20:00:24 -04:00
|
|
|
wrapper = sc._jvm.org.apache.spark.mllib.api.python.MatrixFactorizationModelWrapper(model)
|
2015-03-28 18:08:05 -04:00
|
|
|
return MatrixFactorizationModel(wrapper)
|
|
|
|
|
2014-05-25 20:15:01 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
class ALS(object):
|
2015-09-16 07:34:14 -04:00
|
|
|
"""Alternating Least Squares matrix factorization
|
|
|
|
|
|
|
|
.. versionadded:: 0.9.0
|
|
|
|
"""
|
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):
|
2015-09-16 07:34:14 -04:00
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
Train a matrix factorization model given an RDD of ratings by users
|
|
|
|
for a subset of products. The ratings matrix is approximated as the
|
|
|
|
product of two lower-rank matrices of a given rank (number of
|
|
|
|
features). To solve for these features, ALS is run iteratively with
|
|
|
|
a configurable level of parallelism.
|
|
|
|
|
2020-11-24 20:24:41 -05:00
|
|
|
.. versionadded:: 0.9.0
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
ratings : :py:class:`pyspark.RDD`
|
|
|
|
RDD of `Rating` or (userID, productID, rating) tuple.
|
|
|
|
rank : int
|
|
|
|
Number of features to use (also referred to as the number of latent factors).
|
|
|
|
iterations : int, optional
|
|
|
|
Number of iterations of ALS.
|
|
|
|
(default: 5)
|
|
|
|
lambda\\_ : float, optional
|
|
|
|
Regularization parameter.
|
|
|
|
(default: 0.01)
|
|
|
|
blocks : int, optional
|
|
|
|
Number of blocks used to parallelize the computation. A value
|
|
|
|
of -1 will use an auto-configured number of blocks.
|
|
|
|
(default: -1)
|
|
|
|
nonnegative : bool, optional
|
|
|
|
A value of True will solve least-squares with nonnegativity
|
|
|
|
constraints.
|
|
|
|
(default: False)
|
|
|
|
seed : bool, optional
|
|
|
|
Random seed for initial matrix factorization model. A value
|
|
|
|
of None will use system time as the seed.
|
|
|
|
(default: None)
|
2015-09-16 07:34:14 -04:00
|
|
|
"""
|
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):
|
2015-09-16 07:34:14 -04:00
|
|
|
"""
|
2016-02-22 05:48:37 -05:00
|
|
|
Train a matrix factorization model given an RDD of 'implicit
|
|
|
|
preferences' of users for a subset of products. The ratings matrix
|
|
|
|
is approximated as the product of two lower-rank matrices of a
|
|
|
|
given rank (number of features). To solve for these features, ALS
|
|
|
|
is run iteratively with a configurable level of parallelism.
|
|
|
|
|
2020-11-24 20:24:41 -05:00
|
|
|
.. versionadded:: 0.9.0
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
ratings : :py:class:`pyspark.RDD`
|
|
|
|
RDD of `Rating` or (userID, productID, rating) tuple.
|
|
|
|
rank : int
|
|
|
|
Number of features to use (also referred to as the number of latent factors).
|
|
|
|
iterations : int, optional
|
|
|
|
Number of iterations of ALS.
|
|
|
|
(default: 5)
|
|
|
|
lambda\\_ : float, optional
|
|
|
|
Regularization parameter.
|
|
|
|
(default: 0.01)
|
|
|
|
blocks : int, optional
|
|
|
|
Number of blocks used to parallelize the computation. A value
|
|
|
|
of -1 will use an auto-configured number of blocks.
|
|
|
|
(default: -1)
|
|
|
|
alpha : float, optional
|
|
|
|
A constant used in computing confidence.
|
|
|
|
(default: 0.01)
|
|
|
|
nonnegative : bool, optional
|
|
|
|
A value of True will solve least-squares with nonnegativity
|
|
|
|
constraints.
|
|
|
|
(default: False)
|
|
|
|
seed : int, optional
|
|
|
|
Random seed for initial matrix factorization model. A value
|
|
|
|
of None will use system time as the seed.
|
|
|
|
(default: None)
|
2015-09-16 07:34:14 -04:00
|
|
|
"""
|
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:
|
2018-03-08 06:38:34 -05:00
|
|
|
sys.exit(-1)
|
2013-12-25 00:08:05 -05:00
|
|
|
|
2014-05-25 20:15:01 -04:00
|
|
|
|
2013-12-25 00:08:05 -05:00
|
|
|
if __name__ == "__main__":
|
|
|
|
_test()
|