遍历列表存储向量遇ValueError:无法将(96)形状数组广播至(0)形状
解决ValueError: could not broadcast input array from shape (96) into shape (0)
嘿,这个问题我之前也碰到过!咱们先拆解一下报错的根源:
你看到的shape (96)是spaCy生成的句子向量的长度,而shape (0)是你初始化的数组X的列数——这说明你获取的embedding_dim值是0,根本没法容纳句子向量。
为什么会出现这个问题?
问题出在你使用的spaCy模型上:spaCy的轻量模型(比如en_core_web_sm)不包含预训练的词向量,所以nlp.vocab.vectors_length会返回0。而只有带预训练向量的模型(比如en_core_web_md、en_core_web_lg)才会返回有效的向量长度(比如96、300)。
解决方案
1. 安装带预训练向量的spaCy模型
在终端运行:
pip install en_core_web_md
(如果需要更大维度的向量,也可以安装en_core_web_lg)
2. 加载正确的模型
把你初始化nlp的代码改成:
import spacy nlp = spacy.load("en_core_web_md") # 替换成你安装的带向量的模型
3. 修正你的代码(可选,但更稳妥)
可以在初始化X之前先验证一下embedding_dim的值,避免再踩坑:
import numpy as np # 加载正确的模型 nlp = spacy.load("en_core_web_md") sentences = [' i want to fly from boston at 838 am and arrive in denver at 1110 in the morning', ' what flights are available from pittsburgh to baltimore on thursday morning', ' what is the arrival time in san francisco for the 755 am flight leaving washington', ' cheapest airfare from tacoma to orlando', ' round trip fares from pittsburgh to philadelphia under 1000 dollars'] n_sentences = len(sentences) embedding_dim = nlp.vocab.vectors_length # 验证向量长度是否有效 if embedding_dim == 0: raise ValueError("当前使用的spaCy模型没有预训练向量,请安装en_core_web_md或en_core_web_lg") X = np.zeros((n_sentences, embedding_dim)) for idx, sentence in enumerate(sentences): doc = nlp(sentence) X[idx, :] = doc.vector
额外提示
如果你是自己训练的自定义词向量,记得要正确加载到spaCy的vocab中,否则vectors_length还是会返回0。
内容的提问来源于stack exchange,提问作者Sam.H
相关产品推荐
相关产品推荐

