首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为每个内容创建前10个推荐的数据框架

为每个内容创建前10个推荐的数据框架
EN

Stack Overflow用户
提问于 2019-11-21 05:12:45
回答 1查看 112关注 0票数 0

我正在从这里https://towardsdatascience.com/how-to-build-from-scratch-a-content-based-movie-recommender-with-natural-language-processing-25ad400eb243遵循一个内容基础推荐系统。

在计算余弦相似度矩阵后,创建一个函数来推荐与我们输入的内容最相似的前10个内容。

代码语言:javascript
复制
# 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的新手,任何帮助我都很感激。

EN

回答 1

Stack Overflow用户

发布于 2019-11-21 06:39:36

考虑将输入标题及其建议保存在数据框中,然后根据需要对值运行pivot_table。但是,首先调整函数以返回一个字典,并使用列表理解将结果传递给DataFrame构造函数来运行它:

代码语言:javascript
复制
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')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58963459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档