问题描述
考虑两个 1-dim 数组,一个包含可供选择的项目,一个包含绘制另一个列表的项目的概率.
Consider two 1-dim arrays, one with items to select from and one containing the probabilities of drawing the item of the other list.
items = ["a", 2, 5, "h", "hello", 3]
weights = [0.1, 0.1, 0.2, 0.2, 0.1, 0.3]
在 Julia 中,如何使用 weights
随机选择 items
中的一个项目来加权绘制给定项目的概率?
In Julia, how can one randomly select an item in items
using weights
to weight the probability to drawing a given item?
推荐答案
使用StatsBase.jl
包,即
Pkg.add("StatsBase") # Only do this once, obviously
using StatsBase
items = ["a", 2, 5, "h", "hello", 3]
weights = [0.1, 0.1, 0.2, 0.2, 0.1, 0.3]
sample(items, Weights(weights))
或者如果你想采样很多:
Or if you want to sample many:
# With replacement
my_samps = sample(items, Weights(weights), 10)
# Without replacement
my_samps = sample(items, Weights(weights), 2, replace=false)
(在 Julia < 1.0 中,Weights
被称为 WeightVec
).
(In Julia < 1.0, Weights
was called WeightVec
).
您可以了解更多关于 Weights
及其存在的原因 在文档中.StatsBase
中的采样算法非常高效,旨在根据输入的大小使用不同的方法.
You can learn more about Weights
and why it exists in the docs. The sampling algorithms in StatsBase
are very efficient and designed to use different approaches depending on the size of the input.
这篇关于如何从 Julia 的加权数组中选择一个随机项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!