numpy广播

概述

不同形状 (shape)的数组进行数值计算时, 会使用numpy的 广播 机制

广播的规则:

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

  • 输出数组的 形状 是 输入数组形状的 各个维度 上的 最大值。

  • 如果输入数组的某个维度和输出数组的对应维度的长度相同或者其长度为 1 时,这个数组能够用来计算,否则出错。

  • 当输入数组的某个维度的长度为 1 时,沿着此维度运算时都用此维度上的第一组值。

行数不同 列数相同 的两个数组运行

import numpy as np

arr=np.random.randint(1,10,(2,3))
arr2=np.random.randint(1,10,(3,))
res=arr+arr2
print('arr:\n',arr)
print('arr2:\n',arr2)
print('res:\n',res)

执行结果:

arr:
[[6 9 5]
 [3 3 9]]
arr2:
 [3 3 1]
res:
 [[ 9 12  6]
 [ 6  6 10]]

由于列数相同,但行数不同,所以将arr数组的每一行,与arr2数组的行进行运算

如下图:

行数相同 列数不同 的两个数组运行

import numpy as np

arr=np.random.randint(1,10,(2,3))
arr2=np.random.randint(1,10,(2,1))
res=arr+arr2
print('arr:\n',arr)
print('arr2:\n',arr2)
print('res:\n',res)

执行结果:

arr:
 [[1 4 4]
 [9 2 2]]
arr2:
 [[2]
 [1]]
res:
 [[ 3  6  6]
 [10  3  3]]

由于行数相同,但列数不同,所以将arr数组的每一列,与arr2数组的列进行运算

如下图:

m行1列与1行n列计算

arr = np.arange(0, 4).reshape(4, 1)
arr2 = np.arange(0, 3)
res=arr+arr2
print('arr:\n',arr)
print('arr2:\n',arr2)
print('res:\n',res)

执行结果:

 [[0]
 [1]
 [2]
 [3]]
arr2:
 [0 1 2]
res:
 [[0 1 2]
 [1 2 3]
 [2 3 4]
 [3 4 5]]

行数列数都不相同的两个数组,计算报错

import numpy as np

arr=np.random.randint(1,10,(2,3))
arr2=np.array([1,2])
print('arr:\n',arr)
print('arr2:\n',arr2)
res=arr+arr2
print('res:\n',res)

执行结果如下:

arr:
 [[6 9 1]
 [7 5 6]]
arr2:
 [1 2]
Traceback (most recent call last):
  File "c:/Users/mym/Desktop/python/numpy_study/1.py", line 10, in <module>
    res=arr+arr2
ValueError: operands could not be broadcast together with shapes (2,3) (2,)

在numpy中,两个数组的行数、列数都不相同,无法计算,报错ValueError: operands could not be broadcast together with shapes


原文出处:/show_1EF48b2mjT7K.html