python - scikit learn tfidf 的实现不同于手动实现
问题描述
我尝试使用公式手动计算值,但得到的结果与使用scikit-learn实现tfidf
时得到的结果不同。
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]
解决方案
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]
推荐阅读
- angular - 模块构建失败(来自 ./node_modules/@angular-devkit/build-angular/node_modules/mini-css-extract-plugin/dist/loader.js)
- mysql - 在 MySQL 报告中为漏斗报告格式化数据
- python-3.x - 升级到 pip 版本 19.3.1
- crystal-lang - 如何通过方法在水晶中阻止
- java - 不兼容的类型:单
无法转换为 Completable - c# - 从 ActionFilterAttribute 重定向到自定义错误页面
- android - 每次我保存时,Visual Studio 都会删除 AXML 布局!!!!VS 错误?
- laravel - 在 Laravel 中通过 GET 传递 id 的问题
- python - model.fit() Keras 分类多输入-单输出给出错误:AttributeError: 'NoneType' object has no attribute 'fit'
- grails - 升级到 Grails 4 后无法停止运行 grails 应用程序