Numpy计算一个3D矩阵内部数组的点积[重复]

问题描述 投票:0回答:1

我有两个数组,看起来如下。

enter image description here

在代码中

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])

我怎么能用numpy函数来做这个?

我无法用 .dot, .tensordot 或类似方法...

t.dot(t) 产生这个错误 ValueError: shapes (6,6,2) and (6,6,2) not aligned: 2 (dim 2) != 6 (dim 1) 这是预料之中的,但我想规避它。

python numpy matrix-multiplication dot-product numpy-einsum
1个回答
0
投票

由于你是以 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

0
投票

I got it working with np.einsum:

np.einsum("...i, ...i", t, t)

它产生的输出与我的for循环相同。

© www.soinside.com 2019 - 2024. All rights reserved.