Numpy學習筆記

Numpy學習筆記

屬性

  • ndim:維度
  • shape:行數和列數
  • size:元素個數

建立

  • array:建立數組
  • dtype:指定數據類型
  • zeros:建立數據全爲0
  • ones:建立數據全爲1
  • empty:建立數據接近0
  • arange:按指定範圍建立數據
  • linspace:建立線段

array

a = np.array([2,23,4])  # list 1d
print(a)
# [2 23 4]

a = np.array([[2,23,4],[2,32,4]])  # 2d 矩陣 2行3列
print(a)
"""
[[ 2 23  4]
 [ 2 32  4]]
"""

dtype

a = np.array([2,23,4],dtype=np.int)
print(a.dtype)
# int64

a = np.array([2,23,4],dtype=np.int32)
print(a.dtype)
# int32
a = np.array([2,23,4],dtype=np.float)
print(a.dtype)
# float64

a = np.array([2,23,4],dtype=np.float32)
print(a.dtype)
# float32

zeros

a = np.zeros((3,4)) # 數據全爲0,3行4列
"""
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
"""

empty

a = np.empty((3,4)) # 數據爲empty,3行4列
"""
array([[  0.00000000e+000,   4.94065646e-324,   9.88131292e-324,
          1.48219694e-323],
       [  1.97626258e-323,   2.47032823e-323,   2.96439388e-323,
          3.45845952e-323],
       [  3.95252517e-323,   4.44659081e-323,   4.94065646e-323,
          5.43472210e-323]])
"""

arange

a = np.arange(10,20,2) # 10-19 的數據,2步長
"""
array([10, 12, 14, 16, 18])
"""

reshape

a = np.arange(12).reshape((3,4))    # 3行4列,0到11
"""
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
"""

linspace

a = np.linspace(1,10,20)    # 開始端1,結束端10,且分割成20個數據,生成線段
"""
array([  1.        ,   1.47368421,   1.94736842,   2.42105263,
         2.89473684,   3.36842105,   3.84210526,   4.31578947,
         4.78947368,   5.26315789,   5.73684211,   6.21052632,
         6.68421053,   7.15789474,   7.63157895,   8.10526316,
         8.57894737,   9.05263158,   9.52631579,  10.        ])
"""

reshape

a = np.linspace(1,10,20).reshape((5,4)) # 更改shape
"""
array([[  1.        ,   1.47368421,   1.94736842,   2.42105263],
       [  2.89473684,   3.36842105,   3.84210526,   4.31578947],
       [  4.78947368,   5.26315789,   5.73684211,   6.21052632],
       [  6.68421053,   7.15789474,   7.63157895,   8.10526316],
       [  8.57894737,   9.05263158,   9.52631579,  10.        ]])
"""

運算

c=a-b  
c=a+b  
c=a*b
c=b**2
c=10*np.sin(a)  
c_dot = np.dot(a,b)#叉積
np.sum(a) 
np.min(a)  
np.max(a)
np.sum(a,axis=1)#0行1列
np.min(a,axis=0)
np.max(a,axis=1)
np.argmin(A)#求最小的索引,矩陣轉化爲一行的座標
np.argmax(A)
np.mean(A)#平均值
A.mean()
A.median()#中位數
np.cumsum(A)#累加
p.diff(A)#每項與後一項的差(後-前)
np.nonzero(A)#將全部非零元素的行與列座標分割開,重構成兩個分別關於行和列的矩陣。
np.sort(A)#僅針對每一行進行從小到大排序操做:
np.transpose(A)#轉置
A.T
np.clip(A,5,9)#將矩陣中元素比最小值小的或者比最大值大的轉換爲最小值或者最大值。

索引,合併,分割

A[1][1]
print(A[1, 1:3]) #切片
A.flatten()#將矩陣展開爲一行
np.vstack((A,B))#將矩陣上下合併
np.hstack((A,B))#將矩陣左右合併
A[np.newaxis,:]#將array轉化爲矩陣,以便用上面兩個函數合併
A[np.newaxis,:]
np.concatenate((A,B,B,A),axis=0)#將多個矩陣合併
np.split(A, 3, axis=0)#矩陣橫向平分爲3個
np.array_split(A, 3, axis=0)#不均等分割
np.vsplit()
np.hsplit()

