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

I need to make a random choice with a given probability to select a tuple from the list.

EDIT: Probability for each tuple in a probabilistic list. I don’t know, forget parameter replacement, by default no. The same problem using an array instead of a list

The following code example will give me an error:

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) 

And the error:

 ValueError: a must be 1-dimensional 

How can i solve this?

+6
source share
3 answers

According to the doc function,

 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) 

So following this

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

should do what you want. ( p= added according to the comment, can be omitted if the values ​​are the same).

He selects a number from [0,1,2], and then selects this item from your list.

+7
source

The problem is that the list of tuples is interpreted as a 2D array, and choice only works with 1D arrays or integers (interpreted as "select from range"). See the documentation .

So, one way to fix this is to pass the len list of tuples, and then select the elements with the appropriate index (or indices), as described in another answer . If you first include lista_elegir in np.array , this will also work for multiple indexes. However, there are two more problems:

First, the way you call the function, probabilit will be interpreted as the third replace parameter, and not as probabilities, i.e. the list is interpreted as logical, which means that you select with a replacement, but the actual probabilities are ignored. You can easily check this by passing the third parameter as [1, 0, 0] . Use p=probabilit instead. Secondly, the probabilities must be added up to 1, exactly. You only have 0.999 . It seems that you will have to slightly distort the probabilities or just leave this parameter as None if they are all the same (an even distribution is assumed).

 >>> 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]]) 
+3
source

I know this post is very old, but I will leave it here just in case anyone else is here.

Converting a list to nparray worked for me. You can always convert it back to a list later.

 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) 
0
source

All Articles