Skip to main content
 首页 » 编程设计

python之在 python 中使用 matplotlib 绘制相似性度量

2024年10月25日11dflying

我正在开展一个项目,使用 tf-idf 度量来寻找两个句子/文档之间的相似性。

我尝试了以下示例代码:

from sklearn.feature_extraction.text import TfidfVectorizer 
from sklearn.metrics.pairwise import cosine_similarity   
 
documents = ( 
"The sky is blue", 
"The sun is bright" 
) 
tfidf_vectorizer = TfidfVectorizer() 
tfidf_matrix = tfidf_vectorizer.fit_transform(documents) 
cosine = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix) 
print cosine 

两个句子的相似度为

[[ 1.          0.33609693]] 

现在我的问题是如何以图形/可视化格式显示相似性。 类似于维恩图,其中交集值成为相似性度量或 matplotlib 或任何 python 库中可用的任何其他图。

提前致谢

请您参考如下方法:

绘制维恩图的最简单方法是绘制两个半径为 r 且中心距离为 d = 2 * r * (1 - cosine[0][i ]),其中 i 是您要比较的行索引。如果句子相同,则 d == 0 is True,即两个圆圈相同。如果这两个句子没有任何共同点,则您有 d == 2*r is True,因此圆圈是分离的(它们在一点接触)。

The code to draw circles is already present in StackOverflow.

编辑: 此方法根据您的代码输出绘制维恩图:

## import matplotlib for plotting the Venn diagram 
import matplotlib.pyplot as plt 
 
## output of your first part 
cosine = [[ 1., 0.33609693]] 
 
## set constants 
r = 1 
d = 2 * r * (1 - cosine[0][1]) 
 
## draw circles 
circle1=plt.Circle((0, 0), r, alpha=.5) 
circle2=plt.Circle((d, 0), r, alpha=.5) 
## set axis limits 
plt.ylim([-1.1, 1.1]) 
plt.xlim([-1.1, 1.1 + d]) 
fig = plt.gcf() 
fig.gca().add_artist(circle1) 
fig.gca().add_artist(circle2) 
## hide axes if you like 
# fig.gca().get_xaxis().set_visible(False) 
# fig.gca().get_yaxis().set_visible(False) 
fig.savefig('venn_diagramm.png') 

绘制圆圈时设置 alpha 值使它们看起来半透明。因此,重叠部分的不透明度是圆圈非重叠部分的两倍。