只是玩转Julia(1.0),我需要在Python/numpy/matlab中大量使用的一件事是squeeze
函数来降低单例尺寸。
我发现在Julia中执行此操作的一种方法是:
a = rand(3, 3, 1);
a = dropdims(a, dims = tuple(findall(size(a) .== 1)...))
第二行看起来有点麻烦,并且不容易立即阅读和解析(这也可能是我从其他语言带来的偏见)。但是,我想知道这是否是在Julia中执行此操作的规范方法吗?
最佳答案
这个问题的实际答案使我感到惊讶。您的要求可以改写为:
why doesn't
dropdims(a)
remove all singleton dimensions?
我将在这里从relevant issue引用蒂姆·霍利(Tim Holy):
it's not possible to have squeeze(A) return a type that the compiler can infer---the sizes of the input matrix are a runtime variable, so there's no way for the compiler to know how many dimensions the output will have. So it can't possibly give you the type stability you seek.
除了类型稳定性以外,您所编写的内容还具有其他一些令人惊讶的含义。例如,请注意:
julia> f(a) = dropdims(a, dims = tuple(findall(size(a) .== 1)...))
f (generic function with 1 method)
julia> f(rand(1,1,1))
0-dimensional Array{Float64,0}:
0.9939103383167442
总之,在
Base
中包含这样的方法,Julia会鼓励用户使用它,从而导致潜在的类型不稳定的代码,在某些情况下,它不会很快(某些核心开发人员正在竭力避免这样做)。在像Python这样的语言中,没有强制严格的类型稳定性,因此您会找到此类功能。当然,没有什么可以阻止您定义自己的方法。而且我认为您不会找到一种更简单的编写方法。例如,未实现的
Base
命题是以下方法:function squeeze(A::AbstractArray)
singleton_dims = tuple((d for d in 1:ndims(A) if size(A, d) == 1)...)
return squeeze(A, singleton_dims)
end
请注意使用它的潜在含义。
关于julia - 在Julia中删除单例尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52505760/