在日常数据挖掘工作中,使用除了会涉及到使用Python处理分类或预测任务,构建有时候还会涉及推荐系统相关任务。电影 推荐系统用于各个领域,推荐常见的系统例子包括视频和音乐服务的播放列表生成器、在线商店的使用产品推荐器或社交媒体平台的内容推荐器。在这个项目中,构建我们创建一个电影推荐器。电影 协同过滤通过收集许多用户的推荐偏好或品味信息,对用户的系统兴趣进行自动预测(过滤)。到目前为止,使用推荐系统已经发展很长一段时间了,构建它们的电影模型基于各种技术,如加权平均、推荐相关性、系统机器学习、深度学习等等。 自 1995 年以来,Movielens 20M dataset 拥有超过 2000 万个电影评级和标记活动。在本文中,我们将从movie.csv & rating.csv文件中检索信息。使用Python库:Pandas, Seaborn, Scikit-learn和SciPy,使用k-近邻算法中的余弦相似度训练模型。 以下是该项目的核心步骤: MovieLens 20M 数据集自 1995 年以来超过 2000 万的电影评级和标记活动。 # usecols 允许选择自己选择的特征,并通过dtype设定对应类型 movies_df=pd.read_csv(movies.csv, usecols=[movieId,title], dtype={ movieId:int32,title:str}) ratings_df=pd.read_csv(ratings.csv, usecols=[userId, movieId, rating,timestamp], dtype={ userId: int32, movieId: int32, rating: float32}) 检查是否存在任何空值以及两个数据中的条目数。 # 检查缺失值 movieId 0 title 0 dtype: int64 userId 0 movieId 0 rating 0 timestamp 0 dtype: int64 print("Movies:",movies_df.shape) Movies: (9742, 2) Ratings: (100836, 4) 合并列上的数据帧 movieId # movies_df.info() # ratings_df.info() movies_merged_df=movies_df.merge(ratings_df, on=movieId) 现在已经成功合并了导入的数据集。 添加必要的特征来分析数据。 通过按电影标题对用户评分进行分组来创建Average Rating & Rating Count列。 movies_average_rating=movies_merged_df.groupby(title)[rating]\ .mean().sort_values(ascending=False)\ .reset_index().rename(columns={ rating:Average Rating}) movies_rating_count=movies_merged_df.groupby(title)[rating]\ .count().sort_values(ascending=True)\ .reset_index().rename(columns={ rating:Rating Count}) #ascending=False movies_rating_count_avg=movies_rating_count.merge(movies_average_rating, on=title) 目前已经创建了 2 个新的衍生特征。 使用 Seaborn 可视化数据: 使用 seaborn & matplotlib 可视化数据,以便更好地观察和分析数据。 将新创建的特征绘制直方图,服务器托管并查看它们的分布。设置 bin 大小为80,该值的设置需要具体分析,并合理设置。 # 导入可视化库 import seaborn as sns import matplotlib.pyplot as plt sns.set(font_scale = 1) plt.rcParams["axes.grid"] = False plt.style.use(dark_background) %matplotlib inline # 绘制图形 plt.figure(figsize=(12,4)) plt.hist(movies_rating_count_avg[Rating Count],bins=80,color=tab:purple) plt.ylabel(Ratings Count(Scaled), fontsize=16) plt.savefig(ratingcounthist.jpg) plt.figure(figsize=(12,4)) plt.hist(movies_rating_count_avg[Average Rating],bins=80,color=tab:purple) plt.ylabel(Average Rating,fontsize=16) 图1 Average Rating直方图 图2 Rating Count的直方图 现在创建一个joinplot二维图表,将这两个特征一起可视化。 plot=sns.jointplot(x=Average Rating, y=Rating Count, data=movies_rating_count_avg, alpha=0.5, color=tab:pink) Average Rating和Rating Count的二维图 运用describe()函数得到数据集的描述统计值,如分位数和标准差等。 pd.set_option(display.float_format, lambda x: %.3f % x) print(rating_with_RatingCount[Rating Count].describe())count 100836.000 mean 58.759 std 61.965 min 1.000 25% 13.000 50% 39.000 75% 84.000 max 329.000 设置阈值并筛选出高于阈值的数据。 popularity_threshold = 50 popular_movies= rating_with_RatingCount[ rating_with_RatingCount[Rating Count]>=popularity_threshold] popular_movies.head() 至此已经通过过滤掉了评论低于阈值的电影来清洗数据。 创建一个以用户为索引、以电影为列的数据透视表 为了稍后将数据加载到模型中,需要创建一个数据透视表。并设置title作为索引,userId为列,网站模板rating为值。 import os movie_features_df=popular_movies.pivot_table( index=title,columns=userId,values=rating).fillna(0) movie_features_df.head() 接下来将创建的数据透视表加载到模型。 建立 kNN 模型并输出与每部电影相似的 5 个推荐 使用scipy.sparse模块中的csr_matrix方法,将数据透视表转换为用于拟合模型的数组矩阵。 from scipy.sparse import csr_matrix 最后,使用之前生成的矩阵数据,来训练来自sklearn中的NearestNeighbors算法。并设置参数:metric = cosine, algorithm = brute from sklearn.neighbors import NearestNeighbors model_knn = NearestNeighbors(metric = cosine, algorithm = brute) 现在向模型传递一个索引,根据kneighbors算法要求,需要将数据转换为单行数组,并设置n_neighbors的值。 query_index = np.random.choice(movie_features_df.shape[0]) distances, indices = model_knn.kneighbors(movie_features_df.iloc[query_index,:].values.reshape(1, -1), 最后在 query_index 中输出出电影推荐。 for i in range(0, len(distances.flatten())): if i == 0: print(Recommendations for { 0}:\n .format(movie_features_df.index[query_index])) else: print({ 0}: { 1}, with distance of { 2}: .format(i, movie_features_df.index[indices.flatten()[i]], distances.flatten()[i]))Recommendations for Harry Potter and the Order of the Phoenix (2007): 1: Harry Potter and the Half-Blood Prince (2009), with distance of 0.2346513867378235: 2: Harry Potter and the Order of the Phoenix (2007), with distance of 0.3396233320236206: 3: Harry Potter and the Goblet of Fire (2005), with distance of 0.4170845150947571: 4: Harry Potter and the Prisoner of Azkaban (2004), with distance of 0.4499547481536865: 至此我们已经能够成功构建了一个仅基于用户评分的推荐引擎。 以下是我们构建电影推荐系统的步骤摘要: 以下是可以扩展项目的一些方法:导入数据
导入和合并数据集并创建 Pandas DataFrame添加衍生特征
数据可视化
数据清洗
创建数据透视表
建立 kNN 模型
总结
写在最后
上一篇
下一篇