numpy rollaxis-它到底是如何工作的?

2024-09-27 02:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在用纽比做实验时遇到了一个奇怪的(?)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的方法吗?)


Tags: 方法innpones矩阵数组out事情
3条回答

基本思想是它绕nd阵列的轴移动。 它接受axis参数所提到的轴,并将其置于start参数所提到的位置中;当这种情况发生时,在以下位置的剩余轴将向右移动,直到结束。如果忽略start参数,则会将所述轴移动到第一个位置(即,将作为第0个轴移动)

让我们用一个例子来理解它:

In [21]: arr = np.ones((3,4,5,6))

In [22]: arr.shape
Out[22]: (3, 4, 5, 6)
# here 0th axis is 3, 1st axis is 4, 2nd axis is 5, 3rd axis is 6

# moving `3`rd axis as `1`st axis
In [27]: np.rollaxis(arr, 3, 1).shape

# see how `6` which was the third axis has been moved to location `1`
Out[27]: (3, 6, 4, 5)

当移动轴(或者NumPy称之为滚动轴)时,该位置上已经存在的轴为传入轴腾出空间,随后的轴作为块朝右侧移动。

如果忽略start参数,则axis参数中的轴将移到前面(即移到第0个位置)。

In [29]: a.shape
Out[29]: (3, 4, 5, 6)

# ignoring the `start` moves the axis to the very front position.
In [30]: np.rollaxis(arr, 3).shape
Out[30]: (6, 3, 4, 5)

np.moveaxis比较

In [38]: arr.shape
Out[38]: (3, 4, 5, 6)

In [39]: np.rollaxis(arr, 0, -1).shape
Out[39]: (4, 5, 3, 6)

In [40]: np.moveaxis(arr, 0, -1).shape
Out[40]: (4, 5, 6, 3)

在上面的示例中,观察np.moveaxis如何进行循环移位,而np.rollaxis向右侧扩展


注意,这个rollaxis操作返回从NumPy 1.10.0开始的输入数组的视图

方法rollaxis

def rollaxis(a, axis, start=0):

start“位置重新分配所选axis

以你为例:

a = np.ones((4, 3, 2))
x = np.rollaxis(a, 2)
# x.shape = (2, 4, 3)

关于形状:rollaxis将把位于最后一个axis=2中的数字2带到自start=0以来的第一个位置。

通过使用

x2 = np.rollaxis(x, -2)
# x2.shape = (4,2,3)

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。

像这样:

>>> a.shape

(1, 2, 3, 4, 5, 6)

>>> np.rollaxis(a, 2, 4).shape

(1, 2, 4, 3, 5, 6)

如你所见,3号现在正好在5号之前。 注意:3不会移动到位置4,而是移动到最初位于位置4的值之前的位置(在本例中,原来是位置3)。

负数指定的位置与列表一样。换句话说,axis=-1指定最后一个位置。在我上面的例子中,-1位置有一个6,-2位置有一个5。轴和起点都可能为负。

你可以像我在上面做的那样用负数来表示:

>>> a.shape

(1, 2, 3, 4, 5, 6)

>>> np.rollaxis(a, -4, -2).shape

(1, 2, 4, 3, 5, 6)

如果未指定开始,则默认为0,这是第一个位置。这意味着,如果未指定开始,则指定的轴将始终移动到开始位置,该位置在最初位于0的1之前。

如果这让人困惑,这里还有一个更合理的解释: Reason why numpy rollaxis is so confusing?

相关问题 更多 >

    热门问题