[英]How to reshape only last dimensions in numpy?
假設我的A
形狀為(...,96)
並且想要將其重塑為(...,32,3)
同時保持長度和先前尺寸的數量不變(如果有的話)。
這個怎么做?
如果我寫
np.reshape(A, (-1, 32, 2))
它將所有先前的尺寸展平為一個,我不希望這樣。
一種方法是使用與新的分割軸長度關聯的形狀信息來計算新的形狀元組,然后重塑-
A.reshape(A.shape[:-1] + (32,3))
樣品運行-
In [898]: A = np.random.rand(5,96)
In [899]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[899]: (5, 32, 3)
In [900]: A = np.random.rand(10,11,5,96)
In [901]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[901]: (10, 11, 5, 32, 3)
甚至適用於1D
數組-
In [902]: A = np.random.rand(96)
In [903]: A.reshape(A.shape[:-1] + (32,3)).shape
Out[903]: (32, 3)
之所以有效,是因為要連接的引導軸為空,因此僅在此處使用分割軸的長度-
In [904]: A.shape[:-1]
Out[904]: ()
In [905]: A.shape[:-1] + (32,3)
Out[905]: (32, 3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.