CountVectorizer不打印词汇表

时间:2015-03-06 08:23:40

标签: python numpy scipy

我安装了python 2.7,numpy 1.9.0,scipy 0.15.1和scikit-learn 0.15.2。 现在当我在python中执行以下操作时:

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的新手,所以任何帮助都会受到赞赏。

电弧

2 个答案:

答案 0 :(得分:16)

你缺少一个下划线,试试这个:

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 shell,你可以使用tab完成,你可以更容易地找到对象的方法和属性。

答案 1 :(得分:4)

尝试使用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']