关于Python中两个不同shape的数组间运算规则
作者:little_fat_sheep
1 数组间运算
声明:本博客讨论的数组间运算是指四则运算,如:a+b、a-b、a*b、a/b,不包括 a.dot(b) 等运算,由于 numpy 和 tensorflow 中都遵循相同的规则,本博客以 numpy 为例。
众所周知,相同 shape 的两个数组间运算是指两个数组的对应元素相加。我们经常会碰到一些不同 shape 的数组间运算。
那么,任何两个不同 shape 的数组都能运算么?又遵循什么样的运算规则?
shape 与维数:
如 a:[1,2,3],则 shape=(3, ),维数为1;b:[[1,2,3],[4,5,6]],则shape=(2,3),维数为2
运算条件:
设a为低维数组,b为高维数组,则a和b能运算的充分条件是:a.shape[-1]=b.shape[-1]、a.shape[-2]= b.shape[-2]、...(a可以作为b的一个元素),或者 a.shape=(m,1)(或a.shape=(m, )) 且b.shape=(1,n) (a为行向量,b为列向量)
运算规则:
- 当a为数字时,将a与b的每个元素运算,运算后的 shape 与b相同当
- a可以作为b的一个元素,将a与b中每个相同 shape 的子元素运算,运算后的 shape 与b相同
- 当a为行向量b为列向量时,将a中每个元素与b中每个元素分别运算,运算后的 shape=(a.shape[1], b.shape[0])
如需改变数组 shape,可调用 reshape() 函数,如下:
a=np.array([[1,1],[2,2],[3,3]]) b=a.reshape([-1,1]) #a.shape=(3,2),b.shape=(6,1)
2 实验
数组与数字之间的运算
a=np.array([1,1,1]) b=np.array([[1,1,1],[2,2,2]]) c=a+1 d=b+1 print("c=a+1\n",c) print("d=b+1\n",d)
输出
c=a+1
[2 2 2]
d=b+1
[[2 2 2]
[3 3 3]]
补充:shape=(1, ) 的数组可以与任意 shape 的数组运算,运算规则同数字与数组的运算。
行向量与列向量之间的运算
a=np.array([[1,2,3]]) #或 a=np.array([1,2,3]) b=np.array([[1],[2],[3],[4],[5]]) c=a+b print("c=a+b",c)
输出
c=a+b
[[2 3 4]
[3 4 5]
[4 5 6]
[5 6 7]
[6 7 8]]
1维数组与高维数组之间的运算
a=np.array([1,1,1]) b=np.array([[1,1,1],[2,2,2]]) c=np.array([[1,1,1],[2,2,2],[3,3,3]]) d=a+b e=a+c print("d=a+b\n",d) print("e=a+c\n",e)
d=a+b
[[2 2 2]
[3 3 3]]
e=a+c
[[2 2 2]
[3 3 3]
[4 4 4]]
高维数组之间的运算
a=np.array([[1,1,1],[2,2,2]]) b=np.array([[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]]) c=a+b print("c=a+b\n",c)
c=a+b
[[[2 2 2]
[4 4 4]]
[[4 4 4]
[6 6 6]]]
到此这篇关于关于Python中两个不同shape的数组间运算规则的文章就介绍到这了,更多相关Python两个不同shape的数组内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!