recommenderlab:构建基于R的推荐系统

recommenderlab:构建基于R的推荐系统(1)

http://site.douban.com/182577/widget/notes/10567212/note/345073868/

recommenderlab:构建基于R的推荐系统(1)

1.推荐系统和recommenderlab包

recommenderlab包提供了一个可以用评分数据和0-1数据来发展和测试推荐算法的框架。它提供了几种基础算法,并可利用注册机制允许用户使用自己的算法
recommender包的数据类型采用S4类构造,使用抽象的raringMatrix为评分数据提供接口。raringMatrix采用了很多类似矩阵对象的操作,如dim(),dimnames(),rowCounts(),colMeans(),rowMeans(),colSums(),rowMeans();也增加了一些特别的操作方法,如sample(),用于从用户(即,行)中抽样,image()可以生成像素图。raringMatrix的两种具体运用是realRatingMatrix和binaryRatingMatrix,分别对应评分矩阵的不同情况。其中realRatingMatrix使用的是真实值的评分矩阵,存储在由Matrix包定义的稀疏矩阵(spare matrix)格式中;binaryRatingMatrix使用的是0-1评分矩阵,存储在由arule包定义的itemMatrix中。

类Recommender使用数据结构来存储推荐模型。创建方法是:

Rencommender(data=ratingMatrix,method,parameter=NULL)

返回一个Rencommender对象object,可以用来做top-N推荐的预测:

predict(object,newdata,n,type=c('topNlist,ratings'),…)

使用者可以利用registry包提供的注册机制自定义自己的推荐算法。注册机制调用recommenderRegistry并存贮推荐算法的名字和简短描述。

为评价推荐算法的表现,recommender包提供了evaluationScheme类的对象用于创建并保存评价计划。创建函数如下: evaluatiomScheme(data,method,train,k,given) 这里的方法可以采用简单划分、自助法抽样、k-折交叉验证等。接下来可以使用函数evalute()使用评价计划的多个评价算法的表现。

下面用一个简单的人工例子来说明recommender包的数据结构和数据操作
m <- matrix(sample(c(as.numeric(0:5), NA), 30, replace = TRUE, prob = c(rep(0.5/6, 
    6), 0.5)), ncol = 6, dimnames = list(user = paste("u", 1:5, sep = ""), item = paste("i", 
    1:6, sep = "")))
m
## item
## user i1 i2 i3 i4 i5 i6
## u1 2 2 NA 0 NA NA
## u2 3 3 3 NA NA NA
## u3 NA 1 0 NA 0 1
## u4 NA 2 0 2 NA NA
## u5 NA NA NA NA 1 0
在这里所有没评分的值都是NA

把m转化为realRatingMatrix
library(recommenderlab)
m.real <- as(m, "realRatingMatrix")
m.real
## 5 x 6 rating matrix of class 'realRatingMatrix' with 15 ratings.
str(m.real)
## Formal class 'realRatingMatrix' [package "recommenderlab"] with 2 slots
## ..@ data :Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
## .. .. ..@ i : int [1:15] 0 1 0 1 2 3 1 2 3 0 ...
## .. .. ..@ p : int [1:7] 0 2 6 9 11 13 15
## .. .. ..@ Dim : int [1:2] 5 6
## .. .. ..@ Dimnames:List of 2
## .. .. .. ..$ user: chr [1:5] "u1" "u2" "u3" "u4" ...
## .. .. .. ..$ item: chr [1:6] "i1" "i2" "i3" "i4" ...
## .. .. ..@ x : num [1:15] 2 3 2 3 1 2 3 0 0 0 ...
## .. .. ..@ factors : list()
## ..@ normalize: NULL
(rating <- m.real@data)
## 5 x 6 sparse Matrix of class "dgCMatrix"
## item
## i1 i2 i3 i4 i5 i6
## u1 2 2 . 0 . .
## u2 3 3 3 . . .
## u3 . 1 0 . 0 1
## u4 . 2 0 2 . .
## u5 . . . . 1 0
# 和下面的命令是等价的
dropNA(m)
## 5 x 6 sparse Matrix of class "dgCMatrix"
## item
## i1 i2 i3 i4 i5 i6
## u1 2 2 . 0 . .
## u2 3 3 3 . . .
## u3 . 1 0 . 0 1
## u4 . 2 0 2 . .
## u5 . . . . 1 0
identical(rating, dropNA(m))
## [1] TRUE

# 转换回矩阵
as.matrix(rating)
## item
## user i1 i2 i3 i4 i5 i6
## u1 2 2 0 0 0 0
## u2 3 3 3 0 0 0
## u3 0 1 0 0 0 1
## u4 0 2 0 2 0 0
## u5 0 0 0 0 1 0
# NA没有了,这种转换是不合适的。需要这样做
as(m.real, "matrix")
## item
## user i1 i2 i3 i4 i5 i6
## u1 2 2 NA 0 NA NA
## u2 3 3 3 NA NA NA
## u3 NA 1 0 NA 0 1
## u4 NA 2 0 2 NA NA
## u5 NA NA NA NA 1 0

