将 StatsBase.jl 权重方法添加到 Julia 中的函数

Adding StatsBase.jl weights methods to a function in Julia

我正在尝试向类似于下面示例函数 my_function 的函数添加方法。当传递 StatsBase.jl 包中 AbstractWeights 的任何子类型时,应分派这些方法。

使用 Base 包中的抽象和原始类型编写示例函数时,我没有遇到任何问题。例如

function my_function(v::Array{<:Real,1})
    return sum(v .* 3)/length(v)
end

function my_function(v::Array{<:Real,1}, w::Array{<:Real,1})
    return  sum(v .* w .* 3)/sum(w)
 end

v = [1,2,3]

w = [3,2,1]

my_function(v)
# 6.0
my_function(v, w)
# 5.0

但是,当为来自 StatsBase.jl 的类型添加方法时,我得到 MethodError 错误:

using StatsBase

my_function(v::Array{<:Real,1}, w::Array{<:AbstractWeights,1}) = my_function(v,w)

my_function(v::Array{<:Real,1}, w::Array{Weights,1}) = my_function(v,w)

my_function(v, pweights(w))
# ERROR: LoadError: MethodError: no method matching my_function(::Vector{Int64}, ::ProbabilityWeights{Int64, Int64, Vector{Int64}})

my_function(v, weights(w))
# ERROR: LoadError: MethodError: no method matching my_function(::Vector{Int64}, ::Weights{Int64, Int64, Vector{Int64}})

如何编写上述 StatsBase.jl 权重类型的方法?

如果功能正常,下面应该是true

my_function(v, w) == my_function(v, weights(w)) == my_function(v, pweights(w)) == my_function(v, fweights(w))
# true

这里有几个问题:

  • AbstractWeights已经是vector了,所以不需要用vector包裹起来;
  • 您的实现是递归的(方法调用自身)。

所以你应该实现代码的方式是:

my_function(v::Vector{<:Real}, w::AbstractWeights) = sum(v .* w .* 3)/sum(w)