2017-04-04 2 views
0

This questionには、組み込みの英語のストップワードにCountVectorizerという単語を追加する方法が説明されています。私は、トークンとしての数字を取り除くという分類器への影響を見ることに興味があります。scickit-learnのCountVectorizerにstop_wordsを追加する

ENGLISH_STOP_WORDSはフリーズセットとして保存されていますので、凍ったリストに任意の番号represnetationを追加することができますか?

あなたが渡さなければならないリストの良さは、それを排除するので、私の質問はそれが不可能だということです。

私はword.isdigit()が、私はその後、ENGLISH_STOP_WORDSsee previous answer)との連合が、私はむしろだろうことができますセット/リストに真であるテストコーパスとポップの言葉をループするだろうと同じことを達成する1つの方法を想定します怠惰で、より簡単なものをstop_wordsパラメータに渡します。

答えて

2

ストップワードリストを拡張する代わりに、CountVectorizerの顧客preprocessorとして実装することができます。以下は、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} 

正規表現をプリコンパイルすると、多数のサンプルにわたってスピードアップする可能性があります。

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'] 
関連する問題