【问题标题】:Plotting Similarity measure using matplotlib in python在 python 中使用 matplotlib 绘制相似度度量
【发布时间】:2014-12-23 10:30:01
【问题描述】:

我正在研究使用 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 库中可用的任何其他图。

提前致谢

【问题讨论】:

    标签: python matplotlib visualization similarity


    【解决方案1】:

    绘制维恩图的最简单方法是绘制两个圆,半径为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 值会使它们看起来是半透明的。因此,重叠部分的不透明性是圆的非重叠部分的两倍。

    【讨论】:

    • 圆的半径应该是多少,应该有2个圆..那么它们的半径应该相同吗?如何确定圆心?
    • 两者都是你的选择!如果您为第一个圆选择 (0,0),则您将 (d,0) 或 (0,d) 作为第二个圆的中心。如果您不知道 r,请将其设置为 1。
    • 那么这里的d值如何帮助显示交集。你能用数据或代码示例解释一下吗
    • 我试着给你一些提示。您要对其进行编码?您是否按照链接问题中接受的答案进行操作?
    • d 值如何帮助显示交点,如果 d 变为 0,则该点不清楚,则无法绘制圆,那么如何显示 2 个圆
    猜你喜欢
    • 2015-02-21
    • 2015-10-07
    • 2014-10-06
    • 2020-10-14
    • 1970-01-01
    • 2017-03-13
    • 2021-09-01
    • 1970-01-01
    • 2017-07-06
    相关资源
    最近更新 更多