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:
当不相等时,则会采用规则对其:
a.shape得到的是(3,) b是一个浮点数,如果转换成array,则b.shape是一个(),a的1轴对齐,补齐为1,a.shape(3,1),b对齐,则对齐也为(3,1),然后按照一一对应的方式计算
或许上述例子不是太明确,下面采用一个更加确切的例子说明:
官方的图是这样的:
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]]
官方的图是这样的:
相关文章推荐
- Python的numpy中的 broadcasting(广播)机制
- numpy 中的 broadcasting(广播)机制
- numpy的广播机制
- numpy广播机制
- 详解Numpy中的广播原则/机制
- numpy的广播机制(broadcast)
- numpy的广播机制
- numpy中的通用函数(ufunc)的广播机制(Broadcasting)依赖于数组shape属性
- Android 广播机制 详解
- 广播消息机制
- Android 广播机制 BroadCastReceiver
- 第五章 广播机制
- 第一行代码 广播机制Broadcast Receiver 学习笔记
- Broadcast广播机制--学习笔记
- 广播机制实现
- Android 开发者面试题-广播机制详解
- android中的广播退出机制broadcast
- Android之广播机制
- 杂记1:android广播监听实时监听网络,以及回调机制应用
- 注册广播有几种方式,这些方式有何优缺点?请谈谈Android引入广播机制的用意。