电影推荐系统 基于内容相似度的召回

转载代码:https://zhuanlan.zhihu.com/p/98295397
对上述文章代码进行了实际跑通。
废话不说,直接上代码:
数据说明:
item_profile.json user_profile.json 是加工出来的特征。
就是使用所有电影风格作为用户和电影的几个特征列,对每个用户的这几个电影风格列填充,用户评分的所有电影中有这个风格就是1,没有就是0。同样,电影特征列也是使用这几个电影风格,保持和用户的顺序一致。同样做填充1或0,这样就可以做相似度计算了。有些人认为基于这样的特征做相似度计算就是基于内容的推荐了。有些认为基于内容的推荐,大多是文本场景推荐,基于文本内容的向量化做相似度计算。

我认为,这是基于用户的行为产生了用户和物品的属性交换和转移,原来电影的风格属性转移到了用户身上,这样用户和物品有了相同的属性特征维度,就可以进行相似度的度量了。
因此,基于这样的特征做推荐,我感觉叫做基于画像标签的推荐更合适,实际是对用户进行了电影属性的画像,把电影的属性转移到了用户身上。当然画像不仅仅是打标签分类,也可以像这个特征处理一样,将电影的维度维度、及维度层级作为标签对待。

modelSamples.csv 数据是王哲的电影推荐系统,离线处理的数据,这里直接拿来使用,即加工了用户点击的电影的5个风格,作为用户的特征列。

