【发布时间】:2019-12-27 00:45:42
【问题描述】:
我有以下向量:
import numpy as np
my_vector = np.array([0.001, -0.05, 0.3, 0.5, 0.01, -0.03])
有人可以建议一种随机生成相似向量的方法,只是值略有不同吗?例如,所需的输出是:
[0.002, -0.06, 0.2, 0.4, 0.02, -0.02]
为了给出一些上下文,这个向量表示我输入分类模型的样本。我的计划是随机生成一组相似的样本,并将它们输入到同一个模型中,以观察其输出的变化。最终目标是验证模型是否为相似样本生成相似输出。
我尝试Create random vector given cosine similarity 并将我想要的余弦相似度设置为 1,但使用这种方法我只能获得一个相似的向量(见下文)。我至少需要 10 个。
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
new_vector = rand_cos_sim(my_vector, 1)
print(new_vector)
# [ 0.00170622 -0.08531119 0.51186714 0.8531119 0.01706224 -0.05118671]
我没有考虑特定的相似性度量,它可以是欧几里得、余弦,以最有效的为准。欢迎提出任何建议。
请注意,我提供的my_vector 仅用于说明目的,实际上我的向量将具有不同的值范围,具体取决于我正在测试的模型和不同的数据。
谢谢。
【问题讨论】:
标签: python numpy similarity cosine-similarity