代码行 `np.transpose(image_tensor, (2, 1, 0))` 有什么作用?

Cha*_*ker 2 python numpy

我在看一些代码,有一行说:

# transpose to standard format
# You might want to comment this line or reverse the shuffle
# if you will use a learning algorithm like CNN, since they like their channels separated.
image_standard_form = np.transpose(image, (2, 1, 0))
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚它做了什么。我查看了文档,但我不太明白转置参数中的“轴”是什么意思。它说:

axes : list of ints, optional
By default, reverse the dimensions, otherwise permute the axes according to the values given.
Run Code Online (Sandbox Code Playgroud)

但它并没有真正说明它的用途。此外,使用转置和元组的示例并不是很有见地(或者至少没有向我展示它应该做什么)。有人可以向我解释它应该做什么吗?

我也做了一个我自己的例子来弄清楚它的作用,但我不是 100% 我理解它:

>>> x
array([[[ 0.,  1.,  2.],
        [ 0.,  1.,  2.],
        [ 0.,  1.,  2.]],

       [[ 0.,  1.,  2.],
        [ 0.,  1.,  2.],
        [ 0.,  1.,  2.]],

       [[ 0.,  1.,  2.],
        [ 0.,  1.,  2.],
        [ 0.,  1.,  2.]]])
>>> np.transpose(x, (2, 1, 0))
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 1.,  1.,  1.],
        [ 1.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 2.,  2.,  2.],
        [ 2.,  2.,  2.],
        [ 2.,  2.,  2.]]])
Run Code Online (Sandbox Code Playgroud)

Kh4*_*tiK 6

假设你想访问一个元素:

elem = image[i, j, k]
Run Code Online (Sandbox Code Playgroud)

转置后,现在您应该使用以下命令访问相同的元素:

elem = image_standard_form[k, j, i]
Run Code Online (Sandbox Code Playgroud)

(2,1,0)在转指置换给指数。

对于 CNN,它可能想要转换一个形状的张量:

[width, height, channels]
Run Code Online (Sandbox Code Playgroud)

进入:

[channels, height, width]
Run Code Online (Sandbox Code Playgroud)