I'm using 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]. 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.
Why do operations like np.transpose
don't have their in-place counterpart?
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.
NumPy Matrix transpose() Python numpy module is mostly used to work with arrays in Python. We can use the transpose() function to get the transpose of an array.
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
From 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(A, B)
True
So, you can safely transpose your data withnp.transpose
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With