random - 从自定义分布生成随机值

标签 random julia distribution

我的分布如下:

using Distributions
struct OrthoNNDist <: DiscreteMultivariateDistribution
    x0::Vector{Int64}
    oc::Array{Int64,2}
    x1s::Array
    prob::Float64
    #return a new uniform distribution with all vectors in x1s orthogonal to oc
    function OrthoNNDist(x0::Vector{Int}, oc::Array{Int,2})
        x1s = []
        for i = 1:size(oc)[2]
            x1 = x0 + oc[:, i]
            if nonneg(x1)
                push!(x1s, x1)
            end
            x1 = x0 - oc[:, i]
            if nonneg(x1)
                push!(x1s, x1)
            end
        end
        new(x0, oc, x1s, 1.0/length(x1s))
    end
end

Base.length(d::OrthoNNDist) = length(d.x0)

Distributions.rand(d::OrthoNNDist, N::Integer=1) = rand(d.x1s, 1)

Distributions.pdf(d::OrthoNNDist, x::Vector) = x in d.x1s ? D.prob : 0.0
Distributions.pdf(d::OrthoNNDist) = fill(d.prob, size(d.x1s))
Distributions.logpdf(d::OrthoNNDist, x::Vector) = log(PDF(d, x))

我想从中生成随机值,我不知道我是如何尝试的:rand(OrthoNNDist,1000)但它不起作用,我对它有点陌生概率编程,我不知道如何做到这一点。

<小时/>

最佳答案

不再提供函数nonneg,这很容易修复:

nonneg(x::Real) = zero(x) <= x
nonneg(x::Vector{<:Real}) = all(nonneg, x)

您写的几乎所有内容都很好:

using Distributions

struct OrthoNNDist <: DiscreteMultivariateDistribution
    x0::Vector{Int64}
    oc::Array{Int64,2}
    x1s::Array
    prob::Float64
    #return a new uniform distribution with all vectors in x1s orthogonal to oc
    function OrthoNNDist(x0::Vector{Int}, oc::Array{Int,2})
        x1s = []
        for i = 1:size(oc)[2]
            x1 = x0 + oc[:, i]
            if nonneg(x1)
                push!(x1s, x1)
            end
            x1 = x0 - oc[:, i]
            if nonneg(x1)
                push!(x1s, x1)
            end
        end
        new(x0, oc, x1s, 1.0/length(x1s))
    end
end

Base.length(d::OrthoNNDist) = length(d.x0)

Distributions.pdf(d::OrthoNNDist, x::Vector) = x in d.x1s ? D.prob : 0.0
Distributions.pdf(d::OrthoNNDist) = fill(d.prob, size(d.x1s))
Distributions.logpdf(d::OrthoNNDist, x::Vector) = log(PDF(d, x))

要让rand工作..你就快到了

using Distributions: rand

Distributions.rand(d::OrthoNNDist, n::Int=1) = rand(d.x1s, n)

现在有一些数据

julia> x0 = rand(1:1_000_000,5);
julia> oc = reshape(rand(1:1_000_000,25), (5,5));
julia> dist = OrthoNNDist(x0,oc);
julia> Distributions.rand(dist, 4)
4-element Array{Any,1}:
 [1330729, 656190, 927615, 470782, 1435138]
 [1382946, 1058057, 778316, 488440, 1304526]
 [1330729, 656190, 927615, 470782, 1435138]
 [1409093, 353679, 454229, 698320, 1271674]

(感谢 Mohamed Tarek 的指导)

关于random - 从自定义分布生成随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60075563/

相关文章:

python - 骰子实验结果的分布

c# - 洗牌(随机重新排列)一个 List<string>

sas - SAS中有放回的随机有序抽样

ios - iOS中的随机数?

math - 重写无限矩阵

sorting - 如何在Julia中按给定元素对元组进行排序?

iphone - 通过 App Store 分发第三方开发的应用程序

Python:如何让 for 循环每次打印列表中随机生成的项目?

julia - 我想找到 Julia 的 0 的数字 - 我的意思是最接近 0 的数字

python - 使用带有 seaborn 的 For 循环创建许多分布图