Skip to main content
 首页 » 编程设计

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

2025年05月04日14cyq1162

我正在尝试使用 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) 

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