您的位置:首页 > 编程语言 > Python开发

Numpy的广播机制

2017-04-16 20:03 246 查看
All input arrays with ndim smaller than the input array of largest ndim, have 1’s prepended to their shapes.

The size in each dimension of the output shape is the maximum of all the input sizes in that dimension.

An input can be used in the calculation if its size in a particular dimension either matches the output size in that dimension, or has value exactly 1.

If an input has a dimension size of 1 in its shape, the first data entry in that dimension will be used for all calculations along that dimension. In other words, the stepping machinery of the ufunc will simply not step along that dimension (the stride will be 0 for that dimension).

让所有输入数组都向其中shape最长的数组看齐,shape中不足的部分都通过在前面加1补齐

输出数组的shape是输入数组shape的各个轴上的最大值

如果输入数组的某个轴和输出数组的对应轴的长度相同或者其长度为1时,这个数组能够用来计算,否则出错,当输入数组的某个轴的长度为1时,沿着此轴运算时都用此轴上的第一组值

一般情况下,numpy 都是采用一一对应的方式(element-by-element )进行计算

例子1:

from numpy import array
a = array([1.0,2.0,3.0])
b = array([2.0,2.0,2.0])
a * b
# array([ 2.,  4.,  6.])


当不相等时,则会采用规则对其:

from numpy import array
a = array([1.0,2.0,3.0])
b = 2.0
a * b
# array([ 2.,  4.,  6.])


a.shape得到的是(3,) b是一个浮点数,如果转换成array,则b.shape是一个(),a的1轴对齐,补齐为1,a.shape(3,1),b对齐,则对齐也为(3,1),然后按照一一对应的方式计算

或许上述例子不是太明确,下面采用一个更加确切的例子说明:

import numpy as np
a = np.arange(0, 6).reshape(6, 1)
a
# array([[ 0], [1], [2], [3], [4], [5]])
a.shape
# (6, 1)
b = np.arange(0, 5)
b.shape
# (5,)
c = a + b
print (c)
# [[0 1 2 3 4]
# [1 2 3 4 5]
# [2 3 4 5 6]
# [3 4 5 6 7]
# [4 5 6 7 8]
# [5 6 7 8 9]]


官方的图是这样的:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: