如何从此函数中获得一致的返回类型?

问题描述 投票:3回答:1

有什么方法可以使下面的函数返回一致的类型?我正在使用Julia GLM做一些工作(喜欢它)。我编写了一个函数,可以为数据集创建所有可能的回归组合。但是,我当前创建@formula的方法会为rhs的每个不同长度返回不同的类型。

using GLM

function compose(lhs::Symbol, rhs::AbstractVector{Symbol})
    ts = term.((1, rhs...))
    term(lhs) ~ sum(ts)
end

使用@code_warntype作为简单示例返回以下内容

julia> @code_warntype compose(:y, [:x])
Variables
  #self#::Core.Compiler.Const(compose, false)
  lhs::Symbol
  rhs::Array{Symbol,1}
  ts::Any

Body::FormulaTerm{Term,_A} where _A
1 ─ %1 = Core.tuple(1)::Core.Compiler.Const((1,), false)
│   %2 = Core._apply(Core.tuple, %1, rhs)::Core.Compiler.PartialStruct(Tuple{Int64,Vararg{Symbol,N} where N}, Any[Core.Compiler.Const(1, false), Vararg{Symbol,N} where N])
│   %3 = Base.broadcasted(Main.term, %2)::Base.Broadcast.Broadcasted{Base.Broadcast.Style{Tuple},Nothing,typeof(term),_A} where _A<:Tuple
│        (ts = Base.materialize(%3))
│   %5 = Main.term(lhs)::Term
│   %6 = Main.sum(ts)::Any
│   %7 = (%5 ~ %6)::FormulaTerm{Term,_A} where _A
└──      return %7

并检查一些不同输入的返回类型:

julia> compose(:y, [:x]) |> typeof
FormulaTerm{Term,Tuple{ConstantTerm{Int64},Term}}

julia> compose(:y, [:x1, :x2]) |> typeof
FormulaTerm{Term,Tuple{ConstantTerm{Int64},Term,Term}}

我们看到,随着rhs的长度改变,返回类型也改变。

我可以更改我的compose函数,使其始终返回相同的类型吗?这并不是一个大问题。为每个新数量的回归器进行编译仅需约70毫秒。这实际上更像是“我如何提高我的朱莉娅技能?”

statistics julia regression glm
1个回答
0
投票

[我认为您不能避免类型不稳定,因为~期望RHS是TermTupleTerm

但是,当您调用广播时,要付出的最大编译成本是term.((1, rhs...)),这是编译成本很高的。这是您可以更便宜的方式进行的操作:

function compose(lhs::Symbol, rhs::AbstractVector{Symbol})
    term(lhs) ~ ntuple(i -> i <= length(rhs) ? term(rhs[i]) : term(1) , length(rhs)+1)
end

或(这有点慢,但更像您的原始代码):

function compose(lhs::Symbol, rhs::AbstractVector{Symbol})
    term(lhs) ~ map(term, (1, rhs...))
end

最后,如果您正在执行此类计算,则可以使用公式接口删除,但直接将lmglm矩阵作为RHS馈入,在这种情况下,它应该能够避免额外的编译成本,例如:

julia> y = rand(10);

julia> x = rand(10, 2);

julia> @time lm(x,y);
  0.000048 seconds (18 allocations: 1.688 KiB)

julia> x = rand(10, 3);

julia> @time lm(x,y);
  0.000038 seconds (18 allocations: 2.016 KiB)

julia> y = rand(100);

julia> x = rand(100, 50);

julia> @time lm(x,y);
  0.000263 seconds (22 allocations: 121.172 KiB)
© www.soinside.com 2019 - 2024. All rights reserved.