【问题标题】:Choose an event from a list of events happening with different probabilities从以不同概率发生的事件列表中选择一个事件
【发布时间】:2021-05-02 04:17:53
【问题描述】:

我有一个事件列表,这些事件在满足条件 X 时具有单独的发生概率,例如 [0.1, 0.9, 0.2]。它们加起来不等于 1。但是,当满足条件 X 时,最多可能发生其中一个。事件的数量是可变的。 我的意思是,如果列表中只有事件 A,则列表是例如[0.3]。如果 B 也在那里,例如 [0.3, 0.8]。然后问题是,其中哪一个发生了,或者没有。

代码:

event_prob_list = [0.3, 0.5, 0.8]

列表的长度是可变的。 我想要一个函数或分布,它给我一个索引,或者 None,根据它被选择。

我想出的一个解决方案是:1.) 随机打乱列表。 2.) 对于列表中的每个元素,扔一枚硬币;如果结果

但是,我不知道这在概率上是否正确,以及是否没有更好的函数/分布可供借鉴。 (我在关闭这个问题时确实编辑了它......)

【问题讨论】:

  • 奇怪的是,概率是“相互独立的”,但只有其中一个会发生。是否有可能满足条件 X 而没有一个发生?
  • 如何获得赞成票?这个问题缺少你需要回答的一切......
  • 你能举个代码例子吗?
  • @LizzAlice 示例代码和数据以及预期的结果。并且,如果可能的话,你到目前为止已经尝试过什么。
  • 如果您提供更具体的minimal reproducible example 会有所帮助。例如,目前尚不清楚这个“条件 X”是什么,以及当它满足时你期望发生什么。您的意思是,对于每个元素,您检查它是否可以以指定的概率发生?如果是个体,为什么只能发生其中之一?

标签: python probability


【解决方案1】:

你可以这样做:

import random

probs = [0.1, 0.2]
# get max value and create a list of `none` with length of `max*100`
# for this example we create a list of 20 `none`s
mx = int(max(probs) * 100)
probs_placeholder = ['none'] * mx

# then for each probability, we specify probabilty amount of indices to that prob.
# for example if we have 20 cells, 2 cells for 0.1 and 4 cells for 0.2
# because `4/20=0.2` and `2/20=0.1` 
probs_count = [int(mx*x) for x in probs]
index = 0
for i in range(len(probs)):
    probs_placeholder[index:probs_count[i]] = [probs[i]] * probs_count[i]
    index = probs_count[i]

selected_index = random.choice(range(len(probs_placeholder)))
selected_value = probs_placeholder[selected_index]


if selected_value == 'none':
    print('none selected')
else:
    # its possible to have duplicate probs,  So we should start counting until we reach to selected index. 
    acc = 0
    i = -1
    while acc < selected_index and i < len(probs):
        i += 1
        acc += probs_count[i]
    print(i)


【讨论】:

  • 这里的概率在哪里?您只需在元素之间随机选择。您可能想将choices 与一些weights 一起使用,但我个人仍然不明白这个问题是如何...
  • 将值更改为数字并不会改变您只是随机选择其中一个的事实,可能具有均匀分布...根据 OP,数字应该表明某些事情发生的概率,只是不清楚是什么......
  • @Tomerikoo 它已关闭,我的想法是将列表从[0.1, 0.3, 0.5] 扩展到[0.1, 0.3, 0.3, 0.3, 0.5, 0.5, 0.5, 0.5, 0.5] 然后我们可以随机选择并从初始列表中获取选定的索引。
  • 再一次,你错过了数字代表概率的观点。例如,第二个元素有 80% 的机会被选中。简单地使用choice 并不能反映出...
  • 是的,你是对的。它比看起来复杂。@Tomerikoo 但我认为至少它可以给一个起点。
猜你喜欢
  • 2012-02-08
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-20
相关资源
最近更新 更多