python - Scipy、tf-idf 和余弦相似度

标签 python scipy cluster-analysis trigonometry tf-idf

我正在尝试使用 python 根据 tf-idf 矩阵对一些文档进行聚类。

首先,我遵循公式的维基百科定义,使用规范化的 tf. http://en.wikipedia.org/wiki/Tf-idf

Feat_vectors 以二维 numpy 数组开始,行代表文档,列代表术语,每个单元格中的值是每个文档中每个术语的出现次数。

import numpy as np

feat_vectors /= np.max(feat_vectors,axis=1)[:,np.newaxis]
idf = len(feat_vectors) / (feat_vectors != 0).sum(0)
idf = np.log(idf)
feat_vectors *= idf

然后我使用 scipy 对这些向量进行聚类:

from scipy.cluster import hierarchy

clusters = hierarchy.linkage(feat_vectors,method='complete',metric='cosine')
flat_clusters = hierarchy.fcluster(clusters, 0.8,'inconsistent')

然而,在最后一行它抛出一个错误:

ValueError: Linkage 'Z' contains negative distances.

余弦相似度从 -1 到 1。但是,余弦相似度的维基百科页面指出 http://en.wikipedia.org/wiki/Cosine_similarity :

In the case of information retrieval, the cosine similarity of two documents will range >from 0 to 1, since the term frequencies (tf-idf weights) cannot be negative.

因此,如果我得到的是负相似性,那么我似乎在计算 tf-idf 时犯了一些错误。知道我的错误是什么吗?

最佳答案

我怀疑错误在以下行中:

idf = len(feat_vectors) / (feat_vectors != 0).sum(0)

由于您的逻辑向量将在总和中转换为 int,而 len 是 int,因此您正在失去精度。替换为:

idf = float(len(feat_vectors)) / (feat_vectors != 0).sum(0)

为我工作(即用虚拟数据产生了我所期望的)。其他一切看起来都是正确的。

关于python - Scipy、tf-idf 和余弦相似度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13678186/

相关文章:

python - 按字节数划分文件

python - 将数据帧重复合并到数据帧的单列中的优雅而有效的方法

python - python 中的期望值

python - 肘法不同实现方式的比较

python - 大数据集如何比较簇数?

python - Nohup 在 Ubuntu ec2 中运行 selenium web scraper

python - 获取 dateutil.parse 中的格式

machine-learning - 在 Spark 中使用 Silhouette 聚类

python - 如何将 Spacy en_core_web_md 模型放入 Python 包中

python - 使用 curve_fit 的多维拟合,其中函数在网格上