【发布时间】:2019-11-29 04:57:48
【问题描述】:
我正在尝试在推文上应用词嵌入。我试图通过取推文中出现的单词向量的平均值来为每条推文创建一个向量,如下所示:
def word_vector(tokens, size):
vec = np.zeros(size).reshape((1, size))
count = 0.
for word in tokens:
try:
vec += model_w2v[word].reshape((1, size))
count += 1.
except KeyError: # handling the case where the token is not in vocabulary
continue
if count != 0:
vec /= count
return vec
接下来,当我尝试准备 word2vec 功能集如下:
wordvec_arrays = np.zeros((len(tokenized_tweet), 200))
#the length of the vector is 200
for i in range(len(tokenized_tweet)):
wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 200)
wordvec_df = pd.DataFrame(wordvec_arrays)
wordvec_df.shape
我在循环中得到以下错误:
ValueError Traceback (most recent call last) <ipython-input-32-72aee891e885> in <module> 4 # wordvec_arrays.reshape(1,200) 5 for i in range(len(tokenized_tweet)): ----> 6 wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 200) 7 8 wordvec_df = pd.DataFrame(wordvec_arrays) <ipython-input-31-9e6501810162> in word_vector(tokens, size) 4 for word in tokens: 5 try: ----> 6 vec += model_w2v.wv.__getitem__(word).reshape((1, size)) 7 count += 1. 8 except KeyError: # handling the case where the token is not in vocabulary ValueError: cannot reshape array of size 3800 into shape (1,200)
我检查了 stackOverflow 中所有可用的帖子,但没有一个真的对我有帮助。
我尝试重塑数组,但它仍然给我同样的错误。
我的模型是:
tokenized_tweet = df['tweet'].apply(lambda x: x.split()) # tokenizing
model_w2v = gensim.models.Word2Vec(
tokenized_tweet,
size=200, # desired no. of features/independent variables
window=5, # context window size
min_count=2,
sg = 1, # 1 for skip-gram model
hs = 0,
negative = 10, # for negative sampling
workers= 2, # no.of cores
seed = 34)
model_w2v.train(tokenized_tweet, total_examples= len(df['tweet']), epochs=20)
有什么建议吗?
【问题讨论】:
-
如果添加完整的异常消息(所有帧和行),会更清楚哪一行导致异常。而且,您可能会发现,通过在
gensimKeyedVectors类中完成代码的方式对代码进行建模,计算多词向量的均值会更容易。例如,n_similarity()方法在这行代码中对两组词的向量进行平均:github.com/RaRe-Technologies/gensim/blob/… -
我添加了完整的异常消息。
-
感谢您提供更多详细信息! Stlll,我建议采用以我链接的示例代码为模型的更简单的方法。现在添加更多详细信息的答案..
标签: python deep-learning tokenize word2vec word-embedding