spark的MLlib是其机器学习算法库。
其中协同过滤算法叫做ALS,交替最小二乘法。
下面对算法思路和执行代码进行分析。
算法思想:
1、对于用户、商品、评分构成的打分矩阵。一般来说是稀疏的矩阵,因为用户没有对所有商品打分,很多地方评分是未知数。
2、我们的目的是要将这个打分矩阵填满,从而预测用户对某个商品的打分,继而进行推荐。
3、计算这个原始矩阵的计算量是非常巨大的,而且没有必要。我们希望计算出其低秩矩阵,从而宏观上勾勒出用户和商品之间的关联关系,即相似度。
通过这个相似度,构成推荐系统的基本依据。
4、计算时,采用最小二乘法。
由于要优化的公式变量很多,我们采取固定其一,优化其他变量的方式寻求最优值的方式求解。所以较交替最小二乘法。
计算的最终结束标志是:公式中差的平方和小于预先设定的值,则认为找到最优解了。可以看出,这个最优解不一定是全局最优的。
java源码如下:
package sparkTest;
/*
* 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 O