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

运行BERTopic教程代码调用topic_labels_时遇unhashable type错误

解决BERTopic中TypeError: unhashable type: 'numpy.ndarray'错误

问题出在topic_model.transform()返回的topic是numpy数组类型,而topic_labels_是键为整数的字典——numpy数组属于不可哈希类型,没法直接作为字典的键,所以触发了这个错误。

修正方法很简单,把数组转成整数类型即可,有两种常用方式:

  • 直接取数组的第一个元素(因为单条文本调用transform只会返回一个主题结果):

    topic_model.topic_labels_[topic[0]]
    
  • 将numpy数组强制转换为整数:

    topic_model.topic_labels_[int(topic)]
    

修正后的完整代码示例:

from bertopic import BERTopic
topic_model = BERTopic.load("MaartenGr/BERTopic_Wikipedia")
topic, prob = topic_model.transform("This is an incredible movie!")
# 这里用第一种方式获取主题标签
topic_label = topic_model.topic_labels_[topic[0]]
print(topic_label)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:24:54