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

How to use numpy.random.choice in a list of tuples?

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

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

下一个示例代码报错:

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

我该如何解决?

根据函数的文档,

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

问题是元组列表被解释为二维数组,而 choice 仅适用于一维数组或整数(解释为 "choose from range")。参见 the documentation

因此解决此问题的一种方法是传递元组列表的 len,然后选择具有相应索引(或多个索引)的元素,如 中所述。如果您先将 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]])

我知道这个 post 很旧,但是把它留在这里以防其他人在这里结束。

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

只使用 rundom

import random
import numpy as np

DIRECTIONS = [np.array([-1, 0]),
          np.array([0, 1]),
          np.array([1, 0]),
          np.array([0, -1])]

random.choice(DIRECTIONS)

结果得到元组之一

简单明了的简短解决方案

numpy 版本 1.19.2

import numpy as np

probs = [.1, .2, .7]
vals = [(3, 0), (3, 1), (3, 2)]
n_samples = 5  # choose so may elements from vals

np.random.seed(1)  # fix random seed for reproducibility
inds = np.random.choice(len(vals), n_samples, p=probs)
rand_vals = [vals[ind] for ind in inds]
print(rand_vals)

输出

[(3, 2), (3, 2), (3, 0), (3, 2), (3, 1)]