协同过滤算法

来源:互联网 发布:facebook 批量操作软件 编辑:程序博客网 时间:2024/06/03 21:23

    • 简介
    • 原理
      • 低秩矩阵
      • 最小二乘法
    • Python实现
      • 参数
      • 实现

简介

协同过滤算法常用语推荐系统中,旨在填补用户项目关联矩阵的缺失条目,spark.mllib目前支持基于模型的协同过滤,其中用户和产品由一小组潜在因素描述,可用于预测缺失的条目。spark.mllib使用交替最小二乘法(ALS)算法来学习这些潜在因素。

原理

(先占位,等我这两天搞懂了就填上)

低秩矩阵

最小二乘法

Python实现

参数

参数 含义 numBlocks 用于并行计算的块数(设置为-1为自动配置)。 rank 要使用的特征的数量(也称为潜在因素的数量)。 iterations 运行ALS的迭代次数。 ALS通常在20次迭代或更少次收敛到合理的解决方案。 lambda 在ALS中指定正则化参数。 implicitPrefs 指定是使用显式反馈ALS变体还是适用于隐式反馈数据。 alpha 适用于控制偏好观测的基线置信度的ALS的隐式反馈变体的参数。

实现

from __future__ import print_functionfrom pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Ratingfrom pyspark import SparkContextsc = SparkContext(appName="ALS_Example")# Load and parse the datadata = sc.textFile("test.data")ratings = data.map(lambda l: l.split(','))\    .map(lambda l: Rating(int(l[0]), int(l[1]), float(l[2])))print("ratings:")print(ratings.collect())print("===============")# Build the recommendation model using Alternating Least Squaresrank = 10numIterations = 10model = ALS.train(ratings, rank, numIterations)# Evaluate the model on traing data# testdata = ratings.map(lambda p: (p[0], p[1]))testdata = sc.parallelize([(4, 4), (1, 1), (3, 4)])print("testdata:")print(testdata.collect())print("================")#predictions = model.predictAll(testdata).map(lambda r: ((r[0], r[1]), r[2]))print("predictions:")print(predictions.collect())print("================")ratesAndPreds = ratings.map(lambda r: ((r[0], r[1]), r[2])).join(predictions)print("ratesAndPreds:")print(ratesAndPreds.collect())print("================")MSE = ratesAndPreds.map(lambda r: (r[1][0] - r[1][1]) **2).mean()print("Mean Squared Error = " + str(MSE))
原创粉丝点击