- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在使用 scikit-learn
来查找 tf-idf
值。
我有一组文档
,例如:
D1 = "The sky is blue."
D2 = "The sun is bright."
D3 = "The sun in the sky is bright."
我想创建一个这样的矩阵:
Docs blue bright sky sun
D1 tf-idf 0.0000000 tf-idf 0.0000000
D2 0.0000000 tf-idf 0.0000000 tf-idf
D3 0.0000000 tf-idf tf-idf tf-idf
所以,我在 Python
中的代码是:
import nltk
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.corpus import stopwords
train_set = ["sky is blue", "sun is bright", "sun in the sky is bright"]
stop_words = stopwords.words('english')
transformer = TfidfVectorizer(stop_words=stop_words)
t1 = transformer.fit_transform(train_set).todense()
print t1
我得到的结果矩阵是:
[[ 0.79596054 0. 0.60534851 0. ]
[ 0. 0.4472136 0. 0.89442719]
[ 0. 0.57735027 0.57735027 0.57735027]]
如果我进行手算,那么矩阵应该是:
Docs blue bright sky sun
D1 0.2385 0.0000000 0.0880 0.0000000
D2 0.0000000 0.0880 0.0000000 0.0880
D3 0.0000000 0.058 0.058 0.058
我正在计算像 blue
作为 tf
= 1/2 = 0.5
和 idf
作为 log(3/1) = 0.477121255
。因此 tf-idf = tf*idf = 0.5*0.477 = 0.2385
。通过这种方式,我正在计算其他 tf-idf
值。现在,我想知道,为什么我在手算矩阵和 Python 矩阵中得到不同的结果?哪个给出了正确的结果?是我手算有问题还是我的 Python 代码有问题?
最佳答案
有两个原因:
根据 source sklearn 不使用此类假设。
首先,它平滑了文档计数(因此永远不会有 0
):
df += int(self.smooth_idf)
n_samples += int(self.smooth_idf)
它使用自然对数 (np.log(np.e)==1
)
idf = np.log(float(n_samples) / df) + 1.0
还应用了默认的 l2
规范化。简而言之,scikit-learn 在计算 tfidf 时做了更多“不错的小事”。这些方法(他们的或你的)都不是坏事。他们只是更先进。
关于python - 使用 scikit-learn 和手工计算的 tf-idf 矩阵值的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24032485/
我想学习如何手工计算散列(比如用纸和铅笔)。这可行吗?任何有关从哪里了解这一点的指示都将不胜感激。 最佳答案 这取决于你想做的散列。您可以非常轻松地手动执行一个非常简单的散列——例如,一个简单的散列是
我正在为 IDA Pro 编写脚本使用 idapython 在 Python 中进行反汇编插入。使用它,我能够填补 IDA 自动分析不足的空白。 让我感到难过的一个领域是用(需要一个更好的术语)“漂亮
我找到了一个展示如何手动计算 LCC 的示例(见图)。 如何在 R 中复制这些步骤?重点是找到“邻居之间的实际链接数”(中间步骤) 我最好手动计算一下 *igraph包有提供这个数字吗? 示例邻接矩阵
我正在尝试像 Apple 的 TextSizingExample 那样手动组装 NSTextView 并发现一个无聊的错误。如果您运行 TextSizingExample 并选择“环绕滚动文本”模式,
我想手动制作 TLS 客户端 Hello 消息或至少使用 OkHttp 客户端指定下一个值: TLS 版本 密码 扩展 椭圆曲线 椭圆曲线点格式 可能吗? 最佳答案 见 https://square.
我是一名优秀的程序员,十分优秀!