使用具有不同参数的向量的Distributions.jl从给定分布中获取样本数据

时间:2018-03-28 18:22:25

标签: types julia distribution

我想我可以找到一些不同的黑客来做我想做的事,但我不确定什么是朱莉娅最好的做法。

我想编写一个函数来生成具有不同参数的给定分布类型的样本。使用Distributions.jl包,似乎我需要为每组参数创建适当分布的对象,并将这些参数作为参数传递。为此,我需要以某种方式传递分发的类型,然后从该类型创建对象。这里最好使用参数函数吗?或者有一个分发对象参数并使用typeof?

我当前的代码在下面,它似乎可以工作,但我觉得必须传递一个随机对象来指定分发类型,而不是以更优雅的方式传递类型本身。感谢kludge-y。 p>

function generateSamples(dist::UnivariateDistribution, thetas::AbstractVector, numSamples::Array{Int64,1}; shuffled=true)
    @assert length(thetas) == length(numSamples)
    M=length(thetas)
    N=sum(numSamples)
    data=zeros(Float64, N)
    n=0
    for i in 1:M
        n_i=numSamples[i]
        dist_i=typeof(dist)(thetas[i]...)
        for j in 1:n_i
            data[n+j]=rand(dist_i)
        end
        n+=n_i
    end
    if shuffled
        shuffle!(data)
    end
    return data
end

1 个答案:

答案 0 :(得分:0)

我会怎样做,

using Distributions

function foo(::Type{T}, numsamples, dist_parameters...) where T<:Distribution
    dist = T(dist_parameters...)
    ...
end

foo(Normal, 5)

我不知道您需要哪种分发参数,因此您不能在签名结束时使用Varargs。我认为这是一个很好的做法和Julia方式(即创建一个整数0的数组,你可以调用zeros(Int, ...)

https://docs.julialang.org/en/latest/manual/methods/#Parametric-Methods-1

https://docs.julialang.org/en/latest/manual/types/