“numpy reshape(a, b) != .reshape(b, a).T”有更好的答案吗?

问题描述 投票:0回答:1

我在拼合图像时遇到了这个问题。考虑以下数组

>>> import numpy as np
>>> arr = np.array([[[1, 2],
                     [3, 4]],
                    [[1, 2],
                     [3, 4]]])
>>> arr.shape
(2, 2, 2)

我希望将其重塑为 4x2 数组 其中每个垂直切片都是展平的图像

1.使用
.reshape(2, 4).T

这样就达到了想要的效果

>>> arr_flatten = arr.reshape(2, 4).T
>>> arr_flatten
[[1 1]
 [2 2]
 [3 3]
 [4 4]]

2.使用
.reshape(4, 2)

这没有达到想要的效果

>>> arr_flatten = arr.reshape(4, 2)
>>> arr_flatten
[[1 2]
 [3 4]
 [1 2]
 [3 4]]

为什么第二种方法不起作用?

python arrays numpy reshape transpose
1个回答
0
投票

两次重塑以不同的方式创建数组。将

.reshape(2,4)
想象为在对元素进行计数时遍历数组,每次达到 4 时都会创建一个新行并重新开始计数。因此,括号中的计数为 1 (1)、2 (2)、3 (3)、4 (4)、新行、1 (1)、2 (2)、3 (3)、4 ( 4).对于
.reshape(4,2)
,它计数到 2 并开始一个新行。这样,1 (1), 2 (2),新行,3 (1),4 (2),新行,1 (1),2 (2),新行,3 (1),4 ( 1).

因此,

.reshape(2,4)
产生

array([[1, 2, 3, 4],
       [1, 2, 3, 4]])

并且产生

.reshape(4,2)

array([[1, 2],
       [3, 4],
       [1, 2],
       [3, 4]])

显然,它们的转置不相等。至于为什么给出正确的答案,这一切都取决于数据的含义及其排序方式。在本例中,由于图像位于 0 轴,因此

.reshape(2,4)
在创建新行之前会遍历整个 0 轴,因此会给出正确的结果。

© www.soinside.com 2019 - 2024. All rights reserved.