怎么使用Python构建电影推荐系统

发布时间:2023-04-12 14:58:40 作者:iii
来源:亿速云 阅读:129

这篇文章主要讲解了“怎么使用Python构建电影推荐系统”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用Python构建电影推荐系统”吧!

导入数据

导入和合并数据集并创建 Pandas DataFrame

MovieLens 20M 数据集自 1995 年以来超过 2000 万的电影评级和标记活动。

# usecols 允许选择自己选择的特征,并通过dtype设定对应类型
movies_df=pd.read_csv('movies.csv', 
usecols=['movieId','title'], 
dtype={'movieId':'int32','title':'str'})
movies_df.head()

怎么使用Python构建电影推荐系统

ratings_df=pd.read_csv('ratings.csv',
 usecols=['userId', 'movieId', 'rating','timestamp'],
 dtype={'userId': 'int32', 'movieId': 'int32', 'rating': 'float32'})
ratings_df.head()

怎么使用Python构建电影推荐系统

检查是否存在任何空值以及两个数据中的条目数。

# 检查缺失值
movies_df.isnull().sum()

movieId 0

title 0

dtype: int64

ratings_df.isnull().sum()

userId 0

movieId 0

rating 0

timestamp 0

dtype: int64

print("Movies:",movies_df.shape)
print("Ratings:",ratings_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')
movies_merged_df.head()

怎么使用Python构建电影推荐系统

现在已经成功合并了导入的数据集。

添加衍生特征

添加必要的特征来分析数据。

通过按电影标题对用户评分进行分组来创建'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_average_rating.head()

怎么使用Python构建电影推荐系统

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')
movies_rating_count_avg.head()

怎么使用Python构建电影推荐系统

目前已经创建了 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)
plt.savefig('avgratinghist.jpg')

怎么使用Python构建电影推荐系统

图1 Average Rating直方图

怎么使用Python构建电影推荐系统

图2 Rating Count的直方图

现在创建一个joinplot二维图表,将这两个特征一起可视化。

plot=sns.jointplot(x='Average Rating',
 y='Rating Count',
 data=movies_rating_count_avg,
 alpha=0.5, 
 color='tab:pink')
plot.savefig('joinplot.jpg')

怎么使用Python构建电影推荐系统

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
mean58.759
std 61.965
min1.000
25% 13.000
50% 39.000
75% 84.000
max329.000
Name: Rating Count, dtype: float64

设置阈值并筛选出高于阈值的数据。

popularity_threshold = 50
popular_movies= rating_with_RatingCount[
rating_with_RatingCount['Rating Count']>=popularity_threshold]
popular_movies.head()
# popular_movies.shape

怎么使用Python构建电影推荐系统

至此已经通过过滤掉了评论低于阈值的电影来清洗数据。

创建数据透视表

创建一个以用户为索引、以电影为列的数据透视表

为了稍后将数据加载到模型中,需要创建一个数据透视表。并设置'title'作为索引,'userId'为列,'rating'为值。

import os
movie_features_df=popular_movies.pivot_table(
index='title',columns='userId',values='rating').fillna(0)
movie_features_df.head()
movie_features_df.to_excel('output.xlsx')

怎么使用Python构建电影推荐系统

接下来将创建的数据透视表加载到模型。

建立 kNN 模型

建立 kNN 模型并输出与每部电影相似的 5 个推荐

使用scipy.sparse模块中的csr_matrix方法,将数据透视表转换为用于拟合模型的数组矩阵。

from scipy.sparse import csr_matrix
movie_features_df_matrix = csr_matrix(movie_features_df.values)

最后,使用之前生成的矩阵数据,来训练来自sklearn中的NearestNeighbors算法。并设置参数:metric = 'cosine', algorithm = 'brute'

from sklearn.neighbors import NearestNeighbors
model_knn = NearestNeighbors(metric = 'cosine',
 algorithm = 'brute')
model_knn.fit(movie_features_df_matrix)

现在向模型传递一个索引,根据'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),
n_neighbors = 6)

最后在 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:
5: Harry Potter and the Chamber of Secrets (2002), with distance of 0.4506162405014038:

感谢各位的阅读,以上就是“怎么使用Python构建电影推荐系统”的内容了,经过本文的学习后,相信大家对怎么使用Python构建电影推荐系统这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 怎么使用Python制作一个极简四则运算解释器
  2. Python常用技巧有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python当中Lambda函数怎么使用

下一篇:tensorflow2.10怎么使用BERT实现Semantic Similarity

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》