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

2024-05-20 00:38:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要做一个随机选择,在给定的概率下从列表中选择一个元组。

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

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

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

我该怎么解决?


Tags: 代码importnumpy编辑示例列表参数错误
3条回答

问题是元组列表被解释为2D数组,而choice只适用于1D数组或整数(解释为“choose from range”)。见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]])

根据职能部门的文件

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]中选择一个数字,然后从列表中选择该元素。

我知道这篇文章很老了,但还是把它留在这里,以防其他人到这里来。

对我有用的一件事是将列表转换为一个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)

相关问题 更多 >