3

我根据术语计算了我的文档的 tf-idf。然后,我应用 LSA 来降低术语的维数。'similarity_dist' 包含负值(见下表)。如何计算范围为 0-1 的余弦距离?

tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, tokenizer=tokenize_and_stem, stop_words='english')
%time tf = tf_vectorizer.fit_transform(descriptions)
print(tf.shape)
svd  = TruncatedSVD(100)
normalizer = Normalizer(copy=False)
lsa = make_pipeline(svd, normalizer)
tfidf_desc = lsa.fit_transform(tfidf_matrix_desc)
explained_variance = svd.explained_variance_ratio_.sum()
print("Explained variance of the SVD step: {}%".format(int(explained_variance * 100)))

similarity_dist = cosine_similarity(tfidf_desc)
pd.DataFrame(similarity_dist,index=descriptions.index, columns=descriptions.index).head(10)

print(tfidf_matrix_desc.min(),tfidf_matrix_desc.max())
#0.0 0.736443429828

print(tfidf_desc.min(),tfidf_desc.max())
#-0.518015429416 0.988306783341

print(similarity_dist.max(),similarity_dist.min())
#1.0 -0.272010919022

在此处输入图像描述

4

1 回答 1

9

cosine_similarity 在 -1 到 1 的范围内

余弦距离定义为:

cosine_distance = 1 - cosine_similarity 

因此 cosine_distance 将在以下范围内:0 到 2

https://en.wikipedia.org/wiki/Cosine_similarity

余弦距离是一个常用于正空间补的术语,即:D_C(A,B) = 1 - S_C(A,B)。

注意:如果必须0 到 1 的范围内,可以使用 cosine_distance / 2

于 2016-05-26T08:27:14.663 回答