2015-03-06 2 views
10

Я установил python 2.7, numpy 1.9.0, scipy 0.15.1 и scikit-learn 0.15.2. Теперь, когда я следующий в Python:CountVectorizer не печатает словарь

train_set = ("The sky is blue.", "The sun is bright.") 
test_set = ("The sun in the sky is bright.", 
"We can see the shining sun, the bright sun.") 

from sklearn.feature_extraction.text import CountVectorizer 
vectorizer = CountVectorizer() 

print vectorizer 


    CountVectorizer(analyzer=u'word', binary=False, charset=None, 
    charset_error=None, 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=None, stop_words=None, 
    strip_accents=None, token_pattern=u'(?u)\\b\\w\\w+\\b', 
    tokenizer=None, vocabulary=None) 

    vectorizer.fit_transform(train_set) 
    print vectorizer.vocabulary 

    None. 

На самом деле он должен быть напечатан следующим образом:

CountVectorizer(analyzer__min_n=1, 
analyzer__stop_words=set(['all', 'six', 'less', 'being', 'indeed', 'over',  
'move', 'anyway', 'four', 'not', 'own', 'through', 'yourselves', (...) --->  
For count vectorizer 

{'blue': 0, 'sun': 1, 'bright': 2, 'sky': 3} ---> for vocabulary 

Приведенный выше код взяты из блога: http://blog.christianperone.com/?p=1589

Не могли бы вы помочь мне, почему я получаю такую ​​ошибку. Поскольку словарь не проиндексирован должным образом, я не могу продвинуться в понимании концепции TF-IDF. Я новичок в python, поэтому любая помощь будет оценена.

Arc.

ответ

13

Вы пропускаете подчеркивание, попробуйте так:

from sklearn.feature_extraction.text import CountVectorizer 
train_set = ("The sky is blue.", "The sun is bright.") 
test_set = ("The sun in the sky is bright.", 
    "We can see the shining sun, the bright sun.") 

vectorizer = CountVectorizer(stop_words='english') 
document_term_matrix = vectorizer.fit_transform(train_set) 
print vectorizer.vocabulary_ 
# {u'blue': 0, u'sun': 3, u'bright': 1, u'sky': 2} 

При использовании IPython оболочки, вы можете использовать автодополнению и вы можете найти более простые методы и атрибуты объектов.

+0

Да. Благодарю. Я попробую использовать оболочку ipython, чтобы я не пропустил такое завершение табуляции. У меня оболочка ipython никогда не знала этого. Спасибо за информацию. – Archana

+0

В приведенном выше я также спросил, как мои остановочные слова = Нет в CountVectorize, которых не должно быть. – Archana

+1

Значение по умолчанию для stop_words равно None. Вы можете создать векторный инструмент следующим образом: vectorizer = CountVectorizer (stop_words = 'english'), если вы хотите использовать встроенные английские слова остановки. –

2

Попробуйте использовать метод vectorizer.get_feature_names(). Он дает имена столбцов в порядке, указанном в document_term_matrix.

from sklearn.feature_extraction.text import CountVectorizer 
train_set = ("The sky is blue.", "The sun is bright.") 
test_set = ("The sun in the sky is bright.", 
    "We can see the shining sun, the bright sun.") 

vectorizer = CountVectorizer(stop_words='english') 
document_term_matrix = vectorizer.fit_transform(train_set) 
vectorizer.get_feature_names() 
#> ['blue', 'bright', 'sky', 'sun'] 
Смежные вопросы