【问题标题】:Getting a pdf from scipy.stats in a generic way以通用方式从 scipy.stats 获取 pdf
【发布时间】:2015-09-04 16:45:57
【问题描述】:

我正在 Python 2.7.10 中使用 scipy.stats 运行一些拟合优度测试。

for distrName in distrNameList:
    distr = getattr(distributions, distrName)
    param = distr.fit(sample)
    pdf   = distr.pdf(???)

我应该将什么传递给distr.pdf() 以获得在list 的兴趣样本点(称为abscissas)上的最佳拟合pdf 的值?

【问题讨论】:

标签: python scipy distribution


【解决方案1】:

要评估abscissas 的pdf,您可以将abcissas 作为第一个参数传递给pdf。要指定参数,use the * operator 解压缩 param 元组并将这些值传递给 distr.pdf

pdf = distr.pdf(abscissas, *param)

例如,

import numpy as np
import scipy.stats as stats

distrNameList = ['beta', 'expon', 'gamma']
sample = stats.norm(0, 1).rvs(1000)
abscissas = np.linspace(0,1, 10)
for distrName in distrNameList:
    distr = getattr(stats.distributions, distrName)
    param = distr.fit(sample)
    pdf = distr.pdf(abscissas, *param)
    print(pdf)

【讨论】:

    【解决方案2】:

    从文档中,.fit() method 返回:

    shape, loc, scale : 浮动元组 任何形状统计的 MLE,然后是位置和比例的 MLE。

    .pdf() method 接受:

    x : array_like 分位数

    arg1, arg2, arg3,... : array_like 分布的形状参数(有关详细信息,请参阅实例对象的文档字符串)

    loc:array_like,可选 位置参数(默认=0)

    规模:array_like,可选

    所以基本上你会做这样的事情:

    import numpy as np
    from scipy import stats
    from matplotlib import pyplot as plt
    
    
    # some random variates drawn from a beta distribution
    rvs = stats.beta.rvs(2, 5, loc=0, scale=1, size=1000)
    
    # estimate distribution parameters, in this case (a, b, loc, scale)
    params = stats.beta.fit(rvs)
    
    # evaluate PDF
    x = np.linspace(0, 1, 1000)
    pdf = stats.beta.pdf(x, *params)
    
    # plot
    fig, ax = plt.subplots(1, 1)
    ax.hold(True)
    ax.hist(rvs, normed=True)
    ax.plot(x, pdf, '--r')
    

    【讨论】:

    • 非常好,对图表和详细说明 +1,但本质上这并没有增加 unutbu 的答案——还是我弄错了?
    • 不,不是真的 - 在 unutbu 发布他的答案之前,我没有时间完成输入答案
    • 我做了+1,但很遗憾,不能接受...非常感谢您
    猜你喜欢
    • 2020-04-26
    • 1970-01-01
    • 2013-01-22
    • 2013-07-29
    • 1970-01-01
    • 2011-03-26
    • 2018-08-25
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多