数据操作:
# 转化为列表
as(m.real, "list")
## $u1
## i1 i2 i4 
## 2 2 0 
## 
## $u2
## i1 i2 i3 
## 3 3 3 
## 
## $u3
## i2 i3 i5 i6 
## 1 0 0 1 
## 
## $u4
## i2 i3 i4 
## 2 0 2 
## 
## $u5
## i5 i6 
## 1 0
# 转化为数据框
head(as(m.real, "data.frame"))
## user item rating
## 1 u1 i1 2
## 3 u1 i2 2
## 10 u1 i4 0
## 2 u2 i1 3
## 4 u2 i2 3
## 7 u2 i3 3
# 标准化
n.real <- normalize(m.real)
# 标准化前后的比较,像素图
image(m.real, main = "Raw rating")

 

image(n.real, main = "Normalized rating")
 


2.协同过滤(Collaborative Flitering)方法

(1) 数据探索

协同过滤的基本思想是如果用户在过去有相同的偏好,那么在未来也会有相似的偏好,所以可以利用已知的用户过去的行为或评分对当前用户的喜好进行预测。 协同推荐技术一般分为基于记忆的和基于模型的。基于记忆的模型根据保存在内存中的原始评分数据直接生成推荐,常用的如基于物品的推荐(IBCF)和基于用户的推荐(UBCF)。

下面利用recommender包自带的数据集MovieLense,讨论基本的协同过滤推荐方法的使用。这个数据集收集了网站MovieLens(movielens.umn.edu)从1997年9月19日到1998年4月22日的数据,包括943名用户对1664部电影的评分。

首先利用可视化了解数据集的情况。
data(MovieLense)
# 可视化原始数据
image(MovieLense)
 

# 获取评分
ratings.movie <- data.frame(ratings = getRatings(MovieLense))
summary(ratings.movie$ratings)
## Min. 1st Qu. Median Mean 3rd Qu. Max. 
## 1.00 3.00 4.00 3.53 4.00 5.00
library(ggplot2)
ggplot(ratings.movie, aes(x = ratings)) + geom_histogram(fill = "beige", color = "black", 
    binwidth = 1, alpha = 0.7) + xlab("rating") + ylab("count")
 

# 标准化
ratings.movie1 <- data.frame(ratings = getRatings(normalize(MovieLense, method = "Z-score")))
summary(ratings.movie1$ratings)
## Min. 1st Qu. Median Mean 3rd Qu. Max. 
## -4.850 -0.647 0.108 0.000 0.751 4.130
ggplot(ratings.movie1, aes(x = ratings)) + geom_histogram(fill = "beige", color = "black", 
    alpha = 0.7) + xlab("rating") + ylab("count")
 

标准化的目的是为了去除用户评分的偏差

# 用户的电影点评数
movie.count <- data.frame(count = rowCounts(MovieLense))
ggplot(movie.count, aes(x = count)) + geom_histogram(fill = "beige", color = "black", 
    alpha = 0.7) + xlab("counts of users") + ylab("counts of movies rated")
 

用户存在长尾

# 电影的平均评分
rating.mean <- data.frame(rating = colMeans(MovieLense))
ggplot(rating.mean, aes(x = rating)) + geom_histogram(fill = "beige", color = "black", 
    alpha = 0.7) + xlab("rating") + ylab("counts of movies ")
 


(2)预测推荐

# 先看可以使用的方法
recommenderRegistry$get_entries(dataType = "realRatingMatrix")
## $IBCF_realRatingMatrix
## Recommender method: IBCF
## Description: Recommender based on item-based collaborative filtering (real data).
## Parameters:
## k method normalize normalize_sim_matrix alpha na_as_zero minRating
## 1 30 Cosine center FALSE 0.5 FALSE NA
## 
## $PCA_realRatingMatrix
## Recommender method: PCA
## Description: Recommender based on PCA approximation (real data).
## Parameters:
## categories method normalize normalize_sim_matrix alpha na_as_zero
## 1 20 Cosine center FALSE 0.5 FALSE
## minRating
## 1 NA
## 
## $POPULAR_realRatingMatrix
## Recommender method: POPULAR
## Description: Recommender based on item popularity (real data).
## Parameters: None
## 
## $RANDOM_realRatingMatrix
## Recommender method: RANDOM
## Description: Produce random recommendations (real ratings).
## Parameters: None
## 
## $SVD_realRatingMatrix
## Recommender method: SVD
## Description: Recommender based on SVD approximation (real data).
## Parameters:
## categories method normalize normalize_sim_matrix alpha treat_na
## 1 50 Cosine center FALSE 0.5 median
## minRating
## 1 NA
## 
## $UBCF_realRatingMatrix
## Recommender method: UBCF
## Description: Recommender based on user-based collaborative filtering (real data).
## Parameters:
## method nn sample normalize minRating
## 1 cosine 25 FALSE center NA
对于realRatingMatrix有六种方法:IBCF(基于物品的推荐)、UBCF(基于用户的推荐)、SVD(矩阵因子化)、PCA(主成分分析)、 RANDOM(随机推荐)、POPULAR(基于流行度的推荐)

