转自:用户推荐系统_python 代码-豆瓣
书籍:项亮的<推荐系统实践>

import random
import math class UserBasedCF:
def __init__(self,train = None,test = None):
self.trainfile = train
self.testfile = test
self.readData() def readData(self,train = None,test = None):
self.trainfile = train or self.trainfile
self.testfile = test or self.testfile
self.traindata = {}
self.testdata = {}
for line in open(self.trainfile):
userid,itemid,record,_ = line.split()
self.traindata.setdefault(userid,{})
self.traindata[userid][itemid]=record
for line in open(self.testfile):
userid,itemid,record,_ = line.split()
self.testdata.setdefault(userid,{})
self.testdata[userid][itemid]=record def userSimilarityBest(self,train = None):
train = train or self.traindata
self.userSimBest = dict()
item_users = dict()
for u,item in train.items():
for i in item.keys():
item_users.setdefault(i,set())
item_users[i].add(u)
user_item_count = dict()
count = dict()
for item,users in item_users.items():
for u in users:
user_item_count.setdefault(u,0)
user_item_count[u] += 1
for v in users:
if u == v:continue
count.setdefault(u,{})
count[u].setdefault(v,0)
count[u][v] += 1
for u ,related_users in count.items():
self.userSimBest.setdefault(u,dict())
for v, cuv in related_users.items():
self.userSimBest[u][v] = cuv / math.sqrt(user_item_count[u] * user_item_count[v] * 1.0) def recommend(self,user,train = None,k = 8,nitem = 40):
train = train or self.traindata
rank = dict()
interacted_items = train.get(user,{})
for v ,wuv in sorted(self.userSimBest[user].items(),key = lambda x : x[1],reverse = True)[0:k]:#获取与user相似度最高的k个用户
for i , rvi in train[v].items():
if i in interacted_items:
continue #只选择user没有评分过的物品进行推荐
rank.setdefault(i,0)#设置初始值,以便做下面的累加运算
rank[i] += wuv #书中为rank[i] +=rvi*wuv
return dict(sorted(rank.items(),key = lambda x :x[1],reverse = True)[0:nitem])#用sorted方法对推荐的物品进行排序,预计评分高的排在前面,再取其中nitem个,nitem为每个用户推荐的物品数量 def recallAndPrecision(self,train = None,test = None,k = 8,nitem = 10):
train = train or self.traindata
test = test or self.testdata
hit = 0
recall = 0
precision = 0
for user in train.keys():
tu = test.get(user,{})#如果测试集中没有这个用户,则将tu初始化为空,避免test[user]报错
rank = self.recommend(user, train = train,k = k,nitem = nitem)
for item,_ in rank.items():
if item in tu:
hit += 1
recall += len(tu)
precision += nitem
return (hit / (recall * 1.0),hit / (precision * 1.0)) def coverage(self,train = None,test = None,k = 8,nitem = 10):
train = train or self.traindata
test = test or self.testdata
recommend_items = set()
all_items = set()
for user in train.keys():
for item in train[user].keys():
all_items.add(item)
rank = self.recommend(user, train, k = k, nitem = nitem)
for item,_ in rank.items():
recommend_items.add(item)
return len(recommend_items) / (len(all_items) * 1.0) def popularity(self,train = None,test = None,k = 8,nitem = 10):
train = train or self.traindata
test = test or self.testdata
item_popularity = dict()
for user ,items in train.items():
for item in items.keys():
item_popularity.setdefault(item,0)
item_popularity[item] += 1
ret = 0
n = 0
for user in train.keys():
rank = self.recommend(user, train, k = k, nitem = nitem)
for item ,_ in rank.items():
ret += math.log(1+item_popularity[item])
n += 1
return ret / (n * 1.0) def testUserBasedCF():
train = 'u1.base'
test = 'u1.test'
cf = UserBasedCF(train,test)
cf.userSimilarityBest()
print("%3s%20s%20s%20s%20s" % ('K',"precision",'recall','coverage','popularity'))
for k in [5,10,20,40,80,160]:
recall,precision = cf.recallAndPrecision( k = k)
coverage = cf.coverage(k = k)
popularity = cf.popularity(k = k)
print("%3d%19.3f%%%19.3f%%%19.3f%%%20.3f" % (k,precision * 100,recall * 100,coverage * 100,popularity)) if __name__ == "__main__":
testUserBasedCF() 基于项目的推荐系统,IBCF: '''
Created on 2013-10-10 @author: Administrator
'''
import random
import math class KNN:
def __init__(self,train = None,test = None):
self.trainfile = train
self.testfile = test
self.readData() def readData(self,train = None,test = None):
self.trainfile = train or self.trainfile
self.testfile = test or self.testfile
self.traindata = {}
self.testdata = {}
for line in open(self.trainfile):
userid,itemid,record,_ = line.split()
self.traindata.setdefault(userid,{})
self.traindata[userid][itemid]=record
for line in open(self.testfile):
userid,itemid,record,_ = line.split()
self.testdata.setdefault(userid,{})
self.testdata[userid][itemid]=record def ItemSim(self,train = None):
train = train or self.traindata
ItemSimcount = dict()
Item_count = dict()
for _,items in train.items():
for itemidi in items.keys():
Item_count.setdefault(itemidi,0)
Item_count[itemidi] += 1
for itemidj in items.keys():
if itemidi == itemidj:
continue
ItemSimcount.setdefault(itemidi,{})
ItemSimcount[itemidi].setdefault(itemidj,0)
ItemSimcount[itemidi][itemidj] +=1
self.ItemSimlist = dict()
for itemidi, related_item in ItemSimcount.items():
self.ItemSimlist.setdefault(itemidi,{})
for itemidj,wij in related_item.items():
self.ItemSimlist[itemidi].setdefault(itemidj,0)
self.ItemSimlist[itemidi][itemidj] = wij/math.sqrt(Item_count[itemidi]*Item_count[itemidj]*1.0) def recommend(self,user,train = None,k = 5,nitem = 10):
train = train or self.traindata
recommendlist = dict()
User_Itemlist = train.get(user,{})
for i,ri in User_Itemlist.items():
for j,wij in sorted(self.ItemSimlist[i].items(),key = lambda x:x[1],reverse = True)[0:k]:
if j in User_Itemlist:
continue
recommendlist.setdefault(j,0)
recommendlist[j] += float(ri)*wij
return dict(sorted(recommendlist.items(),key = lambda x :x[1],reverse = True)[0:nitem]) def recallAndPrecision(self,train = None,test = None,k = 5,nitem = 10):
train = train or self.traindata
test = test or self.testdata
hit = 0
recall = 0
precision = 0
for user in train.keys():
tu = test.get(user,{})
rank = self.recommend(user, train = train,k = k,nitem = nitem)
for item,_ in rank.items():
if item in tu:
hit += 1
recall += len(tu)
precision += nitem
return (hit / (recall * 1.0),hit / (precision * 1.0)) def coverage(self,train = None,test = None,k = 5,nitem = 10):
train = train or self.traindata
test = test or self.testdata
recommend_items = set()
all_items = set()
for user in train.keys():
for item in train[user].keys():
all_items.add(item)
rank = self.recommend(user, train, k = k, nitem = nitem)
for item,_ in rank.items():
recommend_items.add(item)
return len(recommend_items) / (len(all_items) * 1.0) def popularity(self,train = None,test = None,k = 5,nitem = 10):
train = train or self.traindata
test = test or self.testdata
item_popularity = dict()
for user ,items in train.items():
for item in items.keys():
item_popularity.setdefault(item,0)
item_popularity[item] += 1
ret = 0
n = 0
for user in train.keys():
rank = self.recommend(user, train, k = k, nitem = nitem)
for item ,_ in rank.items():
if item in item_popularity:
ret += math.log(1+item_popularity[item])
n += 1
return ret / (n * 1.0) def testKNNCF():
train = 'u1.base'
test = 'u1.test'
cf = KNN(train,test)
cf.ItemSim()
print("%3s%20s%20s%20s%20s" % ('K',"precision",'recall','coverage','popularity'))
for k in [5,10,20,40,80,160]:
recall,precision = cf.recallAndPrecision( k = k)
coverage = cf.coverage(k = k)
popularity = cf.popularity(k = k)
print("%3d%19.3f%%%19.3f%%%19.3f%%%20.3f" % (k,precision * 100,recall * 100,coverage * 100,popularity)) if __name__ == "__main__":
testKNNCF()

