这是什么意思?
另外,如果
data.transpose(3, 0, 1, 2)
另外,如果
data.shape == (10, 10, 10)
,为什么会出现 ValueError: axes don't match array
错误?让我用 Python3 来讨论。
我在 Python 中使用转置函数,写作
data.transpose(3,0,1,2)
这是错误的,因为该操作需要 4 个维度,而你只提供了 3 个(例如 (10,10,10)
)。可以通过以下方式复现:
>>> a = np.arange(60).reshape((1,4,5,3))
>>> b = a.transpose((2,0,1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: axes don't match array
w,h,c = original_image.shape #10,10,10
modified_img = np.reshape((1,w,h,c)) #(1,10,10,10)
transpose
对于一个数组(矩阵)的操作就像名称所说的一样。但对于像你的高维数组,它基本上作为moveaxis
运行。那么3, 0, 1, 2是什么意思呢?>>> a = np.arange(60).reshape((4,5,3))
>>> b = a.transpose((2,0,1))
>>> b.shape
(3, 4, 5)
>>> c = np.moveaxis(a,-1,0)
>>> c.shape
(3, 4, 5)
>>> b
array([[[ 0, 3, 6, 9, 12],
[15, 18, 21, 24, 27],
[30, 33, 36, 39, 42],
[45, 48, 51, 54, 57]],
[[ 1, 4, 7, 10, 13],
[16, 19, 22, 25, 28],
[31, 34, 37, 40, 43],
[46, 49, 52, 55, 58]],
[[ 2, 5, 8, 11, 14],
[17, 20, 23, 26, 29],
[32, 35, 38, 41, 44],
[47, 50, 53, 56, 59]]])
>>> c
array([[[ 0, 3, 6, 9, 12],
[15, 18, 21, 24, 27],
[30, 33, 36, 39, 42],
[45, 48, 51, 54, 57]],
[[ 1, 4, 7, 10, 13],
[16, 19, 22, 25, 28],
[31, 34, 37, 40, 43],
[46, 49, 52, 55, 58]],
[[ 2, 5, 8, 11, 14],
[17, 20, 23, 26, 29],
[32, 35, 38, 41, 44],
[47, 50, 53, 56, 59]]])
显而易见,这两种方法的作用相同。
samples
, rows
, columns
, channels
) 转换为 (samples
, channels
, rows
, cols
),可能是从 opencv 到 pytorch。请查看numpy.transpose。
使用transpose(a, argsort(axes))函数并指定axes参数,可以将张量的转置倒转回来。
对于一维数组,转置返回原始数组的未更改视图。
e.g.
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>>
>>> np.transpose(x)
array([[0, 2],
[1, 3]])
您在转置中指定了太多的值
>>> a = np.arange(8).reshape(2,2,2)
>>> a.shape (2, 2, 2)
>>> a.transpose([2,0,1])
array([[[0, 2],
[4, 6]],
[[1, 3],
[5, 7]]])
>>> a.transpose(3,0,1,2) Traceback (most recent call last): File "<interactive input>", line 1, in <module> ValueError: axes don't match array
>>>
data.transpose(2, 0, 1)
。对于所有的i,j,k,l
,以下内容是正确的:
arr[i, j, k, l] == arr.transpose(3, 0, 1, 2)[l, i, j, k]
transpose(3, 0, 1, 2)
可以将数组的维度从 (a, b, c, d)
调整为 (d, a, b, c)
:
>>> arr = np.zeros((10, 11, 12, 13))
>>> arr.transpose(3, 0, 1, 2).shape
(13, 10, 11, 12)
np.transpose
函数的第二个参数是axes
,它是一个 整数列表,可选,默认情况下会反转维度,否则根据给定的值排列轴。.
例如:
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.transpose(x, (0,1))
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.transpose(x, (1,0))
array([[0, 3, 6],
[1, 4, 7],
[2, 5, 8]])
np.zeros((0, 1, 2, 3)).transpose(3, 0, 1, 2).shape
实际上等于(3, 0, 1, 2)
。 - Mateen Ulhaq