首页 > 解决方案 > 沿维度扩展数组

问题描述

以下 Python 函数沿维度展开数组

def expand(x, dim,copies):
        trans_cmd = list(range(0,len(x.shape)))
        trans_cmd.insert(dim,len(x.shape))
        new_data = x.repeat(copies).reshape(list(x.shape) + [copies]).transpose(trans_cmd)
        return new_data

>>x = np.array([[1,2,3],[4,5,6]])
>>x.shape
(2, 3)
>>x_new = expand(x,2,4)
>>x_new.shape
(2,3,4)
>>x_new
array([[[1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3]],

       [[4, 4, 4, 4],
        [5, 5, 5, 5],
        [6, 6, 6, 6]]])

如何在 Julia 中复制此功能?

标签: julia

解决方案


而不是做一个重复 -> 重塑 -> permutedims (就像你在 numpy 中一样),我只是做一个重塑 -> 重复。考虑到行优先到列优先的转换,它看起来像这样:

julia> x = [[1,2,3] [4,5,6]]
3×2 Array{Int64,2}:
 1  4
 2  5
 3  6

julia> repeat(reshape(x, (1, 3, 2)), outer=(4,1,1))
4×3×2 Array{Int64,3}:
[:, :, 1] =
 1  2  3
 1  2  3
 1  2  3
 1  2  3

[:, :, 2] =
 4  5  6
 4  5  6
 4  5  6
 4  5  6

在 Julia 中有效地做到这一点的棘手部分是元组(1, 3, 2)(4, 1, 1). 虽然您可以将它们转换为数组并使用数组突变(就像您将其转换为 python 列表一样),但将它们保留为元组更有效。ntuple你的朋友在这里吗:

julia> function expand(x, dim, copies)
           sz = size(x)
           rep = ntuple(d->d==dim ? copies : 1, length(sz)+1)
           new_size = ntuple(d->d<dim ? sz[d] : d == dim ? 1 : sz[d-1], length(sz)+1)
           return repeat(reshape(x, new_size), outer=rep)
       end
expand (generic function with 1 method)

julia> expand(x, 1, 4)
4×3×2 Array{Int64,3}:
[:, :, 1] =
 1  2  3
 1  2  3
 1  2  3
 1  2  3

[:, :, 2] =
 4  5  6
 4  5  6
 4  5  6
 4  5  6

julia> expand(x, 2, 4)
3×4×2 Array{Int64,3}:
[:, :, 1] =
 1  1  1  1
 2  2  2  2
 3  3  3  3

[:, :, 2] =
 4  4  4  4
 5  5  5  5
 6  6  6  6

julia> expand(x, 3, 4)
3×2×4 Array{Int64,3}:
[:, :, 1] =
 1  4
 2  5
 3  6

[:, :, 2] =
 1  4
 2  5
 3  6

[:, :, 3] =
 1  4
 2  5
 3  6

[:, :, 4] =
 1  4
 2  5
 3  6

推荐阅读