'使用单词向量时出现ValueError(无法广播):如何修复?'

2024-04-19 04:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一个项目制作一个聊天机器人,我正在使用spaCy。我正在学习一个教程,我需要创建一个2D数组X,它的行数和我的数据集中的句子数一样多。每一行都是描述句子的词向量。但是,当我尝试创建这个数组时,我得到了一个错误。我不太清楚是什么原因造成这一点,因为我是新的空间和NLP的一般。你知道吗

我试图从文件中找出问题所在。我也查看了堆栈溢出,但找不到任何解释我的问题的方法。你知道吗

import spacy
import numpy
#load spacy nlp model
nlp = spacy.load("en_core_web_sm")

#calculate the length of my sentences dataset
n_sentences = len(sentences)
#calculate the dimensionality of nlp model
embedding_dim = nlp.vocab.vectors_length
#X is a 2D array with as many rows as there are sentences in my dataset
#Each row is a vector describing the sentence
#initialise array with zeros
X = numpy.zeros((n_sentences, embedding_dim))
#iterate over sentences
for idx, sentence in enumerate(sentences):
   #pass each sentence to nlp object to create document
   doc = nlp(sentence)
   print(doc.vector.shape)
   #save document's .vector attribute to corresponding row in X
   X[idx, :] = doc.vector

这是最后一行抛出错误,据我所知。你知道吗

ValueError: could not broadcast input array from shape (96) into shape (1,0)

我不知道是什么原因造成的,因为我不太熟悉numpy数组和数组形状。我的数据集,句子,是一个简单的字符串列表。我希望最终得到一个包含单词向量的二维数组。我遵循的教程说,代码是正确的,所以我不知道为什么它不适合我,我想我一定错过了一些东西。你知道吗

这是一个学术(A级)项目。你知道吗


Tags: theto项目innumpydocnlpspacy
1条回答
网友
1楼 · 发布于 2024-04-19 04:23:06

en_core_web_sm模型不包括单词向量。您可以下载en_core_web_mden_core_web_lg models,这样做。你知道吗

Reference

nlp = spacy.load("en_core_web_md")
print (nlp.vocab.vectors_length)

输出:

300

相关问题 更多 >