给定余弦相似度创建随机向量

时间:2018-10-21 15:05:32

标签: python numpy cosine-similarity

基本上给定了向量v,我想得到另一个随机向量w,在v和w之间有一些余弦相似性。有什么办法可以在python中获得它?

示例:为简单起见,我将具有v [3,-4]的2D向量。我想获得余弦相似度为60%或加0.6的随机向量w。这将生成具有值[0.875,3]的向量w或具有相同余弦相似度的任何其他向量。所以我希望这足够清楚。

2 个答案:

答案 0 :(得分:3)

给定向量v和余弦相似度costheta(-1和1之间的标量),像函数w中一样计算rand_cos_sim(v, costheta)

import numpy as np


def rand_cos_sim(v, costheta):
    # Form the unit vector parallel to v:
    u = v / np.linalg.norm(v)

    # Pick a random vector:
    r = np.random.multivariate_normal(np.zeros_like(v), np.eye(len(v)))

    # Form a vector perpendicular to v:
    uperp = r - r.dot(u)*u

    # Make it a unit vector:
    uperp = uperp / np.linalg.norm(uperp)

    # w is the linear combination of u and uperp with coefficients costheta
    # and sin(theta) = sqrt(1 - costheta**2), respectively:
    w = costheta*u + np.sqrt(1 - costheta**2)*uperp

    return w

例如,

In [17]: v = np.array([3, -4])

In [18]: w = rand_cos_sim(v, 0.6)

In [19]: w
Out[19]: array([-0.28, -0.96])

验证余弦相似度:

In [20]: v.dot(w)/(np.linalg.norm(v)*np.linalg.norm(w))
Out[20]: 0.6000000000000015

In [21]: w = rand_cos_sim(v, 0.6)

In [22]: w
Out[22]: array([1., 0.])

In [23]: v.dot(w)/(np.linalg.norm(v)*np.linalg.norm(w))
Out[23]: 0.6

返回值始终为1,因此在上面的示例中,只有两个可能的随机向量[1,0]和[-0.28,-0.96]。

另一个示例,这是3-d中的一个:

In [24]: v = np.array([3, -4, 6])

In [25]: w = rand_cos_sim(v, -0.75)

In [26]: w
Out[26]: array([ 0.3194265 ,  0.46814873, -0.82389531])

In [27]: v.dot(w)/(np.linalg.norm(v)*np.linalg.norm(w))
Out[27]: -0.75

In [28]: w = rand_cos_sim(v, -0.75)

In [29]: w
Out[29]: array([-0.48830063,  0.85783797, -0.16023891])

In [30]: v.dot(w)/(np.linalg.norm(v)*np.linalg.norm(w))
Out[30]: -0.75

答案 1 :(得分:-1)

SciPy余弦距离:https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.cosine.html

from scipy.spatial.distance import cosine

v = [3, -4]

w = [0.875, 3]

cosine(v, w)

就向后工作而言,您可以使用点积产品自行完成。