python 积分函数拟合曲线

python fitting curve with integral function

我想用积分函数(截断伽玛分布)拟合数据。 我尝试了以下代码,但出现了错误。如果您愿意帮助我,我将不胜感激。非常感谢您。

%matplotlib inline
import numpy as np
from scipy import integrate
import scipy.optimize
import matplotlib.pyplot as plt

xlist=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14]
ylist=[1.0, 0.7028985507246377, 0.4782608695652174, 0.36231884057971014,
   0.2536231884057971, 0.1811594202898551, 0.12318840579710147,
   0.08695652173913046, 0.057971014492753645, 0.04347826086956524,
   0.02173913043478263, 0.007246376811594223]

xdata=np.array(xlist)
ydata=np.array(ylist)

parameter_initial=np.array([0.0,0.0,0.0])#a,b,c

def func(x,a,b,c):
    return integrate.quad(lambda t:t^(a-1)*np.exp(-t),x/c,b/c)/integrate.quad(lambda t:t^(a-1)*np.exp(-t),0.0,b/c)

parameter_optimal,cov=scipy.optimize.curve_fit(func,xdata,ydata,p0=parameter_initial) 
print "paramater =", paramater_optimal
y = func(xdata,paramater_optimal[0],paramater_optimal[1],paramater_optimal[2])
plt.plot(xdata, ydata, 'o')
plt.plot(xdata, y, '-')
plt.show()

出现以下错误。

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

您的代码存在以下错误:

  • 初始值不合适,因为是零,并且在函数之间划分的参数导致问题,因为 0 之间的划分是未定义的。

  • quad() 函数接收数字数据作为第二个和第三个参数,不是列表,也不是某些可迭代的 np.ndarray(),但在您的情况下是参数 x在你的函数 fun() 中是一个 np.ndarray(),你所做的是迭代 x 并将该参数传递给 quad().

  • quad() returns 2个参数,第一个是积分的值,第二个是误差,所以只用第一个参数。

  • 您必须使用 ** 而不是 ^

综合以上,我提出如下代码:

import numpy as np
from scipy import integrate
import scipy.optimize
import matplotlib.pyplot as plt

xlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14]
ylist = [1.0, 0.7028985507246377, 0.4782608695652174, 0.36231884057971014,
   0.2536231884057971, 0.1811594202898551, 0.12318840579710147,
   0.08695652173913046, 0.057971014492753645, 0.04347826086956524,
   0.02173913043478263, 0.007246376811594223]

xdata = np.array(xlist)
ydata = np.array(ylist)

parameter_initial = np.array([2.5,2.5,2.5]) # a, b, c


def func(x,a,b,c):
    fn = lambda t : t**(a-1)*np.exp(-t)
    den = integrate.quad(fn, 0.0, b/c)[0]
    num = np.asarray([integrate.quad(fn, _x/c, b/c)[0] for _x in x])
    return num/den

parameter_optimal, cov = scipy.optimize.curve_fit(func, xdata, ydata,p0=parameter_initial) 
print("paramater =", parameter_optimal)
y = func(xdata, *parameter_optimal)
plt.plot(xdata, ydata, 'o')
plt.plot(xdata, y, '-')
plt.show()