在 Julia 中,在 statsbase 中创建权重向量

Posted

技术标签:

【中文标题】在 Julia 中,在 statsbase 中创建权重向量【英文标题】:In Julia, creating a Weights vector in statsbase 【发布时间】:2021-03-09 09:35:49 【问题描述】:

我正在和 Julia 玩一会儿。

考虑这个函数:

function drawValues(fromDistribution, byCount)

#=
inputs:
fromDistribution : 
    A 2D array
    Each element is an array with two elements
    The first one is a value, and the second one is the probability of that value
    We will draw a value out of this distribution from a random number generator
    
byCount :
    An integer
    We draw that many values from the source distribution

=#



values = []
wts    = []

for i = 1:length(fromDistribution)
    
    push!(values, fromDistribution[i][1])
    push!(wts   , fromDistribution[i][2])
    
end


w = Weights(wts)

res = []

for i = 1:byCount
    
    r = sample(values, w)
    push!(res, r)
    
end


plot(values, wts)
print(res)


end

这会引发错误:

错误: MethodError: 没有方法匹配权重(::ArrayAny,1, ::Float64) 最接近的候选者是:Weights(::var"#18#V", ::var"#16#S") 其中 var"#16#S"<:real var> 权重(::Any) 在 /home/hedgehog/.julia/packages/StatsBase/EA8Mh/src/weights.jl:16 堆栈跟踪:[1] 权重(::ArrayAny,1) 在 /home/hedgehog/.julia/packages/StatsBase/EA8Mh/src/weights.jl:16 [2] drawValues(::ArrayArrayFloat64,1,1, ::Int64) 在 /home/hedgehog/LASER.jl:51 [3] REPL[13]:1 [4] 的***范围 run_repl(::REPL.AbstractREPL, ::Any) 在 /build/julia/src/julia-1.5.3/usr/share/julia/stdlib/v1.5/REPL/src/REPL.jl:288

看来,第二个定义 (Weights(::ArrayAny,1)) 很合适。但不知何故,Julia 看到了两个输入参数?

请帮忙。

版本详情:

Julia 版本 1.5.3 提交 788b2c77c1* (2020-11-09 13:37 UTC) 平台信息: 操作系统:Linux (x86_64-pc-linux-gnu) CPU:AMD 锐龙 7 3700X 8 核处理器 WORD_SIZE:64 LIBM:libopenlibm LLVM: libLLVM-10.0.1 (ORCJIT, znver2)

【问题讨论】:

values = first.(fromDistribution)wts = last.(fromDistribution)而不是循环。 这是与on the Julia Discourse 相同的帖子。请不要交叉发布,或者至少提供链接以避免浪费人们的时间。 【参考方案1】:

你的Vectors 有任何类型的元素。

应该是:

wts = Float64[]

当您编写 wts=[] 时,它等同于 wts=Any[]

看看weight 方法:

julia> methods(weights)
# 3 methods for generic function "weights":
[1] weights(vs::AbstractArrayT,1 where T<:Real) in StatsBase at c:\JuliaPkg\Julia1.5.3\packages\StatsBase\EA8Mh\src\weights.jl:76
[2] weights(vs::AbstractArrayT,N where N where T<:Real) in StatsBase at c:\JuliaPkg\Julia1.5.3\packages\StatsBase\EA8Mh\src\weights.jl:77
[3] weights(model::StatisticalModel) in StatsBase at c:\JuliaPkg\Julia1.5.3\packages\StatsBase\EA8Mh\src\statmodels.jl:143

需要具有子类型为Real 的元素的容器。

同样推荐其他提供类型的容器:

value = Float64[]
res = Float64[]  # or maybe Int[] depending on what your code does

【讨论】:

以上是关于在 Julia 中,在 statsbase 中创建权重向量的主要内容,如果未能解决你的问题,请参考以下文章

如何在 C# 中创建/编辑 PNG 文件?

Julia - n 嵌套循环

从命名管道到提交日志的 Julia 输出

Julia:将 DataFrame 传递给函数会创建指向 DataFrame 的指针?

递归地改变绘图类型(有线,有点)。

将所有“使用”语句放在文件(Julia)的顶部是不是不好?