【发布时间】:2020-12-23 13:29:52
【问题描述】:
我有一个 Pandas DataFrame,其中包含一个数据集 D 的实例,这些实例都有一些连续值 x。 x 以某种方式分布,比如说统一,可以是任何东西。
我想从D 中抽取n 样本,其中x 具有我可以采样或近似的目标分布。这来自一个数据集,这里我只是取正态分布。
如何从D 中抽样实例,以使抽样中x 的分布等于/类似于我指定的任意分布?
现在,我对一个值x、子集D 进行采样,使其包含所有x +- eps 并从中采样。但是当数据集变大时,这会很慢。人们一定想出了更好的解决方案。也许解决方案已经很好,但可以更有效地实施?
我可以将x 拆分为分层,这样会更快,但是没有这个有没有解决方案?
我当前的代码,运行良好但速度很慢(30k/100k 需要 1 分钟,但我有 200k/700k 左右。)
import numpy as np
import pandas as pd
import numpy.random as rnd
from matplotlib import pyplot as plt
from tqdm import tqdm
n_target = 30000
n_dataset = 100000
x_target_distribution = rnd.normal(size=n_target)
# In reality this would be x_target_distribution = my_dataset["x"].sample(n_target, replace=True)
df = pd.DataFrame({
'instances': np.arange(n_dataset),
'x': rnd.uniform(-5, 5, size=n_dataset)
})
plt.hist(df["x"], histtype="step", density=True)
plt.hist(x_target_distribution, histtype="step", density=True)
def sample_instance_with_x(x, eps=0.2):
try:
return df.loc[abs(df["x"] - x) < eps].sample(1)
except ValueError: # fallback if no instance possible
return df.sample(1)
df_sampled_ = [sample_instance_with_x(x) for x in tqdm(x_target_distribution)]
df_sampled = pd.concat(df_sampled_)
plt.hist(df_sampled["x"], histtype="step", density=True)
plt.hist(x_target_distribution, histtype="step", density=True)
【问题讨论】: