You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python电影推荐函数触发IndexError:索引类型不合法问题咨询

电影推荐函数IndexError问题解决

原代码

def get_recommendations(title, cosine_sim=cosine_sim):
    # Get the index of the movie that matches the title
  

    # Get the pairwsie similarity scores of all movies with that movie
    sim_scores = list(enumerate(cosine_sim[movies['name']]))

    # 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 df2['title'].iloc[movie_indices]

报错信息

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

问题原因

  1. 缺失根据标题获取对应电影索引的核心逻辑,注释中的步骤未实际实现;
  2. cosine_sim[movies['name']]索引方式错误:movies['name']是字符串序列,而相似度矩阵cosine_sim仅支持整数、切片等合法索引类型,直接传入字符串序列触发索引错误。

修复后的代码

def get_recommendations(title, cosine_sim=cosine_sim):
    # 获取匹配标题的电影索引
    try:
        idx = movies[movies['name'] == title].index[0]
    except IndexError:
        return f"未找到电影《{title}》"

    # 获取该电影与所有电影的相似度分数
    sim_scores = list(enumerate(cosine_sim[idx]))

    # 按相似度降序排序
    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)

    # 取前10个最相似的电影(排除自身)
    sim_scores = sim_scores[1:11]

    # 提取对应的电影索引
    movie_indices = [i[0] for i in sim_scores]

    # 返回前10个相似电影标题
    return df2['title'].iloc[movie_indices]

关键修复点

  • 新增根据标题查找电影索引的逻辑,并用try-except处理电影不存在的异常情况;
  • 将cosine_sim[movies['name']]改为cosine_sim[idx],用整数索引定位目标电影的相似度向量,符合矩阵的索引规则。

内容的提问来源于stack exchange,提问作者Honey Jhala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:45:22