我有一个Bool向量,很简单[true, false]。我可以从该向量中抽取 10 个样本
rand([true,false], 10)
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能实现true以 80% 的概率false绘制并以 20% 的概率绘制的呢?
使用sample来自 StatsBase.jl的函数和Weights参数:
julia> using StatsBase
julia> sample([true, false], Weights([0.8, 0.2]), 10)
10-element Array{Bool,1}:
1
0
1
1
1
1
1
1
1
1
Run Code Online (Sandbox Code Playgroud)
为了确保你得到你想要的,你可以写:
julia> countmap(sample([true, false], Weights([0.8, 0.2]), 10^8))
Dict{Bool,Int64} with 2 entries:
false => 20003766
true => 79996234
Run Code Online (Sandbox Code Playgroud)
(当然,您的确切数字会有所不同)
此外,如果您特别需要二进制采样,您可以使用BernoulliDistributions.jl 中的分布:
julia> using Distributions
julia> rand(Bernoulli(0.8), 10)
10-element Array{Bool,1}:
0
1
1
0
1
1
1
1
1
1
julia> countmap(rand(Bernoulli(0.8), 10^8))
Dict{Bool,Int64} with 2 entries:
false => 20005900
true => 79994100
Run Code Online (Sandbox Code Playgroud)
(您可以期望此方法更快)
最后 - 如果你不想使用任何包并且需要一个二进制结果,你可以只写rand(10) .< 0.8,再次 - 你得到你想要的:
julia> countmap(rand(10^8) .< 0.8)
Dict{Bool,Int64} with 2 entries:
false => 20003950
true => 79996050
Run Code Online (Sandbox Code Playgroud)