# coding: utf-8 -*-"""Author: AlanDesc:编写一个基于内容推荐算法的电影推荐系统(训练模型)
"""
import json
import pandas as pd
import numpy as np
import math
import randomclass CBRecommend:# 加载dataProcessing.py中预处理的数据def __init__(self, K):# 给用户推荐的item个数self.K = Kself.item_profile = json.load(open("./item_profile.json", "r"))self.user_profile = json.load(open("./user_profile.json", "r"))# 获取用户未进行评分的item列表def get_none_score_item(self, user):infile = "E:/IdeaProjects/SparrowRecSys-master/TFRecModel/src/com/sparrowrecsys/sampledata/"items = pd.read_csv(infile + "movies.csv")["movieId"].valuesdata = pd.read_csv(infile + "ratings.csv")have_score_items = data[data["userId"] == user]["movieId"].valuesnone_score_items = set(items) - set(have_score_items)return none_score_items# 获取用户对item的喜好程度(余弦相似度)def cosUI(self, user, item):user_vec = np.array(self.user_profile.get(str(user), [0]))item_vec = np.array(self.item_profile.get(str(item), [0]))# print("user_vec = ", user_vec)# print("item_vec = ", item_vec)Uia = sum(user_vec * item_vec)# print("Uia = ", Uia)# print(type(Uia))if Uia.item() == 0:return 0.0Ua = math.sqrt(sum([math.pow(one, 2) for one in self.user_profile[str(user)]]))Ia = math.sqrt(sum([math.pow(one, 2) for one in self.item_profile[str(item)]]))return Uia / (Ua * Ia)# 为用户进行电影推荐def recommend(self, user):user_result = {}item_list = self.get_none_score_item(user)for item in item_list:user_result[item] = self.cosUI(user, item)if self.K is None:result = sorted(user_result.items(), key=lambda k: k[1], reverse=True)else:result = sorted(user_result.items(), key=lambda k: k[1], reverse=True)[:self.K]print(result)# 推荐系统效果评估def evaluate(self):evas = []infile = "E:/IdeaProjects/SparrowRecSys-master/TFRecModel/src/com/sparrowrecsys/sampledata/"data = pd.read_csv(infile + "ratings.csv")# 随机选取20个用户进行效果评估for user in random.sample([one for one in range(1, 6040)], 20):have_score_items = data[data["userId"] == user]["movieId"].valuesitems = pd.read_csv(infile + "movies.csv")["movieId"].valuesuser_result = {}for item in items:user_result[item] = self.cosUI(user, item)results = sorted(user_result.items(), key=lambda k: k[1], reverse=True)[:len(have_score_items)]rec_items = []for one in results:rec_items.append(one[0])eva = len(set(rec_items) & set(have_score_items)) / len(have_score_items)evas.append(eva)return sum(evas) / len(evas)# 获取用户、电影属性表示def get_users_movies_profile(self):infile = "E:/IdeaProjects/SparrowRecSys-master/TFRecModel/src/com/sparrowrecsys/sampledata/modelSamples.csv"data = pd.read_csv(infile)cols = np.concatenate([data['userGenre1'].unique(),data['userGenre2'].unique(),data['userGenre3'].unique(),data['userGenre4'].unique(),data['userGenre5'].unique()]).astype(np.str)genres = np.unique(cols)nan = np.array(['nan']).astype(np.str)genres = set(np.setdiff1d(genres, nan))'''{'Action','Adventure','Animation','Children','Comedy','Crime','Documentary','Drama','Fantasy','Film-Noir','Horror','IMAX','Musical','Mystery','Romance','Sci-Fi','Thriller','War','Western'}'''# 用户属性user_profile_tmp = data.groupby('userId').apply(lambda df: set(np.setdiff1d(np.unique(np.concatenate([df['userGenre1'].unique(),df['userGenre2'].unique(),df['userGenre3'].unique(),df['userGenre4'].unique(),df['userGenre5'].unique()]).astype(np.str)), nan)))user_profile = pd.DataFrame(user_profile_tmp)user_profile['userId'] = user_profile.index# user_profile.rename(columns={'favor_genres': '0'}, inplace=True)user_profile.columns = ['favor_genres', 'userId']for genre in genres:user_profile[genre] = user_profile['favor_genres'].apply(lambda x: 1 if genre in x else 0)# 电影属性item_profile_tmp = data.groupby('movieId').apply(lambda df: set(np.setdiff1d(np.unique(np.concatenate([df['movieGenre1'].unique(),df['movieGenre2'].unique(),df['movieGenre3'].unique()]).astype(np.str)), nan)))item_profile = pd.DataFrame(item_profile_tmp)item_profile['movieId'] = item_profile.index# user_profile.rename(columns={'favor_genres': '0'}, inplace=True)item_profile.columns = ['favor_genres', 'movieId']for genre in genres:item_profile[genre] = item_profile['favor_genres'].apply(lambda x: 1 if genre in x else 0)# 转json形式存储# js = item_profile.drop(columns=['favor_genres']).to_json(orient="values", force_ascii=False)# filename = "./item_profile.json"# with open(filename, 'w', encoding='utf-8') as f:#     json.dump(js, f, ensure_ascii=False)# items = json.load(open(filename, "r"))# items = item_profile.set_index('movieId').drop(columns=['favor_genres']).to_dict('list')users = user_profile.drop(columns=['favor_genres']).to_numpy()users_dict = {}for item in users:users_dict[str(item[0])] = item[1:].tolist()json.dumps(users_dict)filename = "./user_profile.json"with open(filename, 'w', encoding='utf-8') as f:json.dump(users_dict, f, ensure_ascii=False)items = item_profile.drop(columns=['favor_genres']).to_numpy()items_dict = {}for item in items:items_dict[str(item[0])] = item[1:].tolist()json.dumps(items_dict)filename = "./item_profile.json"with open(filename, 'w', encoding='utf-8') as f:json.dump(items_dict, f, ensure_ascii=False)if __name__ == "__main__":cb = CBRecommend(K=10)simi = cb.cosUI(1, 1)cb.recommend(1)print(cb.evaluate())

电影推荐系统 基于内容相似度的召回相关推荐

  1. mysql项目案例电影_Python+Django+Mysql实现在线电影推荐系统 基于用户、项目的协同过滤推荐在线电影系统 代码实现 源代码下载...

    Python+Django+Mysql实现在线电影推荐系统(基于用户.项目的协同过滤推荐算法) pycharm2020professional版本,python3.8版本,django3.1.1版本, ...

  2. Python+Django+Mysql实现在线电影推荐系统 基于用户、项目的协同过滤推荐在线电影系统 代码实现 源代码下载

    Python+Django+Mysql实现在线电影推荐系统(基于用户.项目的协同过滤推荐算法) 一.项目简介 1.开发工具和实现技术 pycharm2020professional版本,python3 ...

  3. 推荐系统-基于内容的推荐算法(Content-Based)

    基于内容的推荐算法(Content-Based) 简介 基于内容的推荐方法是非常直接的,它以物品的内容描述信息为依据来做出的推荐,本质上是基于对物品和用户自身的特征或属性的直接分析和计算. 例如,假设 ...

  4. 推荐系统 - 基于FM算法的协同召回算法

    详细理论参照此处:https://zhuanlan.zhihu.com/p/58160982 说明 1.FM是一种LR基础上扩展的线性模型,在特征上做了两两组合上的信息挖掘,因为其高效性,既可以作为召 ...

  5. Python--[项目]机器学习之电影推荐系统[基于物品的协同过滤](代码版)

    如何将新手机短信转发到指定邮箱或者手机 步骤一: 选择sign in with email 步骤二: 选择get more 步骤三: 找到一个 if any sms received than sen ...

  6. [转载] Python基于机器学习方法实现的电影推荐系统

    参考链接: Python | 电影推荐系统的实现 推荐算法在互联网行业的应用非常广泛,今日头条.美团点评等都有个性化推荐,推荐算法抽象来讲,是一种对于内容满意度的拟合函数,涉及到用户特征和内容特征,作 ...

  7. 基于Python机器学习方法的电影推荐系统

    资源下载地址:https://download.csdn.net/download/sheziqiong/85745459 资源下载地址:https://download.csdn.net/downl ...

  8. 基于机器学习实现协同过滤推荐算法的电影推荐系统

    推荐算法在互联网行业的应用非常广泛,今日头条.美团点评等都有个性化推荐,推荐算法抽象来讲,是一种对于内容满意度的拟合函数,涉及到用户特征和内容特征,作为模型训练所需维度的两大来源,而点击率,页面停留时 ...

  9. movielens推荐系统_基于内容推荐(二)

    A content-based movie recommender system using MovieLens tags (用标签构建一个简单的电影推荐系统) 现在有很多电影.如果没有某种推荐系统, ...

最新文章

  1. 百度快照被劫持跳转的解决办法
  2. ClientDataSet 探讨
  3. 【随笔】卷积神经网络中的卷积怎么卷?
  4. 在js中如何判断一个对象是否为空
  5. vb.net axWindowsMediaPlayer 控件使用
  6. 【思科百难】RIP两个版本之间能够相互通信?
  7. jQuery特效 | 导航底部横线跟随鼠标缓动
  8. jQuery点击文本框复制其内容到剪贴板上
  9. 【优化算法】多目标跟踪优化算法(MTOA)【含Matlab源码 1466期】
  10. 大话西游手游服务器维护要多久,2018年11月22日维护公告
  11. 计算机编程—必备基础知识点
  12. Python3,1行代码,去除图片的背景图,确实香。
  13. 畅购商城(三):商品管理
  14. 传统弓上弦的几种方式
  15. php请求纯文本,php – 使用纯文本回退发送HTML简报
  16. 视频教程-微信小程序电商实战-PHP
  17. 爬取智联招聘网站的手段(scrapy)
  18. 颠覆IoT行业的开发神器!涂鸦智能重磅推出TuyaOS操作系统【程序员必备】
  19. java private修饰方法,private修饰的方法
  20. c语言编程模拟机械钟表行走,C语言课程设计报告-模拟时钟转动程序

热门文章

  1. 2021年WordPress主题Zibll子比主题V5.4资源主题免授权
  2. 多台电脑共享打印机怎么设置?
  3. Android游戏开发教程:手教你写跳跃类游戏
  4. mysql的左联、右联、内联查询
  5. 移远NB-IOT BC28 模组 接入移动OneNET平台
  6. Bootstrap多个手风琴折叠展开效果
  7. MP代码生成器(拿来即用)
  8. java基础数据类型包装类的作用
  9. 【HEC-RAS】2D模型初步介绍(2)--创建二维网格
  10. 浅谈position属性