gpt4 book ai didi

julia - permutedims Julia 中的 perm 参数

转载 作者:行者123 更新时间:2023-12-05 09:26:05 27 4
gpt4 key购买 nike

我不能完全理解这个参数如何影响 permutedims 函数的功能。我读了official doc for this function多次:

permutedims(A::AbstractArray, perm)Permute the dimensions of array A. perm is a vector or a tuple of length ndims(A) specifying the permutation.

第一点对我来说是大胆的是 perm 可以是 TupleVector >ndims(A)。所以如果 A 是一个 3D 数组,那么 length(perm)==3 等等。但是,我无法理解排列部分是如何发生的。
然后,让我们考虑一个与他们在文档中带来的类似示例:

julia> A = reshape(Vector(1:18), (3,2,3))
3×2×3 Array{Int64, 3}:
[:, :, 1] =
1 4
2 5
3 6

[:, :, 2] =
7 10
8 11
9 12

[:, :, 3] =
13 16
14 17
15 18

julia> permutedims(A, (3, 2, 1))
3×2×3 Array{Int64, 3}:
[:, :, 1] =
1 4
7 10
13 16

[:, :, 2] =
2 5
8 11
14 17

[:, :, 3] =
3 6
9 12
15 18

由于上面的脚本在可视化方面有点长,并且难以理解,所以我在下图中将结果并排提供:

enter image description here

例如,我可以看到,每个 A 的内部矩阵的第一个元素出现在 permutedims 结果的每个内部矩阵的第一列中。但我不明白 perm=(3, 2, 1) 是怎么做到的!我应该如何解释 perm 参数的值(此处为 (3, 2, 1))? 而且,对我来说,当我尝试使用不同的 ndimssize 的另一个 A 示例时,它变得更加困难! 我要求解释关于 perm here ,但是我也看不懂。所以我决定把它作为一个独立的问题来问。

最佳答案

我认为从尺寸上看比看打印输出更容易。为清楚起见,请确保没有两个维度具有相同的大小:

julia> x = rand(10, 20, 3, 4);

julia> permutedims(x, (1,2,4,3)) |> size # exchange 3rd & 4th
(10, 20, 4, 3)

julia> invperm((1,2,4,3)) == (1,2,4,3) # easy case, self-inverse
true

julia> y = permutedims(x, (4,1,2,3)); # move the 4th dim to be 1st

julia> size(y)
(4, 10, 20, 3)

julia> y[:, 7, 13, 2] == x[7, 13, 2, :]
true

julia> invperm((4,1,2,3))
(2, 3, 4, 1)

julia> permutedims(x, (2,3,4,1)) |> size # put the 1st dim last
(20, 3, 4, 10)

对于上面的 3D 示例:

julia> A = reshape(1:18, (3, 2, 3));

julia> B = permutedims(A, (3, 2, 1)); # reverse order of dims

julia> A[1,1,:] == B[:,1,1] # these are the red circles
true

julia> A[2,1,:] == B[:,1,2] # these are the yellow circles
true

关于julia - permutedims Julia 中的 perm 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74509503/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com