Numpy随机选择在二维列表中无效

7

我运行了以下Python代码:

import numpy as np
a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
np.random.choice(a_list, size=20, 
    replace=True)

期望得到这样的结果:
[[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2], [1, 2, 3], [1, 2, 3], [10, 1, 2], [1, 2, 3], [7, 8, 9], [1, 2, 3], [1, 2, 3], [10, 1, 2], [4, 5, 6], [4, 5, 6], [10, 1, 2], [10, 1, 2], [7, 8, 9], [1, 2, 3], [7, 8, 9]]

但是我得到的却是下面的错误信息:
 ValueError                           Traceback (most recent call last)
 <ipython-input-80-c11957aca587> in <module>()
    2 a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
    3 np.random.choice(a_list, size=20, 
----> 4 replace=True)

mtrand.pyx in mtrand.RandomState.choice()

ValueError: a must be 1-dimensional

你如何从一个二维列表中随机选择元素?


请修复您问题中的格式,并包含错误信息。您说“下面是错误消息”,但实际上没有错误消息。 - FlyingTeller
1
你没有包含错误。 - roganjosh
哦,抱歉!现在请检查,我已经包含了它。 - Daniel James
5个回答

7

您需要使用索引:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]])
indices = np.arange(arr.shape[0])

output = arr[np.random.choice(indices, 20)]

或者,更简短一些(基于hpaulj的评论):
output = arr[np.random.choice(arr.shape[0],20)]

生成索引的更短方式。 - hpaulj
@hpaulj 哦,误解了建议。已经编辑好了,谢谢。 - roganjosh

4
Numpy不知道您是想从矩阵中提取随机行还是随机单元格。这就是为什么它只适用于1-D数据的原因。
您可以使用random.choice代替:
>>> import random
>>> a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
>>> [random.choice(a_list) for _ in range(20)]
[[4, 5, 6], [7, 8, 9], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6], [1, 2, 3], [10, 1, 2], [10, 1, 2], [4, 5, 6], [1, 2, 3], [1, 2, 3], [1, 2, 3], [10, 1, 2], [4, 5, 6], [1, 2, 3], [4, 5, 6], [4, 5, 6]]

使用Python 3.6或更新版本,您可以直接使用random.choices
>>> random.choices(a_list, k=20)
[[10, 1, 2], [7, 8, 9], [4, 5, 6], [10, 1, 2], [1, 2, 3], [1, 2, 3], [10, 1, 2], [10, 1, 2], [1, 2, 3], [7, 8, 9], [10, 1, 2], [10, 1, 2], [7, 8, 9], [4, 5, 6], [7, 8, 9], [4, 5, 6], [1, 2, 3], [4, 5, 6], [7, 8, 9], [7, 8, 9]]

如果你真的想使用numpy数组,你需要将你的嵌套列表转换为一个对象的1-D数组

2

或者可以使用 map

print(list(map(lambda x: random.choice(a_list),range(20))))

演示:

import random
a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]]
print(list(map(lambda x: random.choice(a_list),range(20))))

输出:

[[7, 8, 9], [10, 1, 2], [4, 5, 6], [10, 1, 2], [4, 5, 6], [10, 1, 2], [7, 8, 9], [4, 5, 6], [7, 8, 9], [1, 2, 3], [7, 8, 9], [1, 2, 3], [1, 2, 3], [10, 1, 2], [10, 1, 2], [10, 1, 2], [4, 5, 6], [10, 1, 2], [1, 2, 3], [7, 8, 9]]

1

有放回抽样

使用random.choices

x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]])
samples = random.choices(x, k=20)

不重复抽样

使用 random.sample

x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 1, 2]])
samples = random.sample(x.tolist(), k=2)

1
或者,使用随机数生成索引;然后从数组中切片。适用于任何维度。
n_sample = 10 #sample count
a_list [np.random.randint(0,a_list.shape[0], n_sample )]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接