利用前940位用户建立推荐模型
m.recomm <- Recommender(MovieLense[1:940], method = "IBCF")
m.recomm
## Recommender of type 'IBCF' for 'realRatingMatrix' 
## learned using 940 users.
对后三位用户进行推荐预测,使用predict()函数,默认是topN推荐,这里取n=3。预测后得到的一个topNList对象,可以把它转化为列表,看预测结果。

(ml.predict <- predict(m.recomm, MovieLense[941:943], n = 3))
## Recommendations as 'topNList' with n = 3 for 3 users.
str(ml.predict)
## Formal class 'topNList' [package "recommenderlab"] with 3 slots
## ..@ items :List of 3
## .. ..$ : int [1:3] 10 14 19
## .. ..$ : int [1:3] 3 39 47
## .. ..$ : int [1:3] 13 128 206
## ..@ itemLabels: chr [1:1664] "Toy Story (1995)" "GoldenEye (1995)" "Four Rooms (1995)" "Get Shorty (1995)" ...
## ..@ n : int 3
as(ml.predict, "list")#预测结果
## [1]
## [1] "Richard III (1995)" "Postino, Il (1994)" "Antonia's Line (1995)"
## 
## [2]
## [1] "Four Rooms (1995)" "Strange Days (1995)" "Ed Wood (1994)" 
## 
## [3]
## [1] "Mighty Aphrodite (1995)" "Supercop (1992)" 
## [3] "Akira (1988)"


recommenderlab:构建基于R的推荐系统(2)

3.评价推荐系统的表现

recommenderlab 包提供了函数 evaluationScheme()建立评价方案,能够使用简单划分、k折交叉验证、自助法进行模型的评价。下面采用简单划分的方法(split),即将数据集简单分为训练集和测试集,在训练集训练模型,然后在测试集上评价。 evaluationScheme()的主要参数:method,评估方法;train,划分为训练集的数据比例;k运行评估的折数或倍数(split的默认值为1);given表示用来进行模型评价的items的数量。

library(recommenderlab)
data(MovieLense)
scheme <- evaluationScheme(MovieLense, method = "split", train = 0.9, k = 1, 
    given = 10, goodRating = 4)
algorithms <- list(popular = list(name = "POPULAR", param = list(normalize = "Z-score")), 
    ubcf = list(name = "UBCF", param = list(normalize = "Z-score", method = "Cosine", 
        nn = 25, minRating = 3)), ibcf = list(name = "IBCF", param = list(normalize = "Z-score")))
results <- evaluate(scheme, algorithms, n = c(1, 3, 5, 10, 15, 20))
## POPULAR run 
## 1 [0.08sec/0.16sec] 
## UBCF run 
## 1 [0.09sec/4.96sec] 
## IBCF run 
## 1 [114.8sec/0.84sec]

recomenderlab包也提供了绘制表现图的方法,可以绘制ROC曲线和 precision-recall曲线

plot(results, annotate = 1:3, legend = "topleft") #ROC

 



plot(results, "prec/rec", annotate = 3)#precision-recall
 



用calcPredictionError()函数可以计算由用户精确评分给出的预测评分的MAE,MSE和RMSE这三种误差

# 按照评价方案建立推荐模型
model.popular <- Recommender(getData(scheme, "train"), method = "POPULAR")
model.ibcf <- Recommender(getData(scheme, "train"), method = "IBCF")
model.ubcf <- Recommender(getData(scheme, "train"), method = "UBCF")
# 对推荐模型进行预测
predict.popular <- predict(model.popular, getData(scheme, "known"), type = "ratings")
predict.ibcf <- predict(model.ibcf, getData(scheme, "known"), type = "ratings")
predict.ubcf <- predict(model.ubcf, getData(scheme, "known"), type = "ratings")
# 做误差的计算
predict.err <- rbind(calcPredictionError(predict.popular, getData(scheme, "unknown")), 
    calcPredictionError(predict.ubcf, getData(scheme, "unknown")), calcPredictionError(predict.ibcf, 
        getData(scheme, "unknown")))
rownames(predict.err) <- c("POPULAR, "UBCF", "IBCF")
predict.err
## MAE MSE RMSE
##POPULAR 3.5402 13.489 3.673
## UBCF 0.8051 1.062 1.030
## IBCF 0.8414 1.333 1.154

calcPredictionError()的参数“know”和“unknow”表示对测试集的进一步划分:“know”表示用户已经评分的,要用来预测的items;“unknow”表示用户已经评分,要被预测以便于进行模型评价的items。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值