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

使用Gensim 4.0的Doc2VecKeyedVectors调用similar_by_vector报解包错误

问题解决:Gensim 4.0中Doc2VecKeyedVectors调用similar_by_vector报错

错误原因在于你误用了Doc2VecKeyedVectors类——这个类是Gensim中Doc2Vec模型内部专用的向量存储类,针对Doc2Vec模型原生的文档向量设计,并不适合手动添加自定义推断向量的场景。直接初始化它并调用add_vector,会导致后续相似度查询时内部逻辑出现解包错误。

正确的做法是使用通用的KeyedVectors类来存储你推断的向量,修改后的代码如下:

from gensim.models import KeyedVectors  # 确保导入正确的类

model = <load a Doc2Vec model>
corpus = <load an object which returns key/words pairs>

# 替换为普通KeyedVectors
kv = KeyedVectors(vector_size=50)
for key, words in corpus:
    vector = model.infer_vector(words)
    kv.add_vector(key, vector)

test_words = ['word1', 'word2', ...]
vector = model.infer_vector(test_words)
sims = kv.similar_by_vector(vector, topn=200)

如果你的场景必须使用Doc2VecKeyedVectors,则应该通过已加载的Doc2Vec模型的dv属性直接获取(该属性已预先初始化好符合要求的向量存储),而非手动创建实例。但对于你这种自行推断向量并存储查询的场景,KeyedVectors是更合适的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:45:07