在Julia中从两个分布中进行概率分布

时间:2017-08-25 15:44:53

标签: julia

using Distributions
d1 = Exponential(0.2)
d2 = Exponential(0.5)
p = 0.7

我是否有任何简单的方法在Julia中构建分布,其行为类似于我可以调用rand()rand!的分布,其行为如下:从分布d1绘制概率为p并从概率为d2的分布1-p中提取。谢谢。

2 个答案:

答案 0 :(得分:4)

您可以使用MixtureModel

julia> m = MixtureModel([d1,d2],[p,1-p])
MixtureModel{Distributions.Exponential{Float64}}(K = 2)
components[1] (prior = 0.7000): Distributions.Exponential{Float64}(θ=0.2)
components[2] (prior = 0.3000): Distributions.Exponential{Float64}(θ=0.5)

julia> mean(m)
0.29000000000000004

julia> pdf(m, 0)
4.1

julia> rand(m)
0.2574516697519676

julia> rand!(m, zeros(1,5))
1×5 Array{Float64,2}:
 0.0704624  0.264519  0.636179  0.11479  0.41158

答案 1 :(得分:2)

Distributions.jl基本上准备了定义新发行版的所有工具。所以,在这种情况下,我的尝试看起来像:

using Distributions

struct CompoundBernoulli{T<:Distributions.VariateForm,
                         S<:Distributions.ValueSupport} <:
         Distributions.Sampleable{T, S}
    p::Bernoulli
    d1::Distributions.Sampleable{T,S}
    d2::Distributions.Sampleable{T,S}
end

# outer constructor  
CompoundBernoulli(p::Real, 
                  d1::Distributions.Sampleable{S, T},
                  d2::Distributions.Sampleable{S, T}) where 
  {S<:Distributions.VariateForm, T<:Distributions.ValueSupport} = 
  CompoundBernoulli{S,T}(Bernoulli(p),d1,d2)

Base.rand(cb::CompoundBernoulli) = rand(cb.p)==0 ? rand(cb.d1) : rand(cb.d2)

有了这些定义:

julia> cb = CompoundBernoulli(0.7,Exponential(0.2),Exponential(0.5))
CompoundBernoulli{Distributions.Univariate,Distributions.Continuous}
(Distributions.Bernoulli{Float64}(p=0.7), 
Distributions.Exponential{Float64}(θ=0.2), 
Distributions.Exponential{Float64}(θ=0.5))

julia> rand(cb)
0.3247418465183849

julia> rand(cb,3,3)
3×3 Array{Float64,2}:
 0.33105   0.231418  0.271571
 0.413905  0.662144  1.42725 
 0.20196   0.091628  0.194761

可以定义更多功能,并且可以根据应用需要将功能专门用于此特定类型。