预处理列表列表,使用 map 删除 doc2vec 的停用词而不丢失单词顺序

Preprocessing a list of list removing stopwords for doc2vec using map without losing words order

我正在用 gensim 而不是 word2vec

实现一个简单的 doc2vec

我需要删除停用词而不丢失列表列表的正确顺序。

每个列表都是一个文档,正如我对 doc2vec 的理解,该模型将有一个 TaggedDocuments 列表作为输入

model = Doc2Vec(lst_tag_documents, vector_size=5, window=2, min_count=1, workers=4)

dataset = [['We should remove the stopwords from this example'],
     ['Otherwise the algo'],
     ["will not work correctly"],
     ['dont forget Gensim doc2vec takes list_of_list' ]]

STOPWORDS = ['we','i','will','the','this','from']


def word_filter(lst):
  lower=[word.lower() for word in lst]
  lst_ftred = [word for word in lower if not word in STOPWORDS]
  return lst_ftred

lst_lst_filtered= list(map(word_filter,dataset))
print(lst_lst_filtered)

输出:

[['we should remove the stopwords from this example'], ['otherwise the algo'], ['will not work correctly'], ['dont forget gensim doc2vec takes list_of_list']]

预期输出:

[[' should remove the stopwords   example'], ['otherwise the algo'], [' not work correctly'], ['dont forget gensim doc2vec takes list_of_list']]


提问前我检查过的问题列表:

How to remove stop words using nltk or python

lower 是一个元素的列表,word not in STOPWORDS 将 return False。取列表中带索引的第一项并用空格分隔 space

lst_ftred = ' '.join([word for word in lower[0].split() if word not in STOPWORDS])
# output: ['should remove stopwords example', 'otherwise algo', 'not work correctly', 'dont forget gensim doc2vec takes list_of_list']
# 'the' is also in STOPWORDS

首先,请注意从 Doc2Vec 训练中删除停用词并不那么重要。其次,请注意,如此小的玩具数据集不会从 Doc2Vec 中提供有趣的结果。 Tha 算法,如 Word2Vec,只有在大型数据集上训练时才开始显示其价值(1)比向量维数多得多的唯一词; (2) 每个词的用法都有很多不同的例子 - 至少几个,最好是几十个或几百个。

不过,如果您想去除停用词,最简单的方法是在 对原始字符串进行分词后进行。 (也就是说,将字符串拆分为单词列表。这就是 Doc2Vec 无论如何都需要的格式。)而且,你 想要你的 dataset成为一个列表列表,每个列表只有一个字符串。相反,您希望它是一个字符串列表(首先),然后是一个列表列表,每个列表都有多个标记。

以下应该有效:

string_dataset = [
     'We should remove the stopwords from this example',
     'Otherwise the algo',
     "will not work correctly",
     'dont forget Gensim doc2vec takes list_of_list',
]

STOPWORDS = ['we','i','will','the','this','from']

# Python list comprehension to break into tokens
tokenized_dataset = [s.split() for s in string_dataset]

def filter_words(tokens):
    """lowercase each token, and keep only if not in STOPWORDS"""
    return [token.lower() for token in tokens if token not in STOPWORDS]

filtered_dataset = [filter_words(s) for sent in tokenized_dataset]

最后,因为如上所述,Doc2Vec 需要多个单词示例才能正常工作,所以使用 min_count=1 几乎总是一个坏主意。