简体   繁体   English

广播的最小/最大 arrays

[英]Min/max of broadcasted arrays

Is there a way to efficiently compare multiple arrays which are broadcast together?有没有办法有效地比较一起广播的多个 arrays ? For example:例如:

a = np.arange( 0,  9).reshape(3,3)
b = np.arange( 9, 18).reshape(3,3)
c = np.arange(18, 27).reshape(3,3)

If I were to broadcast these as follows:如果我按如下方式广播这些:

abc = a[:,:,None,None,None,None] + b[None,None,:,:,None,None] + c[None,None,None,None,:,:]

Then each element of abc is equal to a_ij + b_kl + c_mn where ij , kl , and mn index the respective arrays.然后abc的每个元素等于a_ij + b_kl + c_mn ,其中ijklmn分别索引 arrays。 What I would like instead is to get min(a_ij, b_kl, c_mn) , or ideally, max(a_ij, b_kl, c_mn) - min(a_ij, b_kl, c_mn) .我想要的是得到min(a_ij, b_kl, c_mn) ,或者理想情况下, max(a_ij, b_kl, c_mn) - min(a_ij, b_kl, c_mn) Is there an efficient way in which I can do this?有没有一种有效的方法可以做到这一点?

I could, of course, broadcast temporary arrays as:当然,我可以将临时 arrays 广播为:

Abc =     a[:,:,None,None,None,None] + 0 * b[None,None,:,:,None,None] + 0 * c[None,None,None,None,:,:]
aBc = 0 * a[:,:,None,None,None,None] +     b[None,None,:,:,None,None] + 0 * c[None,None,None,None,:,:]
abC = 0 * a[:,:,None,None,None,None] + 0 * b[None,None,:,:,None,None] +     c[None,None,None,None,:,:]

and then find the min/max from these arrays, however, these arrays can get quite large.然后从这些 arrays 中找到最小值/最大值,但是,这些 arrays 可以变得相当大。 It would be better if there were some way to do it in one step.如果有某种方法可以一步完成,那就更好了。

And as an additional note, these arrays are guaranteed to be broadcastable, but not necessarily have the same shape (for example, (1, 3) and (3, 3) ).作为附加说明,这些 arrays 保证可广播,但不一定具有相同的形状(例如, (1, 3)(3, 3) )。

You can store an intermediate array (smaller than your final result anyway) by doing the operation on a and b :您可以通过对ab执行操作来存储中间数组(无论如何都小于最终结果):

temp = np.minimum.outer(a.ravel(), b.ravel())
res = np.minimum.outer(temp.ravel(), c.ravel())

and then repeat that same operation with c .然后用c重复相同的操作。 minimum computes element-wise min of 2 arrays. minimum计算 2 arrays 的元素最小值。 Since it is a ufunc , you can use outer to apply that operation to all pairs of values for those 2 arrays.由于它是一个ufunc ,您可以使用outer将该操作应用于那些 2 arrays 的所有值对。

You can reshape res as you prefer.您可以根据需要重塑res

Edit # 1编辑#1

Thanks to P. Panzer comment, you do not need to use 1D arrays with ufunc.outer , which results in even simpler code:感谢 P. Panzer 的评论,您不需要将 1D arrays 与ufunc.outer一起使用,这会产生更简单的代码:

temp = np.minimum.outer(a, b)
res = np.minimum.outer(temp, c)

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

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