【问题标题】:scikit learn implementation of tfidf differs from manual implementationscikit learn tfidf 的实现不同于手动实现
【发布时间】:2019-07-11 19:35:30
【问题描述】:

我尝试使用公式手动计算tfidf 值,但得到的结果与使用scikit-learn 实现时得到的结果不同。

from sklearn.feature_extraction.text import TfidfVectorizer

tv = TfidfVectorizer()

a = "cat hat bat splat cat bat hat mat cat"
b = "cat mat cat sat"

tv.fit_transform([a, b]).toarray()

# array([[0.53333448, 0.56920781, 0.53333448, 0.18973594, 0.        ,
#             0.26666724],
#            [0.        , 0.75726441, 0.        , 0.37863221, 0.53215436,
#             0.        ]])

tv.get_feature_names()
# ['bat', 'cat', 'hat', 'mat', 'sat', 'splat']

我尝试手动计算文档的tfidf,但结果与TfidfVectorizer.fit_transform 不同。

(np.log(2+1/1+1) + 1) * (2/9) = 0.5302876358044202
(np.log(2+1/2+1) + 1) * (3/9) = 0.750920989498456
(np.log(2+1/1+1) + 1) * (2/9) = 0.5302876358044202
(np.log(2+1/2+1) + 1) * (1/9) = 0.25030699649948535
(np.log(2+1/1+1) + 1) * (0/9) = 0.0
(np.log(2+1/1+1) + 1) * (1/9) = 0.2651438179022101

我应该得到的是

[0.53333448, 0.56920781, 0.53333448, 0.18973594, 0, 0.26666724]

【问题讨论】:

    标签: python scikit-learn tf-idf tfidfvectorizer text-processing


    【解决方案1】:

    有许多 TFIDF 变体。 sklearn使用的公式是:

    (count_of_term_t_in_d) * ((log ((NUMBER_OF_DOCUMENTS + 1) / (Number_of_documents_where_t_appears +1 )) + 1)
    
    
    
    
    2 * (np.log((1 + 2)/(1+1)) + 1) = 2.8109302162163288
    3 * (np.log((1 + 2)/(2+1)) + 1) = 3.0
    2 * (np.log((1 + 2)/(1+1)) + 1) = 2.8109302162163288
    1 * (np.log((1 + 2)/(2+1)) + 1) = 1.0
    0 * (np.log((1 + 2)/(2+1)) + 1) = 0.0
    1 * (np.log((1 + 2)/(1+1)) + 1) = 1.4054651081081644
    

    计算后,最终的 TFIDF 向量通过欧几里得范数进行归一化:

    tfidf_vector = [2.8109302162163288, 3.0, 2.8109302162163288, 1.0, 0.0, 1.4054651081081644]
    
    tfidf_vector = tfidf_vector / np.linalg.norm(tfidf_vector)
    
    print(tfidf_vector)
    
    [0.53333448, 0.56920781, 0.53333448, 0.18973594, 0, 0.26666724]
    

    【讨论】:

    • np.linalg.norm 计算向量的欧几里得范数。欧几里得范数定义为分量平方和的平方根。 np.sqrt(np.sum(tfidf_vector ** 2))
    • 知道了。谢谢.. 你知道关于TFIDFTransformer 的任何事情吗?它与TFIDFVectorizer 有什么不同?这是另一个question 我已经问过这个问题了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2018-05-01
    • 1970-01-01
    • 2018-04-08
    • 2020-06-12
    • 2014-09-03
    • 2015-01-09
    相关资源
    最近更新 更多