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

查看:32
本文介绍了从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]

我该怎么做?

推荐答案

您可以使用 np.random.choice:

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天全站免登陆