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

如何将(2,300)数组转为(,300)均值数组?Gensim实现方案

用Gensim实现词向量均值计算
  • 直接使用Gensim词向量模型的get_mean_vector()方法就能满足需求,它会自动对传入的tokens对应的词向量做逐元素均值计算,直接返回形状为(300,)的一维数组。
  • 对比你当前用的wv[filtered_tokens]:这个写法返回的是每个token对应的词向量组成的二维数组(shape=(2,300)),而get_mean_vector()内部已经封装了均值计算逻辑,无需额外处理。

代码修改示例

原来的函数:

def preprocess_and_vectorize(text):
    # 这里是你的文本预处理逻辑,得到filtered_tokens
    filtered_tokens = preprocess_text(text)
    # 返回二维数组
    return wv[filtered_tokens]

修改后:

def preprocess_and_vectorize(text):
    filtered_tokens = preprocess_text(text)
    # 返回一维均值数组
    return wv.get_mean_vector(filtered_tokens)

额外说明

如果你想手动用numpy实现(虽然你倾向于Gensim方法),其实可以用np.mean(wv[filtered_tokens], axis=0),axis=0参数指定按列(对应每个特征维度)取均值,同样能得到(300,)的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:35:44