不同 shape numpy ndarray 广播运算

numpy 数组运算主要分为:

  1. numpy ndarray 数组和数字之间的加、减、乘、除运算
  2. 同 shape 的 numpy ndarray 数组之间的加、减、乘、除运算
  3. 不同 shape 的 numpy ndarray 数组之间的加、减、乘、除运算

接下来,我们分别讲解 ndarray 的运算规则:

1. numpy ndarray 数组和数字之间的加、减、乘、除运算

请看下面的示例代码:

import numpy as np


def test():
    nd = np.arange(9).reshape((3, 3))
    print(nd)
    print("-" * 10)

    ret1 = nd + 100
    ret2 = nd * 10
    ret3 = nd / 10
    ret4 = nd - 5

    print(ret1)


if __name__ == "__main__":
    test()

输出结果:

[[0 1 2]
 [3 4 5]
 [6 7 8]]
----------
[[100 101 102]
 [103 104 105]
 [106 107 108]]

从运行结果我们得知:当 ndarray 和数字之间运算时等价于数组中每一个元素和该数字运算。

2. 同 shape 的 numpy ndarray 数组之间的加、减、乘、除运算

请看下面的示例代码:

def test():
    nd1 = np.arange(1, 10).reshape((3, 3))
    nd2 = np.arange(11, 20).reshape(3, 3)

    print(nd1)
    print("-" * 10)
    print(nd2)
    print("-" * 10)

    ret1 = nd1 + nd2
    ret2 = nd1 - nd2
    ret3 = nd1 * nd2
    ret4 = nd1 / nd2

    print(ret1)


if __name__ == "__main__":
    test()

输出结果:

[[1 2 3]
 [4 5 6]
 [7 8 9]]
----------
[[11 12 13]
 [14 15 16]
 [17 18 19]]
----------
[[12 14 16]
 [18 20 22]
 [24 26 28]]

从运行结果可以看到:同 shape ndarray 之间运算等价于同位置元素进行相应运算。

3. 不同 shape 的 numpy ndarray 数组之间的加、减、乘、除运算

不同 shapre 的 ndarray 之间运算并不是如前两个案似的运算。而是会遵循以下规则:

  1. 两个数组的维度右对齐,同位置的两个维度至少有一个是 1、或者相等、或者有一个为空,则此维度为最大值。否则无法进行运算
  2. 当满足条件 1 时,数组会在扩展之后运算。

我们先理解下规则 1,请看下面的代码:

def test():

    nd1 = np.array([1, 2, 3])
    nd2 = np.arange(3).reshape((3, 1))

    print(nd1)
    print('-' * 20)
    print(nd2)

    # 列数必须相同
    ret1 = nd1 + nd2
    # ret2 = nd1 * nd2
    print('-' * 20)
    print(ret1)


if __name__ == "__main__":
    test()

上述代码中,nd1 为 1 行 3 列的数组,nd2 为 3 行 1 列的数组,这两个是否能够运算呢?

nd1 维度13
nd2 维度31
ret1 维度有一个为1,则维度为 3有一个为 1,则维度为 3

由于对应维度都出现了 1,所以是合法的。结果维度为(3, 3)

接下来,对将 nd1、nd2 扩展为 (3, 3),其中:

nd1 扩展为:[ [1, 2, 3], [1, 2, 3], [1, 2, 3] ],即:

123
123
123

nd2 扩展为:[[0,0, 0], [1, 1, 1], [2, 2, 2]]

000
111
222
程序的运算结果为:
[1 2 3]
--------------------
[[0]
 [1]
 [2]]
--------------------
[[1 2 3]
 [2 3 4]
 [3 4 5]]

接下来,按照同 shape 的运算规则计算即可。
至此,讲解完毕了,希望对你有所帮助!

未经允许不得转载:一亩三分地 » 不同 shape numpy ndarray 广播运算
评论 (0)

5 + 1 =