機器學習中常用的Numpy函式
阿新 • • 發佈:2019-02-01
1、numpy.nonzeros()
返回非0元素的索引
如果是二維矩陣的話,返回兩個陣列。第一個陣列包含矩陣非0元素按從左到右從上到下在行上的索引,第二個陣列包含矩陣非0元素按從左到右從上到下在列上的索引
2、numpy.flatten()
返回矩陣展開在一維下的元祖
3、numpy.argsort(x)
返回元祖x按升序排列的索引值,預設為按照從小到大排列
numpy.argsort(-x)
回元祖x按降序排列的索引值
4、numpy.fill_diagonal
np.fill_diagonal(a, 5)
將矩陣a對角元素設定為5
5、numpy.multiply
矩陣對應位置元素相乘
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.multiply(x1, x2)
array([[ 0., 1., 4.],
[ 0., 4., 10.],
[ 0., 7., 16.]])
6、numpy.intersect1d
求兩個陣列的交集
>>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
array ([1, 3])
要求交集的陣列多於兩個, 可使用functools.reduce:
>>> from functools import reduce
>>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
array([3])
7、numpy.where
找到矩陣中滿足給定條件的元素的索引
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array ([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )] # 返回大於3的值.
array([ 4., 5., 6., 7., 8.])
>>> np.where( x == 3.0 ) # 返回等於3的值的索引.
(array([1], dtype=int64), array([0], dtype=int64))
8、numpy.empty_like
返回與給定資料具有同樣大小和型別的資料,並且初始化為0,同理還有ones_like(),zeros_like()
>>> x = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.empyt_like( x )
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> x = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> np.ones_like( x )
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
9、numpy.reshape
返回與給定資料具有同樣值但不同結構的資料
>>> x = np.array([[1., 2., 3.],[4.,5.,6.]])
>>> x
array([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> np.reshape(x,(3,2))
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
10、numpy.random.randint (low, high=None, size=None, dtype=’l’)
返回從low到high之間的隨機整數
>>> np.random.randint(2, size=10)
array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0])
>>> np.random.randint(1, size=10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
>>> np.random.randint(5, size=(2, 4))
array([[4, 0, 2, 1],
[3, 2, 2, 0]])
>>> y_train = np.random.randint(2, size=(10, 1))
>>> y_train
array([[0],
[1],
[0],
[0],
[0],
[1],
[0],
[0],
[1],
[0]])
11、numpy.random.random
返回在半開區間[0.0, 1.0)之間的隨機浮點數數
>>> np.random.random_sample()
0.43394098360117983
>>> x_train = np.random.random((1000, 2))
>>> x_train
array([[ 0.64316127, 0.33500098],
[ 0.69310311, 0.22020709],
[ 0.53413892, 0.60285074],
...,
[ 0.73776484, 0.02222155],
[ 0.4160632 , 0.71319213],
[ 0.83366365, 0.56880872]])
11、numpy.ravel
返回一個連續的扁平陣列
>>> x = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(np.ravel(x))
[1 2 3 4 5 6]
numpy.ravel( )與numpy.reshape(-1, order=order)結果相同
>>> print(x.reshape(-1))
[1 2 3 4 5 6]
>>> print(np.ravel(x, order='F'))
[1 4 2 5 3 6]