简体   繁体   English

Numpy 数组,在特定轴上进行乘法和求和

[英]Numpy array, multiply and sum over specific axis

Let's say I have an array A such that假设我有一个数组 A 这样

A = np.array([
    [[1,1,1,1],[2,2,2,2]],
    [[3,3,3,3],[4,4,4,4]],
    [[5,5,5,5],[6,6,6,6]]
])

where the shape is something like (3,2,4) in this example.在此示例中,形状类似于 (3,2,4)。 Now let's say I have another array B such that现在假设我有另一个数组 B 这样

B = np.array([1,2,3,4])

I would like to multiply A and B element wise along the last axis of A and sum, such that我想沿着 A 的最后一个轴将 A 和 B 元素明智地相乘并求和,这样

C = np.array([
    [10,20],
    [30,40],
    [50,60]
])

Is there a nice way to do this?有没有好的方法来做到这一点? I thought about making an equivalent 3D array out of B, doing element wise multiplication, and summing along the last axis of this new array.我想过用 B 制作一个等效的 3D 数组,进行元素乘法,然后沿着这个新数组的最后一个轴求和。 I was wondering if there is a cleaner way to do this?我想知道是否有更清洁的方法来做到这一点?

Edit: If it makes things easier, A can also be written just as编辑:如果它使事情变得更容易, A 也可以写成

A = np.array([
    [1,2],
    [3,4],
    [5,6]
])

I made A in the way shown at the top of my post because I thought it was neccessary to do so for the proposed multiplication and summation.我按照帖子顶部显示的方式制作了 A,因为我认为对于建议的乘法和求和来说,这样做是必要的。 If working with this version of A at the bottom of this post is easier/just as easy then that would be preferable.如果在这篇文章底部使用这个版本的 A 更容易/同样容易,那将是更可取的。

Cheers干杯

Your example is ambiguous and how you break down the computation is unclear.您的示例含糊不清,您如何分解计算也不清楚。

It looks to me that you could take any element of the last dimension of A and multiply it with the sum of B:在我看来,您可以将 A 的最后一个维度的任何元素与 B 的总和相乘:

A[...,0]*B.sum()

Or do you want to sum afterwards?或者你想事后总结?

(A*B[None,:]).sum(2)

output: output:

array([[10, 20],
       [30, 40],
       [50, 60]])
In [126]: A = np.array([
     ...:     [[1,1,1,1],[2,2,2,2]],
     ...:     [[3,3,3,3],[4,4,4,4]],
     ...:     [[5,5,5,5],[6,6,6,6]]
     ...: ])
In [127]: A.shape
Out[127]: (3, 2, 4)
In [128]: B = np.array([1,2,3,4])
 

(3,2,4) broadcasts with (4,) (eg (1,1,4)) to make (3,2,4), then sum on 4: (3,2,4) 用 (4,) 广播(例如 (1,1,4))生成 (3,2,4),然后对 4 求和:

In [129]: (A*B).sum(axis=-1)
Out[129]: 
array([[10, 20],
       [30, 40],
       [50, 60]])

If the start is (3,2):如果起点是 (3,2):

In [130]: A1 = np.array([
     ...:     [1,2],
     ...:     [3,4],
     ...:     [5,6]
     ...: ])
     ...: 

make it (3,2,1):使它(3,2,1):

In [132]: (A1[:,:,None]*B).shape
Out[132]: (3, 2, 4)
In [133]: (A1[:,:,None]*B).sum(axis=-1)
Out[133]: 
array([[10, 20],
       [30, 40],
       [50, 60]])

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

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