numpy数组广播规则 [英] Numpy array broadcasting rules

查看:85
本文介绍了numpy数组广播规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解Numpy中的数组广播规则.

I'm having some trouble understanding the rules for array broadcasting in Numpy.

很明显,如果您对具有相同尺寸和形状的两个数组执行逐元素乘法,则一切都很好.同样,如果将多维数组乘以标量,则它也可以工作.我了解.

Obviously, if you perform element-wise multiplication on two arrays of the same dimensions and shape, everything is fine. Also, if you multiply a multi-dimensional array by a scalar it works. This I understand.

但是,如果您有两个不同形状的N维数组,那么我不清楚确切的广播规则是什么.该文档/教程解释说:为了广播,尾随轴的大小对于一个操作中的两个数组,它们的大小必须相同,或者其中一个必须为1.

But if you have two N-dimensional arrays of different shapes, it's unclear to me exactly what the broadcasting rules are. This documentation/tutorial explains that: In order to broadcast, the size of the trailing axes for both arrays in an operation must either be the same size or one of them must be one.

好的,所以我假设通过后移轴指的是M x N数组中的N.因此,这意味着如果我尝试将两个2D数组(矩阵)的列数相等,它应该可以工作吗?除非不是...

Okay, so I assume by trailing axis they are referring to the N in a M x N array. So, that means if I attempt to multiply two 2D arrays (matrices) with equal number of columns, it should work? Except it doesn't...

>>> from numpy import *
>>> A = array([[1,2],[3,4]])
>>> B = array([[2,3],[4,6],[6,9],[8,12]])
>>> print(A)
[[1 2]
 [3 4]]
>>> print(B)
[[ 2  3]
 [ 4  6]
 [ 6  9]
 [ 8 12]]
>>> 
>>> A * B
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape

由于AB都有两列,所以我认为这会起作用.因此,我可能在这里误解了有关后移轴"这一术语以及它如何应用于N维数组的信息.

Since both A and B have two columns, I would have thought this would work. So, I'm probably misunderstanding something here about the term "trailing axis", and how it applies to N-dimensional arrays.

有人可以解释为什么我的示例不起作用吗?尾随轴"是什么意思?

Can someone explain why my example doesn't work, and what is meant by "trailing axis"?

推荐答案

好,在链接的文档页面上解释了拖尾轴的含义. 如果有两个具有不同维数的数组,例如一个1x2x3和另一个2x3,则仅比较尾随的公共维,在这种情况下为2x3.但是,如果两个数组都是二维数组,则它们的相应大小必须相等或其中之一必须为1.数组尺寸为1的维度称为单数,并且可以沿数组广播.

Well, the meaning of trailing axes is explained on the linked documentation page. If you have two arrays with different dimensions number, say one 1x2x3 and other 2x3, then you compare only the trailing common dimensions, in this case 2x3. But if both your arrays are two-dimensional, then their corresponding sizes have to be either equal or one of them has to be 1. Dimensions along which the array has size 1 are called singular, and the array can be broadcasted along them.

在您的情况下,您有2x24x24 != 2,而42都不等于1,所以这不起作用.

In your case you have a 2x2 and 4x2 and 4 != 2 and neither 4 or 2 equals 1, so this doesn't work.

这篇关于numpy数组广播规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