Numpy random choice of tuples

回眸只為那壹抹淺笑 提交于 2020-05-12 11:04:34

问题


I'm having trouble to create an array of random choices, where a choice is a tuple.

I get the error: a must be 1-dimensional

Here is an example:

choices = ((0,0,0),(255,255,255))
numpy.random.choice(choices,4)

Is there any other way to do this?

Expected result:

a numpy array consiting of 4 elements randomly picked from the choices tuple.

((0,0,0),(0,0,0),(255,255,255),(255,255,255))

回答1:


Use choice to choose the 1dim indices into the array, then index it.

In the example you provided, only the number of possible choices affects the nature of the choice, not the actual values (0, 255). Choosing indices is the 1dim problem choice knows how to handle.

choices = numpy.array([[0,0,0],[255,255,255]])
idx = numpy.random.choice(len(choices),4)
choices[idx]



回答2:


Just adding this answer to provide a non-numpy based answer:

choices = ((0,0,0),(255,255,255))

from random import choice

print tuple(choice(choices) for _ in range(4))



回答3:


If you want to specifically sample without replacement, you can try:

import random
choices = ((0,0,0),(1,1,1),(2,2,2),(3,3,3))
random.sample(choices, 2)


来源:https://stackoverflow.com/questions/23445936/numpy-random-choice-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!