[英]gensim.corpora Dictionary type error interprets tokenized column as single string
[英]Sentence returns empty dictionary from gensim.corpora
我正在尝试修改这篇文章中应用 tf-idf 的示例。
from sklearn.datasets import fetch_20newsgroups
from gensim.corpora import Dictionary
from gensim.models.tfidfmodel import TfidfModel
from gensim.matutils import sparse2full
import numpy as np
import spacy
nlp = spacy.load('en_core_web_md')
def keep_token(t):
return (t.is_alpha and
not (t.is_space or t.is_punct or
t.is_stop or t.like_num))
def lemmatize_doc(doc):
return [ t.lemma_ for t in doc if keep_token(t)]
sentences = ['Pro USB and Analogue Microphone']
docs = [lemmatize_doc(nlp(doc)) for doc in sentences]
docs_dict = Dictionary(docs)
docs_dict.filter_extremes(no_below=20, no_above=0.2)
docs_dict.compactify()
docs_corpus = [docs_dict.doc2bow(doc) for doc in docs]
model_tfidf = TfidfModel(docs_corpus, id2word=docs_dict)
docs_tfidf = model_tfidf[docs_corpus]
docs_vecs = np.vstack([sparse2full(c, len(docs_dict)) for c in docs_tfidf])
tfidf_emb_vecs = np.vstack([nlp(docs_dict[i]).vector for i in range(len(docs_dict))])
docs_emb = np.dot(docs_vecs, tfidf_emb_vecs)
But I'm getting this error:
282 _warn_for_nonsequence(tup)
--> 283 return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
284
285
ValueError: need at least one array to concatenate
原因是这一行正在重新调整一个空列表:
docs_corpus = [docs_dict.doc2bow(doc) for doc in docs]
docs_corpus
这是因为字典是空的:
但是我用一个非空列表来喂 dic
这就是我找不到失败原因的部分
问题出在这一行:
docs_dict.filter_extremes(no_below=20, no_above=0.2)
no_below=20
表示将整个语料库中计数小于 20 的所有标记从字典中删除。 no_above=0.2
意味着出现在超过 20% 的文档中的所有标记都将从字典中删除。 由于您在示例中只使用了一个玩具文档集,因此您的所有标记都将被过滤。 只需在使用玩具文档集时注释该行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.