【问题标题】:Difference between vocabulary and get_features() of TfidfVectorizer?TfidfVectorizer的词汇表和get_features()之间的区别?
【发布时间】:2019-06-17 12:21:16
【问题描述】:

我有

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Train the vectorizer
text="this is a simple example"
singleTFIDF = TfidfVectorizer(ngram_range=(1,2)).fit([text])
singleTFIDF.vocabulary_ # show the word-matrix position pairs

# Analyse the training string - text
single=singleTFIDF.transform([text])
single.toarray()  

我想将每个值关联到单个相应的功能中。 现在单机是什么结构?如何将单个值的位置映射到特征?

如何解释词汇表和 get_features() 的索引?他们有关系吗?根据文档,两者都具有索引功能。这很混乱?

【问题讨论】:

    标签: python scikit-learn tfidfvectorizer


    【解决方案1】:

    属性vocabulary_输出一个字典,其中所有的ngram都是字典键,各自的值是tfidf矩阵中每个ngram(特征)的列位置。 get_feature_names() 方法输出一个列表,其中 ngram 根据每个特征的列位置出现。因此,您可以使用其中任何一个来确定哪个 tfidf 列对应于哪个功能。在下面的示例中,使用 get_feature_names() 的输出来命名列,可以轻松地将 tfidf 矩阵转换为 pandas 数据框。另请注意,所有值都具有相同的权重,并且所有权重的平方和等于 1。

    singleTFIDF.vocabulary_
    Out[41]: 
    {'this': 5,
     'is': 1,
     'simple': 3,
     'example': 0,
     'this is': 6,
     'is simple': 2,
     'simple example': 4}
    
    singleTFIDF.get_feature_names_out()
    Out[42]: ['example', 'is', 'is simple', 'simple', 'simple example', 'this', 'this is']
    
    import pandas as pd
    df = pd.DataFrame(single.toarray(), columns=singleTFIDF.get_feature_names())
    
    df
    Out[48]: 
        example        is  is simple    simple  simple example      this   this is
    0  0.377964  0.377964   0.377964  0.377964        0.377964  0.377964  0.377964
    

    【讨论】:

    • 啊,我明白了。 get_features 输出的顺序与 tfidf 矩阵中的列顺序相同吗?实际上,我不了解单个(不是 toarray)的输出。我有像 (0,99) 0.045 这样的行所以最后一列是我认为的权重,但是元组是关于什么的?谢谢!
    • single 的输出只是对象信息:' 的稀疏矩阵,包含 7 个压缩稀疏行格式的存储元素>。可能值得再次运行代码来验证这一点。我无法重现您评论过的 (0,99) 0.045。
    • 实际上,print(single) 输出与 single.toarray() 相同的信息,但格式略有不同——索引元组(行、列)和每个特征的相应权重: print(single )(0,6)0.3779644730092272(0,5)0.3779644730092272(0,4)0.3779644730092272(0,3)0.3779644730092272(0,2)0.3779644730092272(0,1)0.3779644730092272(0,0)0.3779644730092272 跨度>
    • Pandas 和 tfidf 对象有多种处理数据的方法,但如果没有详细描述您的目标,则无法为您提供帮助。请考虑发布另一个问题。
    • 什么意思 - 什么是 idf_?
    猜你喜欢
    • 2020-06-04
    • 2015-12-13
    • 2017-01-21
    • 2014-03-04
    • 1970-01-01
    • 2018-07-07
    • 2012-08-22
    相关资源
    最近更新 更多