gpt4 book ai didi

Python Numpy : How to transpose only the last several dimensions

转载 作者:行者123 更新时间:2023-12-03 08:16:36 24 4
gpt4 key购买 nike

例如,如果我只想转置该数组的最后两个维度:a=np.random.randn(2,2,2,2,2),我会写类似:a.transpose((0,1,2,4,3) )。如何省略主要尺寸?有哪些简洁有效的方法?谢谢!

编辑,我知道如何简单地交换数组的形状和步幅,但我认为它看起来很乱:

strides=list(a.strides)
strides[-2], strides[-1]=strides[-1], strides[-2]
a.strides= strides

shape=list(a.shape)
shape[-2], shape[-1]=shape[-1], shape[-2]
a.shape= shape

我想知道是否有一种巧妙的方法可以做到这一点。

最佳答案

np.moveaxis 方法就是您想要的:

a = np.moveaxis(a, -1, -2)

关于Python Numpy : How to transpose only the last several dimensions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69193368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com