首页 > 解决方案 > TfidfVectorizer 如何接受他的论点?

问题描述

我想更好地了解 TfidfVectorizer 的工作原理。我不明白如何使用后续功能,例如get_feature_name

这是我的问题的可重现示例:

from sklearn.feature_extraction.text import TfidfVectorizer

text = ['It was a queer, sultry summer', 'the summer they electrocuted the Rosenbergs',
    'and I didn’t know what I was doing in New York', 'I m stupid about executions',
    'The idea of being electrocuted makes me sick',
    'and that’s all there was to read about in the papers',
    'goggle eyed headlines staring up at me on every street corner and at the fusty',
    'peanut-selling mouth of every subway', 'It had nothing to do with me',
    'but I couldn’t help wondering what it would be like',
    'being burned alive all along your nerves']


tfidf_vect = TfidfVectorizer(max_df=0.7,
                                 min_df= 0.01,
                                 use_idf=True,
                                 ngram_range=(1,2)) 

tfidf_mat = tfidf_vect.fit_transform(text)
print(tfidf_mat)
features = tfidf_vect.get_feature_names()
print(features)

在这个例子中,我认为我的对象tfidf_vect定义了我想要的应用程序的所有参数TfidfVectorizer,然后我将其应用于text,以获得对象中的结果tfidf_mat

我不明白为什么,为了提取我的 tfidf 分析的附加信息,我将函数应用于对象tfidf_vect而不是tfidf_mat.

如果未在其定义中指定,该命令如何tfidf_vect.get_feature_names() 知道这将应用于?text

标签: pythonscikit-learntf-idftfidfvectorizer

解决方案


该命令tfidf_vect.get_feature_names()有效,因为tfidf_vect它是类的一个实例TfidfVectorizer。此类具有某些属性(请参阅文档)。这些属性可以在调用类的方法后发生变化,例如 method fit_transform。现在,get_feature_names可以访问与方法相同的类实例属性fit_transform。您可能想阅读更多关于、方法、属性等的信息。

所以:简单地保存(它是(n_samples,n_features)的稀疏矩阵)tfidf_mat的返回值。fit_transform()调用 后fit_transform()tfidf_vect的属性会发生变化,可以通过该类实例的任何方法访问(也可以通过get_feature_names())。


推荐阅读