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

使用joblib加载模型后调用kneighbors函数触发TypeError报错求助

解决TypeError: 'module' object is not callable报错

错误根源

你代码里的random(range(0,df.__len__()))是把random模块直接当成函数调用了,而random本身是模块对象,并非可调用的函数,这才触发了该报错。

修复方案

1. 修正随机索引生成方式

根据random的导入方式,有两种修正选项:

  • 若使用import random导入模块:
    用random.randint(0, len(df)-1)生成指定范围内的随机整数索引,或者用random.choice(df.index)直接从DataFrame的索引中随机选取一个,后者更简洁。
  • 若想直接导入函数:
    先写from random import randint,再用randint(0, len(df)-1)生成随机索引。

2. 优化后的完整代码

import joblib
import random

# 假设df和lookupdata已正确加载
filename = "Nearest_neighbors_model.pkl"
loaded_model = joblib.load(filename)

# 生成随机索引,替换原错误写法
random_idx = random.randint(0, len(df)-1)
# 也可以用 random_idx = random.choice(df.index)

# 获取邻居索引并遍历输出
neighbors = loaded_model.kneighbors([df.iloc[random_idx]], n_neighbors=50, return_distance=False)[0]
for idx in neighbors:
    print(lookupdata.iloc[idx])

额外优化建议

  • 避免使用df.__len__(),直接用len(df)更符合Python编码规范。
  • 将长代码拆分为多行,提升可读性的同时便于调试。

内容的提问来源于stack exchange,提问作者Otis Golden

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 01:51:00