Numpy:从2D数组中获取随机行集

2024-04-26 06:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很大的二维数组,看起来像这样:

a=
[[a1, b1, c1],
 [a2, b2, c2],
 ...,
 [an, bn, cn]]

使用numpy,有没有一种简单的方法可以获得一个新的2D数组,例如,从初始数组a(不需要替换)获得两个随机行?

例如

b=
[[a4,  b4,  c4],
 [a99, b99, c99]]

Tags: 方法numpyana2a1数组cnb2
3条回答
>>> A = np.random.randint(5, size=(10,3))
>>> A
array([[1, 3, 0],
       [3, 2, 0],
       [0, 2, 1],
       [1, 1, 4],
       [3, 2, 2],
       [0, 1, 0],
       [1, 3, 1],
       [0, 4, 1],
       [2, 4, 2],
       [3, 3, 1]])
>>> idx = np.random.randint(10, size=2)
>>> idx
array([7, 6])
>>> A[idx,:]
array([[0, 4, 1],
       [1, 3, 1]])

总而言之:

A[np.random.randint(A.shape[0], size=2), :]

对于非替换(numpy 1.7.0+):

A[np.random.choice(A.shape[0], 2, replace=False), :]

我认为在1.7之前没有一个好的方法来生成不需要替换的随机列表。也许您可以设置一个小定义,以确保这两个值不相同。

另一个选择是创建一个随机掩码,如果您只想按某个因素对数据进行下采样。假设我想将样本减少到原始数据集的25%,该数据集当前保存在数组data_arr

# generate random boolean mask the length of data
# use p 0.75 for False and 0.25 for True
mask = numpy.random.choice([False, True], len(data_arr), p=[0.75, 0.25])

现在您可以调用data_arr[mask]并返回约25%的行,随机采样。

这是一篇老文章,但这是最适合我的:

A[np.random.choice(A.shape[0], num_rows_2_sample, replace=False)]

将replace=False更改为True以获得相同的结果,但使用replace。

相关问题 更多 >

    热门问题