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

标签 python statistics

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

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

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

最佳答案

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)

resulting plot

new_sample_data 应该从与原始数据大致相同的分布中提取(在某种程度上 KDE 是原始分布的良好近似值)。

关于Python:从经验分布生成随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35434363/

相关文章:

java - 统计计算

python-3.x - scipy回归模型残差总和

python - 使用 sendgrid python 安排电子邮件

python - 根据 2D numpy 数组过滤 3D numpy 数组

python - 将按 pandas 数据框(多个但不是所有列)分组的数据从长转换为宽

SQL统计采样

python - 这个正则表达式在 django 中意味着什么?

python - 如何修复此 mysql 社区-> connector-python(未安装 python 3.4)

matlab - 如何在octave/matlab中从均值和st.dev向量生成多重随机分布?

独立性的Matlab测试