learning-notes icon indicating copy to clipboard operation
learning-notes copied to clipboard

怎么样从 NumPy 数组中随机抽取 i 个元素?

Open daa233 opened this issue 7 years ago • 2 comments

例如,有一个二维数组 X 和一个列向量 y,它们的值如下:

>>> print(X)
[[0 1]
 [2 3]
 [4 5]]
>>> print(y)
[[0]
 [1]
 [2]]

Xy 的行都是对应的,每一行表示一条样本数据。现在希望从中随机抽取两条数据,抽取出来的数据和原来的对应关系一致。

daa233 avatar Oct 31 '17 14:10 daa233

方法一:先组合,再随机排列,最后再拆开

>>> combination = np.hstack((X, y))
>>> print(combination)
[[0 1 0]
 [2 3 1]
 [4 5 2]]
>>> permutation = np.random.permutation(c)[:2] # 随机排列,并返回排列后的前两条数据
>>> print(permutation)
[[4 5 2]
 [2 3 1]]
>>> X_random, y_random = np.hsplit(permutation, np.array([X.shape[1]])) # 拆开
>>> print(X_random)
[[4 5]
 [2 3]]
>>> print(y_random)
[[2]
 [1]]

daa233 avatar Nov 01 '17 01:11 daa233

方法二:先得到随机的 i 个索引,再索引到相关数据

>>> random_indices = np.random.permutation(np.arange(X.shape[0]))[:2]
>>> print(random_indices)
[2 1]
>>> X_random = X[random_indices]
>>> y_random = y[random_indices]
>>> print(X_random)
[[4 5]
 [2 3]]
>>> print(y_random)
[[2]
 [1]]

daa233 avatar Nov 01 '17 01:11 daa233