分别计算求和参数



我正试图使用curve_fitting为以下形式的定义函数:

Z = (Rth(1 - np.exp(- x/tau))

我想计算参数Rth和tau的前四个值。目前,如果我像这样使用整个函数,它工作得很好:

Z = (a * (1- np.exp (- x / b))) + (c * (1- np.exp (- x / d)))+ (e * (1- np.exp (- x / f)))  + (g * (1- np.exp (- x / f)))

但这肯定不是一个好的方法,例如,如果我有一个很长的函数,有超过4个指数项,我想得到所有的参数。我如何调整它,使它在曲线拟合后返回特定数量的Rth和tau值?

例如,如果我想从一个8项指数函数中得到16个参数,我不需要写出完整的8项,而只是一个一般形式,它给出了期望的输出。

谢谢。

使用least_squares可以很容易地得到任意函数的和。

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import least_squares
def partition( inList, n ):
return zip( *[ iter( inList ) ] * n )
def f( x, a, b ):
return a * ( 1 - np.exp( -b * x ) )
def multi_f( x, params ):
if len( params) % 2:
raise TypeError
subparams = partition( params, 2 )
out = np.zeros( len(x) )
for p in subparams:
out += f( x, *p )
return out
def residuals( params, xdata, ydata ):
return multi_f( xdata, params ) - ydata

xl = np.linspace( 0, 8, 150 )
yl = multi_f( xl, ( .21, 5, 0.5, 0.1,2.7, .01 ) )
res = least_squares( residuals, x0=( 1,.9, 1, 1, 1, 1.1 ), args=( xl, yl ) )
print( res.x )
yth = multi_f( xl, res.x )
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.plot( xl, yl )
ax.plot( xl, yth )
plt.show( )

我设法用下面的方法解决了它,也许不是聪明的方法,但它对我有用。

def func(x,*args):
Z=0
for i in range(0,round(len(args)/2)):
Z += (args[i*2] * (1- np.exp (- x / args[2*i+1])))
return Z

然后在一个单独的函数中调用参数,我可以调整参数的数量。

def func2(x,a,b,c,d,e,f,g,h):
return func(x,a,b,c,d,e,f,g,h)
popt , pcov = curve_fit(func2,x,y, method = 'trf', maxfev = 100000)

,它对我来说很好。

最新更新