【问题标题】:Python: Generate random values from empirical distributionPython:从经验分布中生成随机值
【发布时间】:2016-05-27 20:07:39
【问题描述】:

在 Java 中,我通常依靠 org.apache.commons.math3.random.EmpiricalDistribution 类来执行以下操作:

  • 根据观察数据得出概率分布。
  • 从此分布生成随机值。

是否有任何提供相同功能的 Python 库? scipy.stats.gaussian_kde.resample 似乎做了类似的事情,但我不确定它是否实现了与我熟悉的 Java 类型相同的过程。

【问题讨论】:

  • 我认为接受的答案here 有你想要的。
  • @Kevin:链接的答案不适用于这种情况,因为它假设您已经知道分布的分析形式,而这个问题正在寻找非参数的东西。

标签: python statistics


【解决方案1】:
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 是原始分布的良好近似值)。

【讨论】:

  • 这不是绘制代表原始分布的随机样本的正确方法。适当的方法是某种 CDF 变换。
  • @Zanam:您希望这种方法会出现什么样的问题?我不是统计专家,所以我真的很好奇。
  • 事实上,经验分布通常不适合我们所知道的任何标准分布。
  • @Zanam:我所做的唯一假设是原始数据分布可以由高斯平滑 KDE 合理拟合——我不假设它遵循任何特定的标准分布。
  • @Zanam 你能详细说明你想要表达的观点吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 2020-08-26
  • 2011-05-26
  • 2013-08-28
  • 2017-05-18
相关资源
最近更新 更多