从NumPy数组中选择“一些”随机点

7
我有两个相关的numpy数组,Xy。我需要从X中选择n个随机行,并将其存储在一个数组中,对应的y值并附加随机选择点的索引。
我还有另一个数组index,它存储了一个我不想抽样的索引列表。
如何实现这个功能呢?
示例数据:
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):
randomylSelected = np.array([[0.3,0.7],[0.5,0.5]])

期望的输出如下所示:
index = [0,1,2,3]
randomlySelectedY = [0,1]

我该如何做到这一点?

2个回答

0
我会管理一个布尔值数组,然后持续使用它来切片一个索引数组,并从结果中随机选择。
n = X.shape[0]
sampled = np.empty(n, dtype=np.bool)
sampled.fill(False)
rng = np.arange(n)

k = 2

while not sampled.all():
    sample = np.random.choice(rng[~sampled], size=k, replace=False)
    print(X[sample])
    print()
    print(y[sample])
    print()
    sampled[sample] = True

[[ 0.2  0.8]
 [ 0.5  0.5]]

[[0]
 [1]]

[[ 0.3  0.7]
 [ 0.1  0.9]]

[[0]
 [1]]

@scutnex 取决于您所说的“记录”是指什么。我正在使用“真值”更新“sampled”数组……也就是在记录它。这是一种实现此操作的算法。根据个人喜好,有很多可以调整的地方。 - piRSquared

0
如果您想随机选择n行,并且每一行被选中的概率相等:
n = 2 #for sake of argument
randomlySelectedY = np.argsort(np.random.random(4))[:n] #generate a 1x4 array of random, uniformly distributed numbers and then select the indices of the lowest n numbers

randomylSelected = X[randomlySelectedY]
index = np.linspace(1,np.size(X[:,1]),np.size(X[:,1]))

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