我有两个数组,看起来如下。
在代码中
t = np.random.rand(6, 6, 2)
现在我想计算轴2数组的点积(形状2的数组) 对于轴0和轴1数组的每一个条目来说。
我可以用for循环来计算。
Q = np.zeros_like(t)
for i in range(6):
for j in range(6):
Q[i,j] = t[i,j].dot(t[i,j])
我无法用 .dot
, .tensordot
或类似方法...
t.dot(t)
产生这个错误 ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1)
这是预料之中的,但我想规避它。
由于你是以 dot
行与自己的乘积,你可以将其简化为乘以 t
并将其结果相加。为了拥有与 t
,您可以使用 np.broadcast_to
:
np.broadcast_to((t*t).sum(-1)[...,None], t.shape)
最新情况
根据评论,看来你只需要。
(t*t).sum(-1)
检查。
np.allclose(Q, np.broadcast_to((t*t).sum(-1)[...,None], t.shape))
# True
I got it working with np.einsum
:
np.einsum("...i, ...i", t, t)
它产生的输出与我的for循环相同。