首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python:从经验分布生成随机值

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

Stack Overflow用户
提问于 2016-02-16 13:49:27
回答 1查看 5K关注 0票数 8

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

  • 从观测数据中导出概率分布。
  • 从此分布生成随机值。

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

EN

回答 1

Stack Overflow用户

发布于 2018-08-07 12:53:13

代码语言:javascript
运行
复制
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是对原始分布的良好近似)。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35434363

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档