【问题标题】:Get selected feature names TFIDF Vectorizer获取选定的特征名称 TFIDF Vectorizer
【发布时间】:2017-07-20 09:17:55
【问题描述】:

我正在使用 python,我想获取大量数据的 TFIDF 表示,我正在使用以下代码将文档转换为它们的 TFIDF 形式。

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(
    min_df=1,  # min count for relevant vocabulary
    max_features=4000,  # maximum number of features
    strip_accents='unicode',  # replace all accented unicode char 
    # by their corresponding  ASCII char
    analyzer='word',  # features made of words
    token_pattern=r'\w{1,}',  # tokenize only words of 4+ chars
    ngram_range=(1, 1),  # features made of a single tokens
    use_idf=True,  # enable inverse-document-frequency reweighting
    smooth_idf=True,  # prevents zero division for unseen words
    sublinear_tf=False)

tfidf_df = tfidf_vectorizer.fit_transform(df['text'])

这里我传递了一个参数max_features。矢量化器将选择最佳特征并返回一个 scipy 稀疏矩阵。问题是我不知道选择了哪些功能以及如何将这些功能名称映射回我得到的 scipy 矩阵?基本上对于m 文档数量中的n 选定特征,我想要一个m x n 矩阵,其中选定特征作为列名而不是它们的整数ID。我该如何做到这一点?

【问题讨论】:

    标签: python scikit-learn nlp


    【解决方案1】:

    您可以使用tfidf_vectorizer.get_feature_names()。这将打印从原始文档中选择的特征名称(选择的术语)。

    您还可以使用tfidf_vectorizer.vocabulary_ 属性来获取一个字典,它将功能名称映射到它们的索引,但不会被排序。来自get_feature_names() 的数组将按索引排序。

    【讨论】:

    • vocabulary_ 属性用于矢量化器而不是转换后的矩阵。
    • get_feature_names() 是否有任何参数让我们一睹为快?
    • @InsParbo 什么样的一瞥? get_feature_names() 将返回词汇表中使用的单词数组。
    • @VivekKumar 喜欢只显示整个数组的少数结果。
    • @InsParbo 您可以对 arr[:5] 等数组使用切片来显示前 5 个值。它只是一个数组,你想怎么看就怎么看。
    【解决方案2】:

    使用tfidf_vectorizer.vocabulary_,这给出了从特征(术语返回到索引)的映射

    【讨论】:

    • tfidf_df.vocabulary_ 给我一个属性错误。但是我可以使用tfidf_vectorizer.vocabulary_ 获得功能,这是您的意思吗?
    • 是的,我进行了编辑以反映更改,但看起来使用 get_feature_names() 是一个更好的解决方案。
    猜你喜欢
    • 2018-11-22
    • 2016-05-27
    • 2017-06-03
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2020-07-27
    • 2019-06-30
    • 2016-05-24
    相关资源
    最近更新 更多