简体   繁体   English

在 numpy 中将 2D 数组广播到 4D 数组

[英]Broadcasting 2D array to 4D array in numpy

I have a 2D array x of shape (48, 7) , and a 4D array T of shape (48, 7, 48, 7) .我有一个形状为(48, 7)的二维数组x和一个形状为(48, 7, 48, 7)的四维数组T When I multiply x * T , python broadcasts the dimensions, but not in the way I expected (actually, I don´t understand how it is broadcasting).当我将x * T相乘时,python 会广播尺寸,但不是以我预期的方式(实际上,我不明白它是如何广播的)。 The following loop would achieve what I want:以下循环将实现我想要的:

for i in range(48):
    for j in range(7):
        Tx[i, j, :, :] = x[i, j] * T[i, j, :, :]

Where Tx is an array of shape (48, 7, 48, 7) .其中Tx是一个形状数组(48, 7, 48, 7) My question is, is there a way to achieve the same result using broadcasting?我的问题是,有没有办法使用广播达到相同的结果?

I found the solution,我找到了解决方案,
Python broadcast from the rightmost dimmesion and works it's way to the left ( https://numpy.org/doc/stable/user/basics.broadcasting.html#:~:text=When%20operating%20on%20two%20arrays%2C%20NumPy%20compares%20their%20shapes%20element%2Dwise.%20It%20starts%20with%20the%20trailing%20(ie%20rightmost)%20dimensions%20and%20works%20its%20way%20left. ). Python 从最右边的维度广播,并在左边工作( https://numpy.org/doc/stable/user/basics.broadcasting.html#:~:text=When%200arrays%2C %20NumPy%20比较%20their%20shapes%20element%2Dwise.%20It%20starts%20with%20the%20trailing%20(即%20rightmost)%20dimensions%20and%20works%20its%20way%20left。 )。
By transposing the first two dimmesions and the last two dimmensions:通过转置前两个维度和后两个维度:

T = np.transpose(T, (2,3,0,1))

Then it would broadcast the way I expected, after that the resulting array can be transposed again to recover the original shape.然后它会按照我预期的方式广播,之后可以再次转置生成的数组以恢复原始形状。

Tx = x*T
Tx = np.transpose(Tx, (2,3,0,1))

I hope this helps someone else.我希望这对其他人有帮助。

Broadcasting aligns trailing dimensions.广播对齐尾随尺寸。 In other words, x * Tx is doing this:换句话说, x * Tx正在这样做:

for i in range(48):
    for j in range(7):
        Tx[:, :, i, j] = x[i, j] * T[:, :, i, j]

To get the leading dimensions to line up, add unit dimensions to x :要使主要尺寸对齐,请将单位尺寸添加到x

Tx = x[..., None, None] * T

Alternatively, you can use np.einsum to specify the dimensions explicitly:或者,您可以使用np.einsum明确指定尺寸:

Tx = np.einsum('ij,ij...->ij...', x, T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM