简体   繁体   English

Numpy随机选择元组

[英]Numpy random choice of tuples

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 我得到错误: 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. 一个numpy数组,由从选择元组中随机选取的4个元素组成。

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

Use choice to choose the 1dim indices into the array, then index it. 使用choice在数组中选择1dim 索引 ,然后对其进行索引。

In the example you provided, only the number of possible choices affects the nature of the choice, not the actual values (0, 255). 在您提供的示例中,只有可能选择的数量会影响选择的性质,而不会影响实际值(0,255)。 Choosing indices is the 1dim problem choice knows how to handle. 选择索引是1dim问题choice知道如何处理。

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

Just adding this answer to provide a non-numpy based answer: 只需添加此答案即可提供基于non-numpy的答案:

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

from random import choice

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM