Numpy广播功能
广播(Broadcast)是对不同形状(shape)的数组进行数值计算的方式。
广播规则:
- 如果两个数组的维度数不相同,那么小维度数组的形状将会在最左边补1;
- 如果两个数组的形状在任何一个维度都不匹配,那么数组的形状会沿着维度为1的维度扩展以匹配另外一个数组的形状;
- 如果两个数组的形状在任何一个维度上都不匹配并且没有任何一个维度等于1,那么会引出异常。
In [1]: import numpy as np
#相同形状数组数值计算时,数组内元素逐个加减
In [2]: a = np.array([0,1,2])
In [3]: b = np.array([0,1,2])
In [4]: a + b
Out[4]: array([0, 2, 4])
#5扩展成[5,5,5]与a形状一致后分别相加
In [5]: a + 5
Out[5]: array([5, 6, 7])
#x从(1,3)、y从(3,1)都扩展成(3,3)后相加
In [7]: x = np.arange(3)
In [8]: y = np.arange(3)[:,np.newaxis]
In [9]: x
Out[9]: array([0, 1, 2])
In [10]: y
Out[10]:
array([[0],
[1],
[2]])
In [11]: x + y
Out[11]:
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
广播的归一化应用
#x为(10,3)数组
In [12]: x = np.random.random((10,3))
In [13]: x
Out[13]:
array([[0.05404783, 0.76923374, 0.65853154],
[0.08907194, 0.01900223, 0.04000283],
[0.72521795, 0.09186224, 0.67457589],
[0.41700931, 0.42471439, 0.94748451],
[0.95439046, 0.96458199, 0.01966024],
[0.31656808, 0.74726154, 0.22988047],
[0.70578412, 0.04238469, 0.66419186],
[0.1228215 , 0.09629365, 0.09550091],
[0.51172621, 0.96489282, 0.32432765],
[0.69833444, 0.19646535, 0.1527003 ]])
In [14]: x_mean = np.mean(x,axis=0)
In [15]: x_mean
Out[15]: array([0.45949718, 0.43166926, 0.38068562])
#x_mean从(1,3)扩展成(10,3)
In [16]: x_centered = x-x_mean
#归一化值(实际值-平均值)
In [17]: x_centered
Out[17]:
array([[-0.40544935, 0.33756448, 0.27784592],
[-0.37042524, -0.41266704, -0.34068279],
[ 0.26572077, -0.33980702, 0.29389027],
[-0.04248787, -0.00695488, 0.56679889],
[ 0.49489328, 0.53291272, -0.36102538],
[-0.1429291 , 0.31559228, -0.15080515],
[ 0.24628693, -0.38928457, 0.28350624],
[-0.33667569, -0.33537562, -0.28518471],
[ 0.05222903, 0.53322355, -0.05635797],
[ 0.23883725, -0.23520391, -0.22798532]])
In [18]: x_centered.mean(0)
Out[18]: array([-1.11022302e-17, -4.44089210e-17, 2.77555756e-17])