【问题标题】:Is the tf-idf of scikit-learn in this example correct? The most frequent words have high score本例中 scikit-learn 的 tf-idf 是否正确?最常用的词得分高
【发布时间】:2019-07-31 12:56:44
【问题描述】:
from sklearn.feature_extraction.text import TfidfVectorizer

documents=["The car is driven on the road","The truck is                  
            driven on the highway","the lorry is"]
fidf_transformer=TfidfVectorizer(smooth_idf=True,use_idf=True)
tfidf=tfidf_transformer.fit_transform(documents)
print(tfidf_transformer.vocabulary_)
print(tfidf.toarray())

{'the': 7, 'car': 0, 'on': 5, 'driven': 1, 'is': 3, 'road':         6, 'lorry': 4, 'truck': 8, 'highway': 2}
[[0.45171082 0.34353772 0. 0.26678769 0.  0.34353772 0.45171082 0.53357537 0.        ]
 [0.         0.34353772 0.45171082 0.26678769 0.         0.34353772 0.         0.53357537 0.45171082]
 [0.         0.         0.         0.45329466 0.76749457 0. 0.         0.45329466 0.        ]]

“the”这个词在三个文档中应该是低分

【问题讨论】:

    标签: tf-idf tfidfvectorizer


    【解决方案1】:

    tfidf = 词频 (tf)* 逆文档频率 (idf)

    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_extraction.text import TfidfTransformer 
    
    vectorizer = CountVectorizer()
    X = vectorizer.fit_transform(documents)
    print(vectorizer.get_feature_names())
    print (X.toarray())
    print ("---")
    t = TfidfTransformer(use_idf=True, norm=None, smooth_idf=False)
    a = t.fit_transform(X)
    print (a.toarray())
    print ("---")
    print (t.idf_)
    

    输出:

    idf(the) 很低,但 tf(the, doc1) = 2 很高,这将其推向了其他词。

    从上面的示例代码:

    的idf(no Norm, non smoothed idf)是====1

    但是 tf(the, doc1) = 2 和 tf(is, doc1) = 1,这会提高 tfidf(the, doc1) 的 tfidf 值。

    类似 idf(car) = 2.09861229 但 tf(car, doc1) = 1, => tfidf(car, doc1) = 2.09861229,非常接近 tfidf(the,doc1)。 idf 的平滑进一步缩小了差距。

    在大型语料库中,差异变得更加突出。

    尝试通过禁用平滑和不归一化来运行您的代码,以查看对小型语料库的影响。

    tfidf_transformer=TfidfVectorizer(smooth_idf=False,use_idf=True, 规范=无)

    【讨论】:

      猜你喜欢
      • 2016-03-17
      • 2018-08-05
      • 2020-01-18
      • 2018-03-23
      • 2016-10-11
      • 2015-02-11
      • 2021-09-14
      • 2016-07-02
      • 2021-02-24
      相关资源
      最近更新 更多