从numpy数组中随机选择 [英] Randomly select from numpy array

查看:1189
本文介绍了从numpy数组中随机选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相关的numpy数组,Xy.我需要从X中选择n个随机行,并将其存储在数组中,并存储相应的y值,并在其后追加随机选择的点的索引.

I have two related numpy arrays, X and y. I need to select n random rows from X and store this in an array, the corresponding y value and the appends to it the index of the points randomly selected.

我还有另一个数组index,它存储了我不想采样的索引列表.

I have another array index which stores a list of index which I dont want to sample.

我该怎么做?

样本数据:

index = [2,3]
X = np.array([[0.3,0.7],[0.5,0.5] ,[0.2,0.8], [0.1,0.9]])
y = np.array([[0], [1], [0], [1]])

如果随机选择了这些X(其中n=2):

If these X's were randomly selected (where n=2):

randomylSelected = np.array([[0.3,0.7],[0.5,0.5]])

所需的输出将是:

index = [0,1,2,3]
randomlySelectedY = [0,1]

我该怎么做?

推荐答案

您可以使用

You can create random indices with np.random.choice:

n = 2  # for 2 random indices
index = np.random.choice(X.shape[0], n, replace=False)  

然后,您只需要使用结果对数组进行索引:

Then you just need to index your arrays with the result:

x_random = X[index]
y_random = Y[index]

这篇关于从numpy数组中随机选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