本文介绍了scikit学习tfidf的实现与手动实现不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用公式手动计算tfidf值,但获得的结果与使用 scikit-learn 实现.

I tried to manually calculate tfidf values using the formula but the result I got is different from the result I got when using scikit-learn implementation.

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不同.

I tried to manually calculate tfidf for document but result is different from 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]

推荐答案

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

There are many variations of TFIDF. The formula used by sklearn is:

(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向量通过欧几里得范数归一化:

After the calculation, the final TFIDF vector is normalized by the Euclidean norm:

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]

这篇关于scikit学习tfidf的实现与手动实现不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:19