-
cs231 numpy介绍
这个定义比较准确,可以先看看这个,再看后面的例子。
Broadcasting two arrays together follows these rules:
- If the arrays do not have the same rank, prepend the shape of the lower rank array with 1s until both shapes have the same length.
- The two arrays are said to be compatible in a dimension if they have the same size in the dimension, or if one of the arrays has size 1 in that dimension.
- The arrays can be broadcast together if they are compatible in all dimensions.
- After broadcasting, each array behaves as if it had shape equal to the elementwise maximum of shapes of the two input arrays.
- In any dimension where one array had size 1 and the other array had size greater than 1, the first array behaves as if it were copied along that dimension
- numpy 数组广播:例子比较多
-
Numpy中的广播(Broadcasting):这个例子比较清晰。
a.shape得到的是(3,) b是一个浮点数,如果转换成array,则b.shape是一个(),a的1轴对齐,补齐为1,a.shape(3,1),b对齐,则对齐也为(3,1),然后按照一一对应的方式计算
但是这一段说的不太对,根据后面的介绍,正确流程应该是这样:
- b的维度小于a, 因此首先增加维度对齐,b.shape变成(1,),
- 然后b再在维度为1上tail变成(3,)
- 两个shape相同的array最后相加.最后的shape也是(3,0)
ps:如果按照原文说的,最后的shape将是(3,1),这个可以自己实验一下
- 总结:
1.对齐
先看数组维度,维度不相同在短维度的数组前面连续增加1维,直到两个数组维度相同,转向第2步
2.检查
两个维度数目相同的数组,如果二者各个维度的长度相同或者一个长度为1,那么可以进行第3步执行tail(拓展).如果不满足,则不可广播
3.拓展
对于检查无误的a,b两数组,输出的数组的shape是a.shape*b.shape(按位乘).将两数组沿着维度长度为1的轴进行拓展(copy),拓展成与输出一致的shape,然后进行运算.