我正在从这里https://towardsdatascience.com/how-to-build-from-scratch-a-content-based-movie-recommender-with-natural-language-processing-25ad400eb243遵循一个内容基础推荐系统。
在计算余弦相似度矩阵后,创建一个函数来推荐与我们输入的内容最相似的前10个内容。
# creating a Series for the movie titles so they are associated to an ordered numerical
# list I will use in the function to match the indexes
indices = pd.Series(df.index)
# defining the function that takes in movie title
# as input and returns the top 10 recommended movies
def recommendations(title, cosine_sim = cosine_sim):
# initializing the empty list of recommended movies
recommended_movies = []
# gettin the index of the movie that matches the title
idx = indices[indices == title].index[0]
# creating a Series with the similarity scores in descending order
score_series = pd.Series(cosine_sim[idx]).sort_values(ascending = False)
# getting the indexes of the 10 most similar movies
top_10_indexes = list(score_series.iloc[1:11].index)
# populating the list with the titles of the best 10 matching movies
for i in top_10_indexes:
recommended_movies.append(list(df.index)[i])
return recommended_movies上面给出了我输入的每个内容的前10个内容。我想创建一个数据帧,其中列1将是所有内容,列2-10将是最相似的电影。因此,每一行都是原始内容和不包括它自己的前10个相似的电影。我是python的新手,任何帮助我都很感激。
发布于 2019-11-21 06:39:36
考虑将输入标题及其建议保存在数据框中,然后根据需要对值运行pivot_table。但是,首先调整函数以返回一个字典,并使用列表理解将结果传递给DataFrame构造函数来运行它:
indices = pd.Series(df.index)
def recommendations(title, cosine_sim = cosine_sim):
...
df_dict = {'title' = [title] * 10,
'recommended' = recommended_movies,
'rank' = list(range(1, 11))}
return df_dict
# BUILD DATA FRAME FROM LIST OF DICTS
df = pd.DataFrame([recommendations(t) for t in indices.to_list()])
# PIVOT FOR TITLE X OTHERS VIEW
pd.pivot_table(df, index = 'title', columns = 'recommended',
values = 'rank', aggunc = 'max')https://stackoverflow.com/questions/58963459
复制相似问题