R语言实战实现基于用户的简单的推荐系统,数量较少

R语言实战实现基于用户的简单的推荐系统(数量较少)

a<-c(1,1,1,1,2,2,2,2,3,3,3,4,4,4,5,5,5,5,6,6,7,7)

b<-c(1,2,3,4,2,3,4,5,4,1,2,3,2,4,5,2,6,4,1,2,3,4)

da<-data.frame(a,b)

a<-c(1,1,2,2,3,3,3,3,3,4,4,5,5,5,6,6,7,7)

b<-c(2,5,7,2,6,4,7,1,8,6,3,3,4,1,2,4,4,9)

da2<-data.frame(a,b)

ax<-unique(da$a)

bx<-unique(da$b)

m<-matrix(0,max(ax),max(ax))

for(i in 1:max(ax))

{

for(j in 1:max(ax))

{

if(i==j)

{

m[i,j]=0

}else{

m[i,j]=length(intersect(t(da[which(da$a==i),][2]),t(da[which(da$a==j),][2])))

}

}

}

m

myfun<-function(da,k,da2,m)

{

uid<-unique(c)

pre=0

recall=0

for (mm in 1:max(uid))

{

aa<-which(rank(-m[mm,])<k)

bb<-unique(da[unlist(lapply(da$a,function(x){

length(intersect(x,aa))!=0

})),][2])

movie<-setdiff(t(bb),t((da[which(da$a==mm),][2])))

movie2<-t(da2[da2$a==mm,][2])

p<-length(intersect(movie,movie2))/length(movie)

r<-length(intersect(movie,movie2))/length(movie2)

pre<-pre+p

recall<-recall+r

if(mm==1)

{

user_top1<-which(rank(-m[mm,])<k)

movie_top2<-sort(movie[rank(movie)<k])

print(user_top1)

print(movie_top2)

}

}

preA<-pre/length(uid);

recallA<-recall/length(uid);

dataframe<-data.frame(c(k),preA,recallA)

return(dataframe)

}

df<-myfun(da,4,da2,m);

preA<-c()

recallA<-c()

k<-c()

daa<-data.frame(k,preA,recallA)

for(i in 3:7)

{

df<-myfun(da,i,da2,m);

daa<-rbind(daa,df)

}

daa

library(ggplot2)

qplot(preA,recallA,data=daa ,geom = c("point", "smooth"))

preA<-c()recallA<-c()k<-c()daa<-data.frame(k,preA,recallA)