TF-IDF构建内容推荐系统执行排序时报ValueError如何解决?
问题修复方案
报错根因
该报错由两个问题共同触发:
- 索引值非单值:如果你的数据集存在重复的
Movie Title字段,indices[title]会返回包含多个索引的Pandas Series,而非单个整数。此时cosine_sim[idx]会输出二维数组,enumerate处理后每个元素的第二位是数组而非单个浮点相似度值,排序时无法直接比较数组大小,触发对应报错。 - 调用逻辑错误:
get_recommendations.head(10)写法不合法,get_recommendations是函数对象,需要先传入参数调用拿到返回的Series结果后,才能调用head方法。
修复代码
先对数据集去重,同时兼容多匹配场景,修正调用逻辑即可:
# 提前对数据集按电影标题去重,避免重复索引问题 new_df = new_df.drop_duplicates(subset=['Movie Title'], keep='first').reset_index(drop=True) # Build a 1-dimensional array with book titles titles = new_df['Movie Title'] indices = pd.Series(new_df.index, index=new_df['Movie Title']) # Function that takes in movie title as input and outputs most similar movies def get_recommendations(title): # 获取匹配的索引 idx = indices[title] # 兼容多匹配场景,取第一个匹配的索引 if isinstance(idx, pd.Series): idx = idx.iloc[0] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] # Get the movie indices movie_indices = [i[0] for i in sim_scores] # Return the top 10 most similar movies return new_df['Movie Title'].iloc[movie_indices] # 修正后的调用代码 recommend_res = get_recommendations('The Hangover') print(recommend_res.head(10))
内容的提问来源于stack exchange,提问作者eveobrien
相关产品推荐
相关产品推荐

