我正在嘗試將 curve_fit 用于以下形式的定義函式:
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 項,而只需撰寫一個通用形式即可提供所需的輸出。
謝謝你。
uj5u.com熱心網友回復:
使用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( )
uj5u.com熱心網友回復:
我設法通過以下方式解決它,也許不是聰明的方法,但它對我有用。
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)
它對我來說很好用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317012.html
