【发布时间】:2021-11-19 15:26:47
【问题描述】:
我有一个长度为 l 的一维 NumPy 数组 a,我想从中采样 int(np.log(l)) 实例,但我希望样本是:
-
准均匀分布,并且
-
随机的。
-
1我的意思是我想避免两个样本的距离小于int(l/int(np.log(l)))。 -
2我的意思是我不想每次都获得与样本相同的实例。 - 我还需要强调,我无法更改随机种子。
一种方法是将数组拆分为int(np.log(l)) 子数组,然后从每个子数组中随机抽取一个,但我正在寻找一种更有效的实现方式,因为我需要在相当数量的数据。
import numpy as np
a = np.array([np.random.randint(1000) for _ in range(1000)])
a = np.sort(a)
l = len(a)
random_indices = np.random.randint(0, l, int(np.log(l)))
samples = a[random_indices]
samples = np.sort(samples)
samples
# array([183, 536, 644, 791, 925, 999])
感谢任何 cmets、建议和帮助。
【问题讨论】:
-
你考虑过使用
np.random.choice吗?如果你将它与 replace=False 和 size=int(np.log(l)) 一起使用,我想你会得到你想要的 -
谢谢@Luckk,但它正在做我已经做过的事情:为
int(np.log(l))提供均匀分布的样本。我想确保每个块中至少有一个样本。 -
分布不能同时均匀分布和约束。你所要求的在数学上是不可能的。
-
你是对的@obchardon 我编辑了我的问题。
标签: python numpy random sampling