繁体   English   中英

如何获得排名余弦相似度?

[英]How to get the ranked cosine similarity?

我有类似于以下的数据:

TYPES|LABELS
Type1|Label1 Label2 Label4 Label5
Type2|Label2 Label5 Label6 Label8
Type3|Label2 Label5 Label6 Label7
Type4|Label1 Label2 Label4 Label5

在某些情况下,我有如下代码来处理我如何可视化集群:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity

cv = CountVectorizer()
count_matrix = cv.fit_transform(df["LABELS"])
print("Count Matrix:", count_matrix.toarray())

cosine_sim = cosine_similarity(count_matrix)

fg = sns.clustermap(cosine_sim,figsize=(12, 12),method='average')
ax = fg.ax_heatmap
labels = [df.iloc[int(i.get_text())]['TYPES'] for i in list(ax.get_xticklabels())]
ax.set_xticklabels([],rotation=90,fontsize=14)
ax.set_yticklabels(labels,rotation=0,fontsize=14)

倒数第三行是我分配标签的有点骇人听闻的方式,因此它们向我展示了 clustermap 上的所有内容对应的内容。

但我还希望看到具有最强余弦相似性的类型作为 DataFrame 中的排名,我不知道该怎么做。

这将是......(编造一些数字)

Pairs|Cosine_Similarity
(Type1,Type4)|0.8
(Type2,Type3)|0.7
...
perm = permutations(range(0,len(df)), 2)
cor_dic = {}
for i in list(perm):
  if (df['TYPES'].iloc[i[1]],df['TYPES'].iloc[i[0]]) not in cor_dic.keys():
    cor_dic[(df['TYPES'].iloc[i[0]],df['TYPES'].iloc[i[1]])] = round(cosine_sim[i[0],i[1]],4)
df_cor = pd.DataFrame.from_dict(cor_dic,orient='index').reset_index().rename(columns={'index':'TYPES',0:'Correlation'}).sort_values(['Correlation'],ascending=False).reset_index(drop=True)
df_cor

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM