[英]multiply and sum arrays in numpy
Im trying to calculate my own distance with numpy array by adding a weight to each sum in euclidean distance, for example: 我试图通过将一个权重添加到欧几里得距离中的每个和来计算自己的距离,例如:
a = ((1, 2, 3))
b = ((4, 5, 6))
distance = np.sum((a-b)**2)
but what I want is set my distance as: 但我要设置的距离为:
a = ((1, 2, 3))
b = ((4, 5, 6))
w = ((0.2, 0,3, 0,5))
distance = 0.2*((1-4)**2) + 0.3*((2-5)**2) + 0.5*((3-6)**2)
is it any form of do this with numpy without iterate over echa vector and do this manually? 用numpy进行迭代是否有任何形式,而无需遍历echa vector并手动执行此操作?
You're halfway there: 您在其中途:
a = np.array([[1., 2, 3]])
b = np.array([[4., 5, 6]])
w = np.array([[0.2, 0.3, 0.5]])
result = float(np.dot((a - b)**2, w.T))
So, you simply multiply a row-vector (a - b)**2
by a column-vector wT
to get the number you want. 因此,您只需将行向量
(a - b)**2
乘以列向量wT
即可得到所需的数字。
Please note that you'll have to make sure the arrays' dimensions match. 请注意,您必须确保阵列的尺寸匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.