機器學習基礎(二)之numpy基礎

                                         numpy基礎

‘’‘
    numpy初始化
’‘’

import numpy as np   //引用anaconda python中的numpy

X = np.arange(10)    //用numpy創建一個一維數組

X = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) //運行結果


‘’‘
   #reshape 對數組進行重塑
’‘’

x = np.arange(15).reshape(3,5)  //塑造成3行5列

x = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14]])

‘’‘
  #切片,對python中的列表進行切片處理,對於二維一樣
’‘’

X = np.arange(10)

X[::-1]  //從逆序派過來

array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])

X[:3] //獲取下標0-2的元素,左閉右開

array([0, 1, 2])

‘’‘
  #np中矩陣的連接方法
’‘’
x = np.arange(15).reshape(3,5)  

x = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14]])

#concatenate:

np.concatenate([x,x])   //兩個矩陣相疊

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

#vstack :垂直方向相疊

#hstack :水平方向相疊,這兩個可以自行體會一下

‘’‘
  #np中矩陣的分割方法
’‘’

x = np.arange(0,15)

x1,x2,x3 = np.split(x,[3,7])  //注意此時需要用np.split(矩陣名,列表)二不能用 x.split來做,並且此時分爲三部分

x = x.reshape([3,5])

x = array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14]])

#相對應於連接,也有vsplit和hsplit

upper,lower = np.vsplit(x,[2])

left,right = np.hsplit(x,[2])

‘’‘
  #np中矩陣的運算
’‘’

#支持 * + 並且與python中的有所區別

python:n = 10
        L = [i for i in range(n)]
        L*2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

np:    L = np.arange(1,16).reshape(3,5)
        L*2 = array([[ 2,  4,  6,  8, 10],
                 [12, 14, 16, 18, 20],
                 [22, 24, 26, 28, 30]]) //直接乘以兩倍

#dot(兩個矩陣相乘)
#np.linalg.inv() (求某個矩陣的逆矩陣)
#np.sim() (求和操作)
#mean(),median(),max(),min() 統計學基礎上有
#

‘’‘
  #np中的arg,就是求索引index的值
’‘’
L = np.random.random(10)
L = array([0.35656266, 0.92360074, 0.05858776, 0.54221545, 0.06105745,
           0.71913071, 0.77703987, 0.91120598, 0.48754257, 0.16783168])
np.argmin(L)  得出2,對應下標是最小值

#axis = 0 對應按行 axis = 1 按列

‘’‘
  #np中的fancy indexing
’‘’

X = np.arange(16)

ind = [3,5,8]
X[ind]        相應得出array([3, 5, 8])

x = X.reshape(4,-1)  //reshape(4【代表幾行】,-1【代表分4行,自動分爲幾列】)
x = array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15]])

row = np.array([1,3,2]) //想對應行的下標
col = np.array([2,1,3]) //想對應列的下標
x[row,col] = array([ 6, 13, 11])

#注意,python也支持[True,False]這中bool的元素
#注意,而且比較的結果也全是bool值,可以自行體會一下

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章