我有三个numpy矩阵x,r和r。谁的值是:
x = np.array([[4,2],
[0,-1],
[-2,5],
[2,6]])
y = np.array([[1,7],
[2,6],
[5,2]])
r = np.array([[2,2,1],
[2,3,1],
[9,5,1],
[2,0,4]])
我要做的是:(很难用文字来描述,所以我使用代码来表达我想做的事情)
K = r.shape[1]
D = x.shape[1]
v = np.zeros((K, D, D))
for k in range(K):
v[k] = (r[:, k] * (x - y[k]).transpose() @ (x - y[k]))
print(v)
最后一个v是我需要的,而v等于
[[[103. 38.]
[ 38. 216.]]
[[100. 46.]
[ 46. 184.]]
[[111. -54.]
[-54. 82.]]]
在没有for循环的情况下,是否有任何优雅或pythonic的方法来实现这一目标?
谢谢
答案 0 :(得分:1)
这应该为您工作:
A = x[np.newaxis,...]-y[:,np.newaxis,:] # equivalent to (x-y[k]) for all k
B = A.swapaxes(1,2) # equivalent to (x-y[k]).transpose() for all k
C = r.T[:,np.newaxis,:]*B # equivalent to r[:, k] * (x - y[k]).transpose()
D = C@A # equivalent to r[:, k] *(x - y[k]).transpose() @ (x - y[k])
或以怪物无法读取的形式
((r.T[:,np.newaxis,:]*(x[np.newaxis,...]
-y[:,np.newaxis,:]).swapaxes(1,2))@
(x[np.newaxis,...]-y[:,np.newaxis,:]))
证明:
>>> (v==((r.T[:,np.newaxis,:]*(x[np.newaxis,...]
-y[:,np.newaxis,:]).swapaxes(1,2))@
(x[np.newaxis,...]-y[:,np.newaxis,:]))).all()
True