运行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
相关产品推荐
相关产品推荐

