解讀numpy中改變數組維度的幾種方式
numpy改變數組維度的幾種方式
在進行深度學習或強化學習時經常需要對數據的維度進行變換,本文總結了numpy中幾種常用的變換數據維度的方法
增加一個維度
在多維數組的最后一維再增加一個維度可以使用numpy.reshape或numpy.expand_dims或numpy.newaxis。
示例如下:
import numpy as np import matplotlib.pyplot as plt # 生成一個二維數據 x = np.array(range(12)) x = np.reshape(x, (3,4)) print(x) # 輸出為: # [[ 0 ?1 ?2 ?3] # ?[ 4 ?5 ?6 ?7] # ?[ 8 ?9 10 11]] # 在多維數組的最后一維再增加一個維度 y1 = np.expand_dims(x, axis=x.ndim) y2 = np.expand_dims(x, axis=-1) y3 = x[:,:,np.newaxis] y4 = np.reshape(x, (*x.shape,1)) # 上述四種方法的結果完全一致 assert(np.all(y1==y2)) assert(np.all(y2==y3)) assert(np.all(y3==y4)) print(y4) # 輸出為: # [[[ 0] # ? [ 1] # ? [ 2] # ? [ 3]] # ?[[ 4] # ? [ 5] # ? [ 6] # ? [ 7]] # ?[[ 8] # ? [ 9] # ? [10] # ? [11]]]
減小一個維度
如果多維數組的最后一維的長度為1,可以將該維去掉,去掉的方法可以使用numpy.reshape或numpy.squeeze。
示例如下:
# 假設欲將剛才增加一維生成的多維數組y4的最后一維去掉 y = y4 x1 = np.squeeze(y, axis=(y.ndim-1)) x2 = np.squeeze(y) x3 = np.squeeze(y, axis=-1) x4 = np.reshape(y, y.shape[:-1]) # 上述四種方法的結果完全一致 assert(np.all(x1==x2)) assert(np.all(x2==x3)) assert(np.all(x3==x4)) print(x4) # 輸出為: # [[ 0 ?1 ?2 ?3] # ?[ 4 ?5 ?6 ?7] # ?[ 8 ?9 10 11]]
將多維數組壓縮為一維數組
將多維數組壓縮為一維數組,可使用flatten或ravel以及reshape方法。
示例如下:
z1 = y.flatten() z2 = y.ravel() z3 = y.reshape(y.size) # 上述三種方法結果完全一致 assert(np.all(z1==z2)) assert(np.all(z2==z3)) print(z3) # 輸出為: # [ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11]
將多維數組壓縮為二維數組,0軸保持不變
在深度學習或強化學習中,有時需要將shape為(batches, d1, d2, d3,...)的多維數組轉化為shape為(batches, d1*d2*d3...)的數組,此時可以使用reshape進行轉化。
示例如下:
#生成多維數據 d0 = np.expand_dims(x, axis=0) d1 = np.repeat(d0, 3, axis=0) print(d1) # 輸出為 # [[[ 0 ?1 ?2 ?3] # ? [ 4 ?5 ?6 ?7] # ? [ 8 ?9 10 11]] # ?[[ 0 ?1 ?2 ?3] # ? [ 4 ?5 ?6 ?7] # ? [ 8 ?9 10 11]] # ?[[ 0 ?1 ?2 ?3] # ? [ 4 ?5 ?6 ?7] # ? [ 8 ?9 10 11]]] #轉化為二維數組 d2 = np.reshape(d1, (d1.shape[0], d1[0].size)) print(d2) # 輸出為: # [[ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11] # ?[ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11] # ?[ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11]]
numpy數組-交換維度
比如對于numpy數組x,x.shape=[3 ,384 ,512],想要得到cv2讀入圖片的格式,即[384,512,3],則需以下兩行命令即可
x.swapaxes(0,2) x.swapaxes(0,1)
np.swapaxes(a,x,y) ,是ndarray對象的操作函數,用來調換維度。
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
tensorflow 用矩陣運算替換for循環(huán) 用tf.tile而不寫for的方法
今天小編就為大家分享一篇tensorflow 用矩陣運算替換for循環(huán) 用tf.tile而不寫for的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07