【问题标题】:How to know specific TF-IDF value of a word?如何知道一个词的具体 TF-IDF 值?
【发布时间】:2017-08-28 17:26:10
【问题描述】:

如何使用 TfidfVectorizer 函数知道特定单词的值? 比如我的代码是:

docs = []
docs.append("this is sentence number one")
docs.append("this is sentence number two")
vectorizer = TfidfVectorizer(norm='l2',min_df=0, use_idf=True, smooth_idf=True, stop_words='english', sublinear_tf=True)
sklearn_representation = vectorizer.fit_transform(docs)

现在,我如何知道句子 2(docs[1])中“句子”的 TF-IDF 值?

【问题讨论】:

    标签: python scikit-learn nlp tf-idf


    【解决方案1】:

    您需要使用vectorizervocabulary_ 属性,这是术语到特征索引的映射。

    >>> from sklearn.feature_extraction.text import TfidfVectorizer
    >>> docs = []
    >>> docs.append("this is sentence number one")
    >>> docs.append("this is sentence number two")
    >>> vectorizer = TfidfVectorizer(norm='l2',min_df=0, use_idf=True, smooth_idf=True, stop_words='english', sublinear_tf=True)
    >>> x = vectorizer.fit_transform(docs)
    >>> x.todense()
    matrix([[ 0.70710678,  0.70710678],
            [ 0.70710678,  0.70710678]])
    >>> vectorizer.vocabulary_['sentence']
    1
    >>> c = vectorizer.vocabulary_['sentence']
    >>> x[:,c]
    <2x1 sparse matrix of type '<class 'numpy.float64'>'
        with 2 stored elements in Compressed Sparse Row format>
    >>> x[:,c].todense()
    matrix([[ 0.70710678],
            [ 0.70710678]])
    

    【讨论】:

    • vectorizer.vocabulary_['sentence'] 做了什么?我怎样才能只得到一个值?只有特定文档中该单词的 TF-IDF 值
    • @Skinish 正如我所解释的,vocabulary_ 属性是术语到特征索引的映射(即dict)。在您的 X 矩阵中,列对应于特征,行对应于文档。您有该列,因此如果您只想要 1 行,请选择相应的行。 x[:, c] 选择所有行。例如,如果您想要第一个,您可以使用x[0, c]
    • 太棒了!非常感谢!
    猜你喜欢
    • 2018-08-05
    • 2019-11-16
    • 2014-07-22
    • 2018-03-23
    • 2019-04-17
    • 2018-05-27
    • 1970-01-01
    • 2020-05-11
    • 2019-06-12
    相关资源
    最近更新 更多