2

这个问题解释了如何将自己的单词添加到内置的英文停用词中CountVectorizer。我有兴趣看到消除任何数字作为标记对分类器的影响。

ENGLISH_STOP_WORDS存储为冻结集,所以我想我的问题归结为(除非有我不知道的方法)是否可以将任意数字表示添加到冻结列表中?

我对这个问题的感觉是这是不可能的,因为您必须通过的列表的有限性排除了这一点。

我想完成同样事情的一种方法是循环测试语料库和流行词,其中word.isdigit()对我可以联合的集合/列表是正确的ENGLISH_STOP_WORDS见上一个答案),但我宁愿懒惰并传递一些东西参数更简单stop_words

4

2 回答 2

3

您可以将其作为自定义preprocessor来实现,而不是扩展停用词列表CountVectorizer。下面是一个简单的版本,如图所示bpython

>>> import re
>>> cv = CountVectorizer(preprocessor=lambda x: re.sub(r'(\d[\d\.])+', 'NUM', x.lower()))
>>> cv.fit(['This is sentence.', 'This is a second sentence.', '12 dogs eat candy', '1 2 3 45'])
CountVectorizer(analyzer=u'word', binary=False, decode_error=u'strict',
        dtype=<type 'numpy.int64'>, encoding=u'utf-8', input=u'content',
        lowercase=True, max_df=1.0, max_features=None, min_df=1,
        ngram_range=(1, 1),
        preprocessor=<function <lambda> at 0x109bbcb18>, stop_words=None,
        strip_accents=None, token_pattern=u'(?u)\\b\\w\\w+\\b',
        tokenizer=None, vocabulary=None)
>>> cv.vocabulary_
{u'sentence': 6, u'this': 7, u'is': 4, u'candy': 1, u'dogs': 2, u'second': 5, u'NUM': 0, u'eat': 3}

预编译正则表达式可能会给大量样本带来一些加速。

于 2017-07-11T02:44:09.630 回答
1
import re
from sklearn.feature_extraction.text import CountVectorizer

list_of_texts = ['This is sentence.', 'This is a second sentence.', '12 dogs eat candy', '1 2 3 45']

def no_number_preprocessor(tokens):
    r = re.sub('(\d)+', 'NUM', tokens.lower())
    # This alternative just removes numbers:
    # r = re.sub('(\d)+', '', tokens.lower())
    return r

for t in list_of_texts:
    no_num_t = no_number_preprocessor(t)
    print(no_num_t)

cv = CountVectorizer(input='content', preprocessor=no_number_preprocessor)
dtm = cv.fit_transform(list_of_texts)
cv_vocab = cv.get_feature_names()

print(cv_vocab)

出局

this is sentence.

this is a second sentence.

NUM dogs eat candy

NUM NUM NUM NUM

['NUM', 'candy', 'dogs', 'eat', 'is', 'second', 'sentence', 'this']
于 2017-11-30T23:25:52.320 回答