Python:从经验分布生成随机值

8

我认为这里的被接受答案有你要找的内容。 - Kevin
3
@Kevin: 链接的答案对于这种情况不起作用,因为它假定您已经知道分布的解析形式,而这个问题正在寻找非参数化的东西。 - abeboparebop
1个回答

7
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt

# This represents the original "empirical" sample -- I fake it by
# sampling from a normal distribution
orig_sample_data = np.random.normal(size=10000)

# Generate a KDE from the empirical sample
sample_pdf = scipy.stats.gaussian_kde(orig_sample_data)

# Sample new datapoints from the KDE
new_sample_data = sample_pdf.resample(10000).T[:,0]

# Histogram of initial empirical sample
cnts, bins, p = plt.hist(orig_sample_data, label='original sample', bins=100,
                         histtype='step', linewidth=1.5, density=True)

# Histogram of datapoints sampled from KDE
plt.hist(new_sample_data, label='sample from KDE', bins=bins,
         histtype='step', linewidth=1.5, density=True)

# Visualize the kde itself
y_kde = sample_pdf(bins)
plt.plot(bins, y_kde, label='KDE')
plt.legend()
plt.show(block=False)

结果图

new_sample_data 应该从与原始数据大致相同的分布中绘制出来(在KDE是原始分布的良好近似程度上)。


2
这不是绘制代表原始分布的随机样本的正确方法。一个适当的方法应该是某种CDF变换。 - Zanam
1
@Zanam:你对这种方法会有什么问题?我不是统计学专家,所以我真的很好奇。 - abeboparebop
事实上,经验分布通常不符合我们所知的任何标准分布。 - Zanam
@Zanam:我所做的唯一假设是原始数据分布可以通过高斯平滑的KDE合理拟合--我并不假设它遵循任何特定的标准分布。 - abeboparebop
1
@Zanam,您能否详细说明您想表达的观点? - Vlad

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