给定一个现有的分布,我怎样才能抽取标准为 X 的大小为 N 的样本?

Given an existing distribution, how can I draw samples of size N with std of X?

我有一个现有的值分布,我想绘制大小为 5 的样本,但这 5 个样本需要在一定公差范围内具有 X 的标准差。例如,我需要 5 个 std 为 10 的样本(即使整体分布为 std=~32)。

下面的示例代码有些工作,但对于大型数据集来说速度很慢。它随机对分布进行采样,直到找到接近目标 std 的东西,然后删除这些元素,使它们无法再次绘制。

有没有更聪明的方法来正确和更快地做到这一点?它适用于某些 target_std(6 以上),但低于 6 则不准确。

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(23)

# Create a distribution
d1 = np.random.normal(95, 5, 200)
d2 = np.random.normal(125, 5, 200)
d3 = np.random.normal(115, 10, 200)
d4 = np.random.normal(70, 10, 100)
d5 = np.random.normal(160, 5, 200)
d6 = np.random.normal(170, 20, 100)
dist = np.concatenate((d1, d2, d3, d4, d5, d6))
print(f"Full distribution: len={len(dist)}, mean={np.mean(dist)}, std={np.std(dist)}")
plt.hist(dist, bins=100)
plt.title("Full Distribution")
plt.show();


batch_size = 5
num_batches = math.ceil(len(dist)/batch_size)
target_std = 10
tolerance = 1
# how many samples to search
num_samples = 100
result = []

# Find samples of batch_size that are closest to target_std
for i in range(num_batches):
    samples = []
    idxs = np.arange(len(dist))
    for j in range(num_samples):
        indices = np.random.choice(idxs, size=batch_size, replace=False)
        sample = dist[indices]
        std = sample.std()
        err = abs(std - target_std)
        samples.append((sample, indices, std, err, np.mean(sample), max(sample), min(sample)))
        if err <= tolerance:
            # close enough, stop sampling
            break
    # sort by smallest err first, then take the first/best result
    samples = sorted(samples, key=lambda x: x[3])
    best = samples[0] 
    if i % 100 == 0:
        pass
        print(f"{i}, std={best[2]}, err={best[3]}, nsamples={num_samples}")
    result.append(best)
    # remove the data from our source
    dist = np.delete(dist, best[1])

df_samples = pd.DataFrame(result, columns=["sample", "indices", "std", "err", "mean", "max", "min"])

df_samples["err"].plot(title="Errors (target_std - batch_std)")
batch_std = df_samples["std"].mean()
batch_err = df_samples["err"].mean()
print(f"RESULT: Target std: {target_std}, Mean batch std: {batch_std}, Mean batch err: {batch_err}")

由于您的问题不限于特定分布,因此我使用正态随机分布,但这应该适用于任何分布。但是 运行 时间将取决于人口规模。

population = np.random.randn(1000)*32
std = 10.
tol = 1.
n_samples = 5
samples = list(np.random.choice(population, n_samples))
while True:
    center = np.mean(samples)
    dis = [abs(i-center) for i in samples]
    if np.std(samples)>(std+tol):
        samples.pop(dis.index(max(dis)))
    elif np.std(samples)<(std-tol):
        samples.pop(dis.index(min(dis)))
    else:
        break
    samples.append(np.random.choice(population, 1)[0])

下面是代码的工作原理。 首先画n_samples,可能std不在你想要的范围内,所以我们计算每个样本的均值和与均值的绝对距离。然后,如果 std 大于所需值加上公差,我们踢出最远的样本并绘制一个新样本,反之亦然。

请注意,如果这对您的数据来说计算时间太长,在剔除异常值后,您可以计算应该在总体中绘制的下一个元素的范围,而不是随机取一个.希望这对你有用。

免责声明:这不再是随机抽奖,您应该知道抽奖有偏见,不能代表总体。