文章

numpy的广播运算

前言

这篇文章主要是对numpy中广播运算进行一个解释,官网说的很清楚了,简单来说:

  • 首先是广播运算是尾部对齐的
  • 其次数组a、b对应的同一维度想要能够运算,只有两种成立情况
    1. 二者此维度的大小相等
    2. 其中一个是1(这样可以扩展成另一个数组对应的值)

剩下的看看例子就明白了,以下是摘抄的原文:

numpy的广播运算

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimension and works its way left. Two dimensions are compatible when

  1. they are equal, or
  2. one of them is 1.

Input arrays do not need to have the same number of dimensions. The resulting array will have the same number of dimensions as the input array with the greatest number of dimensions, where the size of each dimension is the largest size of the corresponding dimension among the input arrays. Note that missing dimensions are assumed to have size one.

example:

1
2
3
Image  (3d array): 256 x 256 x 3
Scale  (1d array):             3
Result (3d array): 256 x 256 x 3

链接地址:numpy官方文档

本文由作者按照 CC BY 4.0 进行授权