numpy中一些常用函式記錄(3)
阿新 • • 發佈:2018-12-17
1. np.prod() : prod函式用於求陣列元素的乘積。
Note: 陣列沒有元素,即為空時,得到的值為 1.0 In [2]: np.prod([]) Out[2]: 1.0 In [4]: np.prod([[],[]]) Out[4]: 1.0
示例: >>> np.prod([1.,2.]) 2.0 >>> np.prod([[1.,2.],[3.,4.]]) 24.0 >>> np.prod([[1.,2.],[3.,4.]], axis=1) array([ 2., 12.])
2. np.pad() : 根據需要將陣列填充成指定的形狀
這裡只介紹卷積過程中為防止圖片資訊丟失使用的 0 填充模式
#二維陣列 >>> a=np.arange(1,5).reshape(2,2) >>> a [[1 2] [3 4]] # a是二維陣列, 中間的兩個(2,3)分別針對 axis=0 和 axis=1 來填充 # mode="constant" 是預設填充值為0 >>> np.pad(a,((2,3),(2,3)),mode="constant") >>> array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0, 0], [0, 0, 3, 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) # costant 有值時 按給出的值填充 In [15]: np.pad(a,((2,3),(2,3)),mode="constant",constant_values=(6,8)) Out[15]: array([[6, 6, 6, 6, 8, 8, 8], [6, 6, 6, 6, 8, 8, 8], [6, 6, 1, 2, 8, 8, 8], [6, 6, 3, 4, 8, 8, 8], [6, 6, 8, 8, 8, 8, 8], [6, 6, 8, 8, 8, 8, 8], [6, 6, 8, 8, 8, 8, 8]])
3. np.random.randn() : 返回一個服從正態分佈的陣列
標準形式 :
: sigma * np.random.randn(...) + mu
#我們一般常用返回為服從N(0,1)正態分佈陣列 In [28]: np.random.randn(3,3) Out[28]: array([[ 0.77832362, -0.26915292, -0.0997728 ], [ 1.38962369, -0.4438962 , -1.00224716], [-1.06567318, 1.42600225, -0.6901084 ]])
4. np.random.rand() : 返回一個給定shape的(0,1)之間的均勻分佈
# 返回一個 4*4 數值 In [29]: np.random.rand(4,4) Out[29]: array([[0.10359531, 0.88317262, 0.50667337, 0.38014409], [0.59356012, 0.54673751, 0.68416049, 0.89578659], [0.52713305, 0.20503638, 0.79684913, 0.73882077], [0.11927379, 0.00325085, 0.65378211, 0.94322903]])
5. np.linspace()
在指定的間隔內返回均勻間隔的數字。返回number均勻分佈的樣本,在[start, stop]。這個區間的端點可以任意的被排除在外。
>>> >>> np.linspace(2.0, 3.0, num=5) array([ 2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([ 2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)