Numpy.random.choice vs random.choice

Why doesn't numpy.random.choice work the same as random.choice? When I do this:

 >>> random.choice([(1,2),(4,3)])
 (1, 2)

      

He works.

But when I do this:

 >>> np.random.choice([(1,2), (3,4)])
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "mtrand.pyx", line 1393, in mtrand.RandomState.choice 
 (numpy/random/mtrand/mtrand.c:15450)
 ValueError: a must be 1-dimensional

      

How do I achieve the same behavior as random.choice () in numpy.random.choice ()?

+3


source to share


1 answer


Ok np.random.choice

, as noted in the docs expects a 1D array and your input, if expressed as an array, will 2D

. So it won't just work.

To make it work, we can feed the length of the input and let it pick one index, which when indexed on the input will be equivalent to from random.choice

as shown below -

out = a[np.random.choice(len(a))] # a is input

      

Example run -



In [74]: a = [(1,2),(4,3),(6,9)]

In [75]: a[np.random.choice(len(a))]
Out[75]: (6, 9)

In [76]: a[np.random.choice(len(a))]
Out[76]: (1, 2)

      

Alternatively, we can convert the input to a 1D array of a dtype object, and this will allow us to directly use np.random.choice

as shown below -

In [131]: a0 = np.empty(len(a),dtype=object)

In [132]: a0[:] = a

In [133]: a0.shape
Out[133]: (3,)  # 1D array

In [134]: np.random.choice(a0)
Out[134]: (6, 9)

In [135]: np.random.choice(a0)
Out[135]: (4, 3)

      

+11


source







All Articles