pyspark.ml.recommendation.
ALS
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”,, 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.
New in version 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
Methods
clear(param)
clear
Clears a param from the param map if it has been explicitly set.
copy([extra])
copy
Creates a copy of this instance with the same uid and some extra params.
explainParam(param)
explainParam
Explains a single param and returns its name, doc, and optional default value and user-supplied value in a string.
explainParams()
explainParams
Returns the documentation of all params with their optionally default values and user-supplied values.
extractParamMap([extra])
extractParamMap
Extracts the embedded default param values and user-supplied values, and then merges them with extra values from input into a flat param map, where the latter value is used if there exist conflicts, i.e., with ordering: default param values < user-supplied values < extra.
fit(dataset[, params])
fit
Fits a model to the input dataset with optional parameters.
fitMultiple(dataset, paramMaps)
fitMultiple
Fits a model to the input dataset for each param map in paramMaps.
getAlpha()
getAlpha
Gets the value of alpha or its default value.
getBlockSize()
getBlockSize
Gets the value of blockSize or its default value.
getCheckpointInterval()
getCheckpointInterval
Gets the value of checkpointInterval or its default value.
getColdStartStrategy()
getColdStartStrategy
Gets the value of coldStartStrategy or its default value.
getFinalStorageLevel()
getFinalStorageLevel
Gets the value of finalStorageLevel or its default value.
getImplicitPrefs()
getImplicitPrefs
Gets the value of implicitPrefs or its default value.
getIntermediateStorageLevel()
getIntermediateStorageLevel
Gets the value of intermediateStorageLevel or its default value.
getItemCol()
getItemCol
Gets the value of itemCol or its default value.
getMaxIter()
getMaxIter
Gets the value of maxIter or its default value.
getNonnegative()
getNonnegative
Gets the value of nonnegative or its default value.
getNumItemBlocks()
getNumItemBlocks
Gets the value of numItemBlocks or its default value.
getNumUserBlocks()
getNumUserBlocks
Gets the value of numUserBlocks or its default value.
getOrDefault(param)
getOrDefault
Gets the value of a param in the user-supplied param map or its default value.
getParam(paramName)
getParam
Gets a param by its name.
getPredictionCol()
getPredictionCol
Gets the value of predictionCol or its default value.
getRank()
getRank
Gets the value of rank or its default value.
getRatingCol()
getRatingCol
Gets the value of ratingCol or its default value.
getRegParam()
getRegParam
Gets the value of regParam or its default value.
getSeed()
getSeed
Gets the value of seed or its default value.
getUserCol()
getUserCol
Gets the value of userCol or its default value.
hasDefault(param)
hasDefault
Checks whether a param has a default value.
hasParam(paramName)
hasParam
Tests whether this instance contains a param with a given (string) name.
isDefined(param)
isDefined
Checks whether a param is explicitly set by user or has a default value.
isSet(param)
isSet
Checks whether a param is explicitly set by user.
load(path)
load
Reads an ML instance from the input path, a shortcut of read().load(path).
read()
read
Returns an MLReader instance for this class.
save(path)
save
Save this ML instance to the given path, a shortcut of ‘write().save(path)’.
set(param, value)
set
Sets a parameter in the embedded param map.
setAlpha(value)
setAlpha
Sets the value of alpha.
alpha
setBlockSize(value)
setBlockSize
Sets the value of blockSize.
blockSize
setCheckpointInterval(value)
setCheckpointInterval
Sets the value of checkpointInterval.
checkpointInterval
setColdStartStrategy(value)
setColdStartStrategy
Sets the value of coldStartStrategy.
coldStartStrategy
setFinalStorageLevel(value)
setFinalStorageLevel
Sets the value of finalStorageLevel.
finalStorageLevel
setImplicitPrefs(value)
setImplicitPrefs
Sets the value of implicitPrefs.
implicitPrefs
setIntermediateStorageLevel(value)
setIntermediateStorageLevel
Sets the value of intermediateStorageLevel.
intermediateStorageLevel
setItemCol(value)
setItemCol
Sets the value of itemCol.
itemCol
setMaxIter(value)
setMaxIter
Sets the value of maxIter.
maxIter
setNonnegative(value)
setNonnegative
Sets the value of nonnegative.
nonnegative
setNumBlocks(value)
setNumBlocks
Sets both numUserBlocks and numItemBlocks to the specific value.
numUserBlocks
numItemBlocks
setNumItemBlocks(value)
setNumItemBlocks
Sets the value of numItemBlocks.
setNumUserBlocks(value)
setNumUserBlocks
Sets the value of numUserBlocks.
setParams(self, \*[, rank, maxIter, …])
setParams
Sets params for ALS.
setPredictionCol(value)
setPredictionCol
Sets the value of predictionCol.
predictionCol
setRank(value)
setRank
Sets the value of rank.
rank
setRatingCol(value)
setRatingCol
Sets the value of ratingCol.
ratingCol
setRegParam(value)
setRegParam
Sets the value of regParam.
regParam
setSeed(value)
setSeed
Sets the value of seed.
seed
setUserCol(value)
setUserCol
Sets the value of userCol.
userCol
write()
write
Returns an MLWriter instance for this ML instance.
Attributes
params
Returns all params ordered by name.
Methods Documentation
Creates a copy of this instance with the same uid and some extra params. This implementation first calls Params.copy and then make a copy of the companion Java pipeline component with extra params. So both the Python wrapper and the Java pipeline component get copied.
Extra parameters to copy to the new instance
JavaParams
Copy of this instance
extra param values
merged param map
New in version 1.3.0.
pyspark.sql.DataFrame
input dataset.
an optional param map that overrides embedded params. If a list/tuple of param maps is given, this calls fit on each param map and returns a list of models.
Transformer
fitted model(s)
New in version 2.3.0.
collections.abc.Sequence
A Sequence of param maps.
_FitMultipleIterator
A thread safe iterable which contains one model for each param map. Each call to next(modelIterator) will return (index, model) where model was fit using paramMaps[index]. index values may not be sequential.
New in version 2.2.0.
New in version 2.0.0.
Gets the value of a param in the user-supplied param map or its default value. Raises an error if neither is set.
New in version 3.0.0.
Attributes Documentation
Returns all params ordered by name. The default implementation uses dir() to get all attributes of type Param.
dir()
Param