假设我有 A
形状(...,96)
想把它改造成(...,32,3)
保持前面维度的长度和数量(如果有的话)完整无缺。
这该怎么做?
如果我写
np.reshape(A, (-1, 32, 2))
它会将所有先前的维度展平为一个我不想要的单一维度。
最佳答案
一种方法是使用与新分割轴长度连接的形状信息计算新的形状元组,然后重新整形 -
A.reshape(A.shape[:-1] + (32,3))
sample 运行 -
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)
关于python - 如何仅 reshape numpy中的最后一个维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183967/