【问题标题】:How do I select a random item from a weighted array in Julia?如何从 Julia 的加权数组中选择一个随机项?
【发布时间】:2015-02-18 00:43:14
【问题描述】:

考虑两个 1-dim 数组,一个包含可供选择的项目,一个包含绘制另一个列表中的项目的概率。

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

在 Julia 中,如何使用 weights 随机选择 items 中的一个项目来加权绘制给定项目的概率?

【问题讨论】:

  • @Prix 感谢您的更新。在此类问题的标题中指明感兴趣的语言不是很重要吗?也许在问题末尾的括号中?
  • 好的,谢谢。确实,能够订购标签真是太好了。
  • 希望你喜欢这种方式,我认为没有理由不在那里拥有它,所以我想这取决于个人喜好;)

标签: arrays random julia random-sample


【解决方案1】:

使用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))

或者如果你想采样很多:

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

(在 Julia Weights 被称为 WeightVec)。

您可以详细了解Weights 以及它存在的原因in the docsStatsBase 中的采样算法非常高效,旨在根据输入的大小使用不同的方法。

【讨论】:

    【解决方案2】:

    这是一个更简单的方法,它只使用 Julia 的基础库:

    sample(items, weights) = items[findfirst(cumsum(weights) .> rand())]
    

    例子:

    >>> sample(["a", 2, 5, "h", "hello", 3], [0.1, 0.1, 0.2, 0.2, 0.1, 0.3])
    "h"
    

    这比StatsBase.jl效率低,但对于小向量来说没问题。

    另外,如果weights 不是归一化向量,您需要这样做:cumsum(weights ./ sum(weights))

    【讨论】:

    • 我可以使用它从列表中生成多个元素(无需替换)吗?
    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 2011-11-14
    • 2011-01-24
    • 2017-07-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多