【发布时间】:2019-02-08 06:35:50
【问题描述】:
我正在研究一个 NLP 问题,我的目标是在通过 Python 的 Gensim 库使用 Word2Vec 后能够将我的数据传递到 sklearn 的算法中。我试图解决的潜在问题是一系列推文的二进制分类。为此,我正在修改this git repo 中的代码。
这是与标记化相关的部分代码:
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
input_file["tokens"] = input_file["text"].apply(tokenizer.tokenize)
all_words = [word for tokens in input_file["tokens"] for word in tokens]
sentence_lengths = [len(tokens) for tokens in input_file["tokens"]]
vocabulary = sorted(set(all_words))
现在这里是我使用 Gensim 的 sklearn-api 来尝试矢量化我的推文的部分:
from sklearn.model_selection import train_test_split
from gensim.test.utils import common_texts
from gensim.sklearn_api import W2VTransformer
text = input_file["text"].tolist()
labels = input_file["label"].tolist()
X_train, X_test, y_train, y_test = train_test_split(text, labels, test_size=0.2,random_state=40)
model = W2VTransformer(size=10, min_count=1, seed=1)
X_train_w2v = model.fit(common_texts).transform(X_train)
这会导致以下错误:
KeyError: "word 'Great seeing you again, don't be a stranger!' not in vocabulary"
问题的一部分似乎是 Gensim 期望一次只输入一个词,而不是收到整个推文。
X_train 是列表类型,这里是列表的前三个元素:
["Great seeing you again, don't be a stranger!",
"Beautiful day here in sunny Prague. Not a cloud in the sky",
" pfft! i wish I had a laptop like that"]
更新
为了解决这个问题,我尝试了以下方法:
X_train_list = []
for sentence in X_train:
word_list = sentence.split(' ')
while("" in word_list):
word_list.remove("")
X_train_list.append(word_list)
model = W2VTransformer(size=10, min_count=1, seed=1)
X_train_tfidf = model.fit(common_texts).transform(X_train_list)
这会产生以下错误:
KeyError: "word 'here' not in vocabulary"
说实话,这让我大吃一惊!像“这里”这样的常用词怎么不在词汇表中,这超出了我的理解。还想知道带有杂散字母的推文是否会引发错误,我想通常作为单词的奇怪的字母混乱会导致类似的问题。
【问题讨论】:
标签: python nlp gensim word2vec topic-modeling