从numpy数组中选择'一些'随机点
问题描述:
我有两个相关的numpy数组,X
和y
。我需要从X
中选择n
随机行并将其存储在一个数组中,对应的值为y
,并附加它随机选择的点的索引。从numpy数组中选择'一些'随机点
我有另一个数组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]
我怎样才能做这个?
答
我会管理一个布尔值数组,我不断用它来切片索引数组并从结果中随机选择。
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]]
答
如果你想在随机选择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]))
@scutnex取决于你的意思是记录一下。我正在更新具有True值的采样数组...正在记录它。这是一个算法。有很多东西可以根据口味调整。 – piRSquared