如何在元组列表中使用numpy.random.choice?

问题描述 投票:6回答:3

我需要随机选择具有从列表中选择元组的给定概率。

编辑:每个元组的概率在概率列表中我不知道忘记参数替换,默认情况下是无同样的问题使用数组而不是列表

下一个示例代码给出了一个错误:

import numpy as np

probabilit = [0.333, 0.333, 0.333]
lista_elegir = [(3, 3), (3, 4), (3, 5)]

np.random.choice(lista_elegir, 1, probabilit)

错误是:

ValueError: a must be 1-dimensional

我怎么解决这个问题?

python numpy random
3个回答
7
投票

根据函数的文档,

a : 1-D array-like or int
    If an ndarray, a random sample is generated from its elements.
    If an int, the random sample is generated as if a was np.arange(n)

所以那之后

lista_elegir[np.random.choice(len(lista_elegir),1,p=probabilit)]

应该做你想做的事。 (p=根据评论添加;如果值是统一的,可以省略)。

它从[0,1,2]中选择一个数字,然后从列表中选择该元素。


3
投票

问题是元组列表被解释为2D数组,而choice仅适用于1D数组或整数(解释为“从范围中选择”)。见the documentation

因此,解决此问题的一种方法是传递元组列表的len,然后选择具有相应索引(或索引)的元素,如other answer中所述。如果你首先将lista_elegir变成np.array,这也适用于多个索引。但是,还有两个问题:

首先,你调用函数的方式,probabilit将被解释为第三个参数replace,而不是概率,即列表被解释为布尔值,意味着你选择替换,但实际的概率被忽略。您可以通过将第三个参数作为[1, 0, 0]传递来轻松检查。请改用p=probabilit。其次,概率必须总和为1。你的只是0.999。看起来你必须略微倾斜概率,或者只是将它们作为None保留,如果它们都是相同的(因此假设均匀分布)。

>>> probabilit = [0.333, 0.333, 0.333]
>>> lista_elegir = np.array([(3, 3), (3, 4), (3, 5)]) # for multiple indices
>>> indices = np.random.choice(len(lista_elegir), 2, p=probabilit if len(set(probabilit)) > 1 else None)
>>> lista_elegir[indices]
array([[3, 4],
       [3, 5]])

2
投票

我知道这篇文章很老了,但是留在这里以防其他人到此为止。

对我有用的一点是将列表转换为nparray。您可以随时将其转换回列表。

import numpy as np

numSamples = 2    
probabilit = [0.333, 0.333, 0.333] 
lista_elegir = [(3, 3), (3, 4), (3, 5)]

lista_elegir_arr = np.array(lista_elegir)

#make sure probabilities sum to 1, and if they are all the same they are not needed
np.random.choice(lista_elegir_arr, numSamples, p = None)
© www.soinside.com 2019 - 2024. All rights reserved.