julia - 沿维度扩展数组
问题描述
以下 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 中复制此功能?
解决方案
而不是做一个重复 -> 重塑 -> 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
推荐阅读
- r - 在R中通过唯一值创建一个变量来表示值范围的最大值
- oracle - 将数据从 Oracle 移动到 Sybase - 字符串问题
- python - 如何使用opencv检测摄像机中的黑色?
- gitlab - 通过 GitLab API 下载已手动上传的文件
- vb.net - VB.Net 2003 - 如何创建具有绑定列能力的 DataGrid 按钮列?
- ruby - 如何为 pre ruby 1.9.1 实现 string.codepoints
- oracle - PostgreSQL 中的 Oracle DBMS_APPLICATION_INFO.SET_MODULE 等效项
- react-native - 减速器方法不调用?
- javascript - 在Angular 6上解析和忽略多维数组中的空数据
- ios - 您可以在同一个 iOS 企业帐户上使用不同的分发证书来签署应用程序吗?