numpy.random.choice与random.choice

问题描述:

为什么numpy.random.choice不能与random.choice一样工作?当我这样做时:

Why does numpy.random.choice not work the same as random.choice? When I do this :

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

有效.

但是当我这样做时:

 >>> 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

如何实现与numpy.random.choice()中的random.choice()相同的行为?

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

np.random.choice 期望是一维数组,并且当表示为数组时,您的输入将是2D.因此,它不会像那样简单地工作.

Well np.random.choice as noted in the docs, expects a 1D array and your input when expressed as an array would be 2D. So, it won't work simply like that.

要使其工作,我们可以输入输入的长度,并让它选择一个索引,当索引到输入中时,它等于random.choice中的一个,如下所示-

To make it work, we can feed in the length of the input and let it select one index, which when indexed into the input would be the equivalent one from random.choice, as shown below -

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

样品运行-

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)

或者,我们可以将输入转换为对象dtype的一维数组,这将使我们可以直接使用np.random.choice,如下所示-

Alternatively, we can convert the input to a 1D array of object dtype and that would 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)