如何从Julia的加权数组中选择一个随机项目?

问题描述:

考虑两个1-dim数组,其中一个具有可供选择的项目,另一个包含绘制另一个列表项目的概率。如何从Julia的加权数组中选择一个随机项目?

items = ["a", 2, 5, "h", "hello", 3] 
weights = [0.1, 0.1, 0.2, 0.2, 0.1, 0.3] 

在利亚,如何可以使用一个到weights重量绘制的给定项目的概率随机地选择在items的项目?

+0

@Prix感谢您的更新。在这个问题的标题中注明兴趣语言是否很重要?也许在问题结尾的括号中? – 2014-12-19 05:02:11

+0

好的,谢谢。事实上,能够订购标签真是太棒了。 – 2014-12-19 05:09:09

+0

希望你喜欢这样,我觉得没有理由不在那里,所以我想它归结为个人喜好;) – Prix 2014-12-19 05:15:24

使用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, WeightVec(weights)) 

或者,如果你想品尝到许多:

# With replacement 
my_samps = sample(items, WeightVec(weights), 10) 
# Without replacement 
my_samps = sample(items, WeightVec(weights), 2, replace=false) 

您可以了解更多关于WeightVec,为什么它存在in the docsStatsBase中的采样算法非常高效,可根据输入的大小使用不同的方法。