[英]How to transpose numpy ndarray in place?
I'm using numpy. 我正在使用numpy。
I have an ndarray with shape of [T, H, W, C] and I want to transpose it to become like: [T, C, H, W]. 我有一个形状为[T,H,W,C]的ndarray,我想把它转换为:[T,C,H,W]。 However, this array is huge and I want to be memory-efficient. 但是,这个阵列非常庞大,我想要节省内存。
But I just found np.transpose
to do this which is not in-place . 但我刚发现np.transpose
来做这个不到位的 。
Why do operations like np.transpose
don't have their in-place counterpart? 为什么像np.transpose
这样的操作没有它们的原位对应物?
I used to think that any operation named np.Bar
would have its in-place counterpart named np.Bar_
, only to find that this is not the truth. 我曾经认为任何名为np.Bar
操作都会有一个名为np.Bar
的就地对象, np.Bar_
发现这不是事实。
From np.transpose
docs 来自np.transpose
docs
A view is returned whenever possible. 尽可能返回视图。
meaning no extra memory is allocated for the output array. 意味着没有为输出数组分配额外的内存。
>>> import numpy as np
>>> A = np.random.rand(2, 3, 4, 5)
>>> B = np.transpose(A, axes=(0, 3, 1, 2))
>>> A.shape
(2, 3, 4, 5)
>>> B.shape
(2, 5, 3, 4)
You can use np.shares_memory
to check if B
is a view of A
: 您可以使用np.shares_memory
来检查B
是否是A
的视图:
>>> np.shares_memory(A, B)
True
So, you can safely transpose your data with np.transpose
. 因此,您可以使用np.transpose
安全地转置数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.