【问题标题】:Finding cosine similarity between 2 numbered datasets using Python使用 Python 查找 2 个编号数据集之间的余弦相似度
【发布时间】:2014-10-10 09:22:15
【问题描述】:

我对长度为 22 的数据集进行了编号,其中每个数字可以位于 0 到 1 之间,代表该属性的百分比。

[0.03, 0.15, 0.58, 0.1, 0, 0, 0.05, 0, 0, 0.07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0]


[0.9, 0, 0.06, 0.02, 0, 0, 0, 0, 0.02, 0, 0, 0.01, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0]


[0.01, 0.07, 0.59, 0.2, 0, 0, 0, 0, 0, 0.05, 0, 0, 0, 0, 0, 0, 0.07, 0, 0, 0, 0, 0]


[0.55, 0.12, 0.26, 0.01, 0, 0, 0, 0.01, 0.02, 0, 0, 0.01, 0, 0, 0.01, 0, 0.01, 0, 0, 0, 0, 0]


[0, 0.46, 0.43, 0.05, 0, 0, 0, 0, 0, 0, 0, 0.02, 0, 0, 0, 0, 0.02, 0.02, 0, 0, 0, 0]

如何使用 Python 计算这两个数据集之间的余弦相似度?

【问题讨论】:

    标签: python similarity cosine-similarity


    【解决方案1】:

    根据Cosine similarity的定义,只需要计算ab这两个向量的归​​一化点积即可:

    import numpy as np
    
    a = [0.03, 0.15, 0.58, 0.1, 0, 0, 0.05, 0, 0, 0.07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0]
    b = [0.9, 0, 0.06, 0.02, 0, 0, 0, 0, 0.02, 0, 0, 0.01, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0]
    
    print np.dot(a, b) / np.linalg.norm(a) / np.linalg.norm(b)
    

    输出:

    0.115081383219
    

    【讨论】:

      【解决方案2】:

      不依赖于 numpy,你可以使用

      result = (sum(ax*bx for ax, bx in a, b) /
                (sum(ax**2 for ax in a) +
                 sum(bx**2 for bx in b))**0.5)
      

      【讨论】:

        【解决方案3】:

        你可以直接从sklearn使用方法

        import numpy as np
        from sklearn.metrics.pairwise import cosine_similarity
        cosine_similarity(np.asmatrix([1,2,3]), np.asmatrix([4,5,6]))[0][0]
        

        输出

        0.97463184619707621
        

        注意(由于numpy 方法通常对矩阵进行操作) 如果你不使用 np.asmatrix(),你会得到如下警告

        DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample
        

        为了得到一个标量的最终值,你需要在输出上使用[0][0]

        【讨论】:

          猜你喜欢
          • 2016-04-11
          • 2011-02-01
          • 2017-12-05
          • 1970-01-01
          • 2022-10-12
          • 2021-02-22
          • 2018-09-27
          • 2015-12-05
          • 2014-11-02
          相关资源
          最近更新 更多