解讀numpy中改變數(shù)組維度的幾種方式
numpy改變數(shù)組維度的幾種方式
在進行深度學習或強化學習時經(jīng)常需要對數(shù)據(jù)的維度進行變換,本文總結(jié)了numpy中幾種常用的變換數(shù)據(jù)維度的方法
增加一個維度
在多維數(shù)組的最后一維再增加一個維度可以使用numpy.reshape或numpy.expand_dims或numpy.newaxis。
示例如下:
import numpy as np import matplotlib.pyplot as plt # 生成一個二維數(shù)據(jù) 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]] # 在多維數(shù)組的最后一維再增加一個維度 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)) # 上述四種方法的結(jié)果完全一致 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]]]
減小一個維度
如果多維數(shù)組的最后一維的長度為1,可以將該維去掉,去掉的方法可以使用numpy.reshape或numpy.squeeze。
示例如下:
# 假設(shè)欲將剛才增加一維生成的多維數(shù)組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]) # 上述四種方法的結(jié)果完全一致 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]]
將多維數(shù)組壓縮為一維數(shù)組
將多維數(shù)組壓縮為一維數(shù)組,可使用flatten或ravel以及reshape方法。
示例如下:
z1 = y.flatten() z2 = y.ravel() z3 = y.reshape(y.size) # 上述三種方法結(jié)果完全一致 assert(np.all(z1==z2)) assert(np.all(z2==z3)) print(z3) # 輸出為: # [ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11]
將多維數(shù)組壓縮為二維數(shù)組,0軸保持不變
在深度學習或強化學習中,有時需要將shape為(batches, d1, d2, d3,...)的多維數(shù)組轉(zhuǎn)化為shape為(batches, d1*d2*d3...)的數(shù)組,此時可以使用reshape進行轉(zhuǎn)化。
示例如下:
#生成多維數(shù)據(jù) 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]]] #轉(zhuǎn)化為二維數(shù)組 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數(shù)組-交換維度
比如對于numpy數(shù)組x,x.shape=[3 ,384 ,512],想要得到cv2讀入圖片的格式,即[384,512,3],則需以下兩行命令即可
x.swapaxes(0,2) x.swapaxes(0,1)
np.swapaxes(a,x,y) ,是ndarray對象的操作函數(shù),用來調(diào)換維度。
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pygame實現(xiàn)鍵盤的連續(xù)監(jiān)控
這篇文章主要為大家詳細介紹了pygame實現(xiàn)鍵盤的連續(xù)監(jiān)控,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04PYQT5 實現(xiàn)給listwidget的滾動條添加滾動信號
這篇文章主要介紹了PYQT5 實現(xiàn)給listwidget的滾動條添加滾動信號,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03tensorflow 用矩陣運算替換for循環(huán) 用tf.tile而不寫for的方法
今天小編就為大家分享一篇tensorflow 用矩陣運算替換for循環(huán) 用tf.tile而不寫for的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07