转:TopN推荐系统——推荐的实现与推荐效果的评价指标的更多相关文章

  1. 新闻推荐系统:基于内容的推荐算法(Recommender System:Content-based Recommendation)

    https://blog.csdn.net/qq_32690999/article/details/77434381 因为开发了一个新闻推荐系统的模块,在推荐算法这一块涉及到了基于内容的推荐算法(Co ...

  2. 推荐系统之基于图的推荐:基于随机游走的PersonalRank算法

    转自http://blog.csdn.net/sinat_33741547/article/details/53002524 一 基本概念 基于图的模型是推荐系统中相当重要的一种方法,以下内容的基本思 ...

  3. linux学习书籍推荐linux学习书籍推荐

    引用地址:http://www.cnblogs.com/notepi/archive/2013/06/15/3137103.html Linux 学习书目推荐 Linux基础 1.<Linux与 ...

  4. 推荐算法之用户推荐(UserCF)和物品推荐(ItemCF)对比

    一.定义 UserCF:推荐那些和他有共同兴趣爱好的用户喜欢的物品 ItemCF:推荐那些和他之前喜欢的物品类似的物品 根据用户推荐重点是反应和用户兴趣相似的小群体的热点,根据物品推荐着重与用户过去的 ...

  5. python书籍推荐:python编码推荐(高清完整pdf)

    目录INF-qa Python 编码规范................................................................................ ...

  6. 如何用ABP框架快速完成项目(11) - ABP只要加人即可马上加快项目进展- 全栈篇(2) - 不推荐模块组件化, 推荐微服务

    一个人写代码不需要担心会和别人的代码冲突, 不需要做代码合并, 不需要担心自己的代码被覆盖. 但是多个人一起写代码就需要担心这些问题.   解决这些问题的方法很多, 比如用AzureDevOps(TF ...

  7. SparkML之推荐引擎(二)---推荐模型评估

    本文内容和代码是接着上篇文章来写的,推荐先看一下哈~ 我们上一篇文章是写了电影推荐的实现,但是推荐内容是否合理呢,这就需要我们对模型进行评估 针对推荐模型,这里根据 均方差 和 K值平均准确率 来对模 ...

  8. JS 浮点型计算的精度问题 推荐的js 库 推荐的类库 Numeral.js 和 accounting.js

    推荐的类库 Numeral.js 和 accounting.js 文章来自 http://www.css88.com/archives/7324#more-7324

  9. mac软件推荐及chrome插件推荐

    通用软件 Alfred (超级好用的效率工具) 用mac这个软件一定要装,用习惯之后加上电脑本身的快捷键.效率提升的飞起. Alfred我常使用的功能有: 搜索chrome的书签 我搜索的书签大概分为 ...

随机推荐

  1. input 获取当前id,name

    <input name=" src="toright.png" value="mp3"> <script language=&quo ...

  2. MSSQL日期格式化

    Sql Server 中一个非常强大的日期格式化函数 Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AM Select CON ...

  3. Log4cpp配置文件格式说明

    Log4cpp配置文件格式说明 博客分类: log4cpp log4cpp  log4cpp有3个主要的组件:categories(类别).appenders(附加目的地).和 layouts(布局) ...

  4. IIS站点无法访问..点浏览IIS窗口直接关掉

    呃..其实这个问题很简单.. 大家可以先看这位大婶写的博文.. http://blog.csdn.net/chenguang79/article/details/7220232 如果网站一访问IIS就 ...

  5. xml基础总结

    可扩展的标记语言(eXtensible Markup Language) 优点:容易读懂:格式标准任何语言都内置了XML分析引擎,不用单独进行文件分析引擎的编写. 用普通二进制传输数据的缺点,解析方式 ...

  6. 如何判断一个变量是否是utf-8

    //判断传入的字符是否是utf-8  function is_utf8($word){   if (preg_match("/^([".chr(228)."-" ...

  7. admin site

    基本步骤: 1.添加 'django.contrib.admin' 到 INSTALL_APP 设置中. 2.再添加四个依赖项: 'django.contrib.auth', 'django.cont ...

  8. [译]Node.js Best Practices - Part 2

    原文: https://blog.risingstack.com/node-js-best-practices-part-2/ 统一风格 在大团队开发JS应用, 创建一个风格指南是很有必要的. 推荐看 ...

  9. VTK初学一,e_Triangle_CellArray三角形的另一种方法绘制

    #ifndef INITIAL_OPENGL #define INITIAL_OPENGL #include <vtkAutoInit.h> VTK_MODULE_INIT(vtkRend ...

  10. OC第三节——NSArray和NSMutableArray

    1.OC数组和c数组的区别        C语言的数组:            相同类型变量的有序结合. 类型:可以是简答数据类型.构造数据类型                int     a[10 ...