淺拷貝與深拷貝

= 的賦值方式會帶有關聯性html

copy() 的賦值方式沒有關聯性python

加速方法

Numpy 快速的矩陣相乘運算, 能將乘法運算分配到計算機中的多個核, 讓運算並行. 這年頭, 咱們什麼都想 多線程/ 多進程 (再次說出了機器學習同窗們的心聲~). 這也是 Numpy 爲何受人喜歡的一個緣由. 這種並行運算大大加速了運算速度.

橫縱對應

當你的計算中涉及合併矩陣, 不一樣形式的矩陣建立方式會給你不一樣的時間效果. 由於在 Numpy 中的矩陣合併等, 都是發生在一維空間裏, ! 不是咱們想象的二維空間中!git

a = np.zeros((200, 200), order='C')
b = np.zeros((200, 200), order='F')
N = 9999

def f1(a):
    for _ in range(N):
        np.concatenate((a, a), axis=0)

def f2(b):
    for _ in range(N):
        np.concatenate((b, b), axis=0)

t0 = time.time()
f1(a)
t1 = time.time()
f2(b)
t2 = time.time()

print((t1-t0)/N)     # 0.000040
print((t2-t1)/N)     # 0.000070

在 Numpy 中, 建立 2D Array 的默認方式是 「C-type」 以 row 爲主在內存中排列, 而若是是 「Fortran」 的方式建立的, 就是以 column 爲主在內存中排列.github

row 爲主的存儲方式, 若是在 row 的方向上合併矩陣, 將會更快. 由於只要咱們將思惟放在 1D array 那, 直接再加一個 row 放在1D array 後面就行了, 因此在測試中, f1 速度要更快. 可是在以 column 爲主的系統中, 往 1D array 後面加 row 的規則變複雜了, 消耗的時間也變長. 若是以 axis=1 的方式合併, 「F」 方式的 f2將會比 「C」 方式的 f1 更好。爲了速度, 推薦仍是儘可能使用 np.concatenate數組

copy慢 view快

減小建立無用的變量多線程

np.ravel()不用np.flatten()dom

view操做機器學習

a_view1 = a[1:2, 3:6]    # 切片 slice
a_view2 = a[:100]        # 同上
a_view3 = a[::2]         # 跳步
a_view4 = a.ravel()      # 上面提到了

copy操做函數

a_copy1 = a[[1,4,6], [2,4,6]]   # 用 index 選
a_copy2 = a[[True, True], [False, True]]  # 用 mask
a_copy3 = a[[1,2], :]        # 雖然 1,2 的確連在一塊兒了, 可是他們確實是 copy
a_copy4 = a[a[1,:] != 0, :]  # fancy indexing
a_copy5 = a[np.isnan(a), :]  # fancy indexing

使用 np.take(), 替代用 index 選數據的方法.學習

a = np.random.rand(1000000, 10)
N = 99
indices = np.random.randint(0, 1000000, size=10000)

def f1(a):
    for _ in range(N):
        _ = np.take(a, indices, axis=0)

def f2(b):
    for _ in range(N):
        _ = b[indices]

print('%f' % ((t1-t0)/N))    # 0.000393
print('%f' % ((t2-t1)/N))    # 0.000569

使用 np.compress(), 替代用 mask 選數據的方法.

mask = a[:, 0] < 0.5
def f1(a):
    for _ in range(N):
        _ = np.compress(mask, a, axis=0)

def f2(b):
    for _ in range(N):
        _ = b[mask]

print('%f' % ((t1-t0)/N))    # 0.028109
print('%f' % ((t2-t1)/N))    # 0.031013

out參數很快

a += 1                 # 0.011219
np.add(a, 1, out=a)    # 0.008843

帶有 out 的 numpy 功能都在這裏:Universal functions.

Reference

  1. 筆記大綱參考莫煩PYTHON
相關文章
相關標籤/搜索