所以我在用纽比做实验时遇到了一个奇怪的(?)rollaxis方法中的行为。
In [81]: a = np.ones((4, 3, 2))
In [82]: a.shape
Out[82]: (4, 3, 2)
In [83]: x = np.rollaxis(a, 2)
In [84]: x.shape
Out[84]: (2, 4, 3)
In [85]: np.rollaxis(x, -2).shape
Out[85]: (4, 2, 3)
难道-2不应该反转滚动轴吗?我要做的是应用一个矩阵,它只能在2坐标为第一坐标时应用。但我想把我的数组恢复到原来的形式。我找到的唯一工作是应用np.rollaxis(x, 2)
两次,或者应用np.rollaxis(x, 0, start=3)
。我只是通过猜测找到了这些,我不知道它们为什么有用。他们似乎也掩盖了我真正想做的事情。有人能解释一下我该如何“逆转”一个滚动,或者我做错了什么吗?
(有什么Python的方法吗?)
基本思想是它绕nd阵列的轴移动。 它接受
axis
参数所提到的轴,并将其置于start
参数所提到的位置中;当这种情况发生时,在以下位置的剩余轴将向右移动,直到结束。如果忽略start
参数,则会将所述轴移动到第一个位置(即,将作为第0个轴移动)让我们用一个例子来理解它:
当移动轴(或者NumPy称之为滚动轴)时,该位置上已经存在的轴为传入轴腾出空间,随后的轴作为块朝右侧移动。
如果忽略
start
参数,则axis
参数中的轴将移到前面(即移到第0个位置)。与
np.moveaxis
比较在上面的示例中,观察
np.moveaxis
如何进行循环移位,而np.rollaxis
仅向右侧扩展。注意,这个rollaxis操作返回从NumPy 1.10.0开始的输入数组的视图
方法
rollaxis
在
start
“位置重新分配所选axis
以你为例:
关于形状:
rollaxis
将把位于最后一个axis=2
中的数字2
带到自start=0
以来的第一个位置。通过使用
rollaxis
将带上第二个最后一个轴axis=-2
的数字4,并在第一个位置重新分配,因为start=0
。这就解释了结果(4,2,3)
,而不是(4,3,2)
。遵循相同的逻辑,这解释了为什么两次应用
rollaxis(a,2)
会使数组形状返回到初始形状。np.rollaxis(x, 0, start=3)
也可以工作,因为第一个轴转到最后一个轴,换句话说,(2,4,3)中的数字2转到最后一个位置(4,3,2)。rollaxis(tensor,axis,start)将axis参数指定的轴移动到位于start的轴之前的位置,没有例外。
假设轴是(1,2,3,4,5,6)如果轴指向3,开始点指向5,那么在滚动之后,3将刚好在5之前。因为我的例子中的3在维度元组的位置2,axis=2。另外,因为5在位置4,所以start=4。
像这样:
如你所见,3号现在正好在5号之前。 注意:3不会移动到位置4,而是移动到最初位于位置4的值之前的位置(在本例中,原来是位置3)。
负数指定的位置与列表一样。换句话说,axis=-1指定最后一个位置。在我上面的例子中,-1位置有一个6,-2位置有一个5。轴和起点都可能为负。
你可以像我在上面做的那样用负数来表示:
如果未指定开始,则默认为0,这是第一个位置。这意味着,如果未指定开始,则指定的轴将始终移动到开始位置,该位置在最初位于0的1之前。
如果这让人困惑,这里还有一个更合理的解释: Reason why numpy rollaxis is so confusing?
相关问题 更多 >
编程相关推荐