我根据术语计算了我的文档的 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