파이썬을 사용하여 tf-idf 행렬에 따라 일부 문서를 클러스터링하려고합니다.Scipy, tf-idf 및 코사인 유사도
먼저 정규화 된 tf를 사용하여 공식의 위키 피 디아 정의를 따릅니다. http://en.wikipedia.org/wiki/Tf-idf
Feat_vectors 각 셀에서 문서를 나타내는 행과 조건을 나타내는 열 값이 각 문서 내의 각 용어의 발생 횟수 인 상태 NumPy와 이차원 배열로 시작한다.
ValueError: Linkage 'Z' contains negative distances.
코사인 유사도가 -1 그러나 1로 간다 : 그것은 오류가 발생합니다 마지막 줄에,
from scipy.cluster import hierarchy
clusters = hierarchy.linkage(feat_vectors,method='complete',metric='cosine')
flat_clusters = hierarchy.fcluster(clusters, 0.8,'inconsistent')
그러나 :
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를 사용하여 이러한 벡터를 클러스터 , 코사인 유사성 상태에 대한 위키 백과 페이지 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로 변환 될 것입니다 때문에, 그리고 렌, 당신은 정밀도를 잃고있는 int입니다 :
'feat_vectors'에 음수 값이있는 것 같습니다. 'idf'로 곱하기 전에, 또는'np.log'를 취하기 전에 idf는 1보다 낮은 값을가집니다. – tiago
행렬의 최소값은 0입니다. 코사인 유사성의 결과는 <0입니다. – Fergusmac