【问题标题】:Exponential fit on a histogram直方图上的指数拟合
【发布时间】:2020-09-23 16:48:37
【问题描述】:

我试图在从变量 y1_pt 创建的直方图上拟合指数曲线,然后获取指数的参数。问题是它给了我以下警告:

OptimizeWarning:无法估计参数的协方差 和 pcov_exponential =

array([[inf, inf, inf],
       [inf, inf, inf],
       [inf, inf, inf]]))

结果更像是一个指数拟合,在我看来有点随机..(见情节) 有人知道出了什么问题吗?


import pandas as pd
import numpy
from pylab import *
import scipy.stats as ss
from scipy.optimize import curve_fit


df=pd.read_hdf('data.h5','dataset')

pty1 = df1['y1_pt']

bins1 = numpy.linspace(35, 1235, 100)
counts, bins = numpy.histogram(pty1, bins = bins1, range = [35, 1235], density = False)
binscenters = numpy.array([0.5 * (bins1[i] + bins1[i+1]) for i in range(len(bins1)-1)])
def exponential(x, a, k, b):
    return a*np.exp(-x*k) + b


popt_exponential, pcov_exponential = curve_fit(exponential,  xdata=binscenters, ydata=counts)
print(popt_exponential)

xspace = numpy.linspace(0, 6, 100000)
plt.bar(binscenters, counts, color='navy', label=r'Histogram entries')
plt.plot(xspace, exponential(xspace, *popt_exponential), color='darkorange', linewidth=2.5, label=r'Fitted function')
plt.show()

【问题讨论】:

  • 如果您为curve_fit 提供良好的初始参数 (p0=) 和边界 (bounds=) 可能会有所帮助?参见例如docs 中的最后一个示例
  • 用最小二乘误差拟合指数函数似乎不是一个好计划。我认为也许您应该通过取对数将这些值转换为线性事物,然后拟合曲线,然后对结果求幂。

标签: python numpy dataframe histogram curve-fitting


【解决方案1】:

我认为您在指数公式中缺少一个减号,因此溢出。应该是a * np.exp( - x * k) + b

查看https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html的示例

【讨论】:

  • 好地方,谢谢。这确实解决了溢出问题,但现在我留下了 OptimizeWarning: Covariance of the parameters could not beested and the above plot with pcov_exponential 是无限的。所以,我的问题又来了。
  • 可能是您的直方图看起来更像泊松而不是指数,其中峰值不最接近 0 并且密度不是单调的。你可以拟合泊松或做 KDE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-22
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
相关资源
最近更新 更多