2017-08-25 76 views
3
using Distributions 
d1 = Exponential(0.2) 
d2 = Exponential(0.5) 
p = 0.7 

有没有简单的方法,我构建朱莉娅分布,表现得像在分配我可以打电话rand()rand!,其行为如下:从分布d1平局概率为p,并以概率1-p从分布d2中抽取。谢谢。建立从两个分布的概率分布在朱莉娅

回答

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 
+0

谢谢马特。此解决方案效果更好。有一个很好的机会将这样的东西烘焙到Distributions包中。现在我会记住它。 –

+0

谢谢,这是一个不错的解决方案。 –

+0

如果我想要其中一个发行版返回其值-1(好像我在制作https://en.wikipedia.org/wiki/Laplace_distribution),那么我该怎么做?它不喜欢'MixtureModel([d1,-d2],[p,1-p])' –

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 

更多的功能可以被定义和应用需要的功能,可以专门用于这种特定类型。

+0

非常感谢您 –

+2

布拉沃如此迅速地滚动您的版本。它实际上非常接近内置'MixtureModel'的定义!他们只是使用分类分布而不是伯努利,因此它可以支持两个以上组件的混合。 –