Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# # 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. #
HasCheckpointInterval, HasSeed
""" Params for :py:class:`ALS` and :py:class:`ALSModel`.
.. versionadded:: 3.0.0 """
"the integer value range.", typeConverter=TypeConverters.toString) "the integer value range.", typeConverter=TypeConverters.toString) "unknown or new users/items at prediction time. This may be useful " + "in cross-validation or production scenarios, for handling " + "user/item ids the model has not seen in the training data. " + "Supported values: 'nan', 'drop'.", typeConverter=TypeConverters.toString)
def getUserCol(self): """ Gets the value of userCol or its default value. """
def getItemCol(self): """ Gets the value of itemCol or its default value. """
def getColdStartStrategy(self): """ Gets the value of coldStartStrategy or its default value. """ return self.getOrDefault(self.coldStartStrategy)
""" Params for :py:class:`ALS`.
.. versionadded:: 3.0.0 """
typeConverter=TypeConverters.toInt) typeConverter=TypeConverters.toInt) typeConverter=TypeConverters.toInt) typeConverter=TypeConverters.toBoolean) typeConverter=TypeConverters.toFloat)
typeConverter=TypeConverters.toString) "whether to use nonnegative constraint for least squares", typeConverter=TypeConverters.toBoolean) "StorageLevel for intermediate datasets. Cannot be 'NONE'.", typeConverter=TypeConverters.toString) "StorageLevel for ALS model factors.", typeConverter=TypeConverters.toString)
implicitPrefs=False, alpha=1.0, userCol="user", itemCol="item", ratingCol="rating", nonnegative=False, checkpointInterval=10, intermediateStorageLevel="MEMORY_AND_DISK", finalStorageLevel="MEMORY_AND_DISK", coldStartStrategy="nan")
def getRank(self): """ Gets the value of rank or its default value. """ return self.getOrDefault(self.rank)
def getNumUserBlocks(self): """ Gets the value of numUserBlocks or its default value. """ return self.getOrDefault(self.numUserBlocks)
def getNumItemBlocks(self): """ Gets the value of numItemBlocks or its default value. """ return self.getOrDefault(self.numItemBlocks)
def getImplicitPrefs(self): """ Gets the value of implicitPrefs or its default value. """ return self.getOrDefault(self.implicitPrefs)
def getAlpha(self): """ Gets the value of alpha or its default value. """ return self.getOrDefault(self.alpha)
def getRatingCol(self): """ Gets the value of ratingCol or its default value. """ return self.getOrDefault(self.ratingCol)
def getNonnegative(self): """ Gets the value of nonnegative or its default value. """ return self.getOrDefault(self.nonnegative)
def getIntermediateStorageLevel(self): """ Gets the value of intermediateStorageLevel or its default value. """
def getFinalStorageLevel(self): """ Gets the value of finalStorageLevel or its default value. """
""" Alternating Least Squares (ALS) matrix factorization.
ALS attempts to estimate the ratings matrix `R` as the product of two lower-rank matrices, `X` and `Y`, i.e. `X * Yt = R`. Typically these approximations are called 'factor' matrices. The general approach is iterative. During each iteration, one of the factor matrices is held constant, while the other is solved for using least squares. The newly-solved factor matrix is then held constant while solving for the other factor matrix.
This is a blocked implementation of the ALS factorization algorithm that groups the two sets of factors (referred to as "users" and "products") into blocks and reduces communication by only sending one copy of each user vector to each product block on each iteration, and only for the product blocks that need that user's feature vector. This is achieved by pre-computing some information about the ratings matrix to determine the "out-links" of each user (which blocks of products it will contribute to) and "in-link" information for each product (which of the feature vectors it receives from each user block it will depend on). This allows us to send only an array of feature vectors between each user block and product block, and have the product block find the users' ratings and update the products based on these messages.
For implicit preference data, the algorithm used is based on `"Collaborative Filtering for Implicit Feedback Datasets", <https://doi.org/10.1109/ICDM.2008.22>`_, adapted for the blocked approach used here.
Essentially instead of finding the low-rank approximations to the rating matrix `R`, this finds the approximations for a preference matrix `P` where the elements of `P` are 1 if r > 0 and 0 if r <= 0. The ratings then act as 'confidence' values related to strength of indicated user preferences rather than explicit ratings given to items.
.. versionadded:: 1.4.0
Notes ----- The input rating dataframe to the ALS implementation should be deterministic. Nondeterministic data can cause failure during fitting ALS model. For example, an order-sensitive operation like sampling after a repartition makes dataframe output nondeterministic, like `df.repartition(2).sample(False, 0.5, 1618)`. Checkpointing sampled dataframe or adding a sort before sampling can help make the dataframe deterministic.
Examples -------- >>> df = spark.createDataFrame( ... [(0, 0, 4.0), (0, 1, 2.0), (1, 1, 3.0), (1, 2, 4.0), (2, 1, 1.0), (2, 2, 5.0)], ... ["user", "item", "rating"]) >>> als = ALS(rank=10, seed=0) >>> als.setMaxIter(5) ALS... >>> als.getMaxIter() 5 >>> als.setRegParam(0.1) ALS... >>> als.getRegParam() 0.1 >>> als.clear(als.regParam) >>> model = als.fit(df) >>> model.getBlockSize() 4096 >>> model.getUserCol() 'user' >>> model.setUserCol("user") ALSModel... >>> model.getItemCol() 'item' >>> model.setPredictionCol("newPrediction") ALS... >>> model.rank 10 >>> model.userFactors.orderBy("id").collect() [Row(id=0, features=[...]), Row(id=1, ...), Row(id=2, ...)] >>> test = spark.createDataFrame([(0, 2), (1, 0), (2, 0)], ["user", "item"]) >>> predictions = sorted(model.transform(test).collect(), key=lambda r: r[0]) >>> predictions[0] Row(user=0, item=2, newPrediction=0.69291...) >>> predictions[1] Row(user=1, item=0, newPrediction=3.47356...) >>> predictions[2] Row(user=2, item=0, newPrediction=-0.899198...) >>> user_recs = model.recommendForAllUsers(3) >>> user_recs.where(user_recs.user == 0)\ .select("recommendations.item", "recommendations.rating").collect() [Row(item=[0, 1, 2], rating=[3.910..., 1.997..., 0.692...])] >>> item_recs = model.recommendForAllItems(3) >>> item_recs.where(item_recs.item == 2)\ .select("recommendations.user", "recommendations.rating").collect() [Row(user=[2, 1, 0], rating=[4.892..., 3.991..., 0.692...])] >>> user_subset = df.where(df.user == 2) >>> user_subset_recs = model.recommendForUserSubset(user_subset, 3) >>> user_subset_recs.select("recommendations.item", "recommendations.rating").first() Row(item=[2, 1, 0], rating=[4.892..., 1.076..., -0.899...]) >>> item_subset = df.where(df.item == 0) >>> item_subset_recs = model.recommendForItemSubset(item_subset, 3) >>> item_subset_recs.select("recommendations.user", "recommendations.rating").first() Row(user=[0, 1, 2], rating=[3.910..., 3.473..., -0.899...]) >>> als_path = temp_path + "/als" >>> als.save(als_path) >>> als2 = ALS.load(als_path) >>> als.getMaxIter() 5 >>> model_path = temp_path + "/als_model" >>> model.save(model_path) >>> model2 = ALSModel.load(model_path) >>> model.rank == model2.rank True >>> sorted(model.userFactors.collect()) == sorted(model2.userFactors.collect()) True >>> sorted(model.itemFactors.collect()) == sorted(model2.itemFactors.collect()) True >>> model.transform(test).take(1) == model2.transform(test).take(1) True """
numItemBlocks=10, implicitPrefs=False, alpha=1.0, userCol="user", itemCol="item", seed=None, ratingCol="rating", nonnegative=False, checkpointInterval=10, intermediateStorageLevel="MEMORY_AND_DISK", finalStorageLevel="MEMORY_AND_DISK", coldStartStrategy="nan", blockSize=4096): """ __init__(self, \\*, rank=10, maxIter=10, regParam=0.1, numUserBlocks=10, numItemBlocks=10, implicitPrefs=False, alpha=1.0, userCol="user", itemCol="item", \ seed=None, ratingCol="rating", nonnegative=False, checkpointInterval=10, \ intermediateStorageLevel="MEMORY_AND_DISK", \ finalStorageLevel="MEMORY_AND_DISK", coldStartStrategy="nan", blockSize=4096) """
numItemBlocks=10, implicitPrefs=False, alpha=1.0, userCol="user", itemCol="item", seed=None, ratingCol="rating", nonnegative=False, checkpointInterval=10, intermediateStorageLevel="MEMORY_AND_DISK", finalStorageLevel="MEMORY_AND_DISK", coldStartStrategy="nan", blockSize=4096): """ setParams(self, \\*, rank=10, maxIter=10, regParam=0.1, numUserBlocks=10, \ numItemBlocks=10, implicitPrefs=False, alpha=1.0, userCol="user", itemCol="item", \ seed=None, ratingCol="rating", nonnegative=False, checkpointInterval=10, \ intermediateStorageLevel="MEMORY_AND_DISK", \ finalStorageLevel="MEMORY_AND_DISK", coldStartStrategy="nan", blockSize=4096) Sets params for ALS. """
def setRank(self, value): """ Sets the value of :py:attr:`rank`. """
def setNumUserBlocks(self, value): """ Sets the value of :py:attr:`numUserBlocks`. """ return self._set(numUserBlocks=value)
def setNumItemBlocks(self, value): """ Sets the value of :py:attr:`numItemBlocks`. """ return self._set(numItemBlocks=value)
def setNumBlocks(self, value): """ Sets both :py:attr:`numUserBlocks` and :py:attr:`numItemBlocks` to the specific value. """ self._set(numUserBlocks=value) return self._set(numItemBlocks=value)
def setImplicitPrefs(self, value): """ Sets the value of :py:attr:`implicitPrefs`. """ return self._set(implicitPrefs=value)
def setAlpha(self, value): """ Sets the value of :py:attr:`alpha`. """ return self._set(alpha=value)
def setUserCol(self, value): """ Sets the value of :py:attr:`userCol`. """ return self._set(userCol=value)
def setItemCol(self, value): """ Sets the value of :py:attr:`itemCol`. """ return self._set(itemCol=value)
def setRatingCol(self, value): """ Sets the value of :py:attr:`ratingCol`. """ return self._set(ratingCol=value)
def setNonnegative(self, value): """ Sets the value of :py:attr:`nonnegative`. """ return self._set(nonnegative=value)
def setIntermediateStorageLevel(self, value): """ Sets the value of :py:attr:`intermediateStorageLevel`. """
def setFinalStorageLevel(self, value): """ Sets the value of :py:attr:`finalStorageLevel`. """
def setColdStartStrategy(self, value): """ Sets the value of :py:attr:`coldStartStrategy`. """ return self._set(coldStartStrategy=value)
""" Sets the value of :py:attr:`maxIter`. """
""" Sets the value of :py:attr:`regParam`. """
""" Sets the value of :py:attr:`predictionCol`. """ return self._set(predictionCol=value)
""" Sets the value of :py:attr:`checkpointInterval`. """ return self._set(checkpointInterval=value)
""" Sets the value of :py:attr:`seed`. """ return self._set(seed=value)
def setBlockSize(self, value): """ Sets the value of :py:attr:`blockSize`. """ return self._set(blockSize=value)
""" Model fitted by ALS.
.. versionadded:: 1.4.0 """
def setUserCol(self, value): """ Sets the value of :py:attr:`userCol`. """
def setItemCol(self, value): """ Sets the value of :py:attr:`itemCol`. """ return self._set(itemCol=value)
def setColdStartStrategy(self, value): """ Sets the value of :py:attr:`coldStartStrategy`. """ return self._set(coldStartStrategy=value)
def setPredictionCol(self, value): """ Sets the value of :py:attr:`predictionCol`. """
def setBlockSize(self, value): """ Sets the value of :py:attr:`blockSize`. """ return self._set(blockSize=value)
def rank(self): """rank of the matrix factorization model"""
def userFactors(self): """ a DataFrame that stores user factors in two columns: `id` and `features` """
def itemFactors(self): """ a DataFrame that stores item factors in two columns: `id` and `features` """
""" Returns top `numItems` items recommended for each user, for all users.
.. versionadded:: 2.2.0
Parameters ---------- numItems : int max number of recommendations for each user
Returns ------- :py:class:`pyspark.sql.DataFrame` a DataFrame of (userCol, recommendations), where recommendations are stored as an array of (itemCol, rating) Rows. """
""" Returns top `numUsers` users recommended for each item, for all items.
.. versionadded:: 2.2.0
Parameters ---------- numUsers : int max number of recommendations for each item
Returns ------- :py:class:`pyspark.sql.DataFrame` a DataFrame of (itemCol, recommendations), where recommendations are stored as an array of (userCol, rating) Rows. """
""" Returns top `numItems` items recommended for each user id in the input data set. Note that if there are duplicate ids in the input dataset, only one set of recommendations per unique id will be returned.
.. versionadded:: 2.3.0
Parameters ---------- dataset : :py:class:`pyspark.sql.DataFrame` a DataFrame containing a column of user ids. The column name must match `userCol`. numItems : int max number of recommendations for each user
Returns ------- :py:class:`pyspark.sql.DataFrame` a DataFrame of (userCol, recommendations), where recommendations are stored as an array of (itemCol, rating) Rows. """
""" Returns top `numUsers` users recommended for each item id in the input data set. Note that if there are duplicate ids in the input dataset, only one set of recommendations per unique id will be returned.
.. versionadded:: 2.3.0
Parameters ---------- dataset : :py:class:`pyspark.sql.DataFrame` a DataFrame containing a column of item ids. The column name must match `itemCol`. numUsers : int max number of recommendations for each item
Returns ------- :py:class:`pyspark.sql.DataFrame` a DataFrame of (itemCol, recommendations), where recommendations are stored as an array of (userCol, rating) Rows. """
# The small batch size here ensures that we see multiple batches, # even in these small test examples: .master("local[2]")\ .appName("ml.recommendation tests")\ .getOrCreate() finally: except OSError: pass sys.exit(-1) |