[英]Least mean square method for multiple functions at once in python
您可以將函數的相對重要性放在超參數lambda
中,然后使用func1 + lambda * func2
。
使用代碼:
importance_of_func1_relative_to_func2 = 1
def objective(args1, args2):
return func1(args1) * importance_of_func1_relative_to_func2 + func2(args2)
如果不使用像lmfit
或類似的包,具有共享參數的擬合曲線將總是需要編寫某種包裝器。 我個人會寫一個殘差 function 並使用scipy.optimize.least_squares
,但如果堅持使用curve_fit
,這將是一個可能的包裝器:
import numpy as np
from scipy.optimize import curve_fit
def f1( x, c, L, R):
a = c**2 * x / ( R**2 + (x * L )**2 )
return a * x * L
def f2( x, c, L, R):
a = c**2 * x / ( R**2 + (x * L )**2 )
return a * R
def falt( x, c, L, R, n=-1):
"""
by construction x is the doubled x-list, 0 <= nn / l < 1
and >= 1/2 is the second part
"""
if isinstance( x, ( list, tuple, np.ndarray ) ):
### curve_fit sends array
l = len( x )
out = [ falt( xx, c, L, R, n=( nn / l ) ) for nn, xx in enumerate( x ) ]
else:
if n < 0.5:
out = f1( x, c, L, R)
else:
out = f2( x, c, L, R)
return out
## some data
c0=1.2
L0=0.3
R0= 0.45
size = 99
xl = np.linspace( 0, 10, size )
y1l = f1( xl , c0, L0, R0 ) + ( 2 * np.random.random( size=size ) - 1 ) * 0.1
y2l = f2( xl , c0, L0, R0 ) + ( 2 * np.random.random( size=size ) - 1 ) * 0.1
sol, err = curve_fit(
falt,
np.append( xl, xl ),
np.append( y1l, y2l )
)
print( sol )
如果我理解目標(不確定),我認為您可能想要做的是使用一個 function 來評估 Fperp 和 Fpara 的 2 個值,然后將它們連接起來。 你把它們寫成都乘以|z|
(也許abs(zhat)
?)——我不知道這應該是一個通用的比例因子、一個擬合變量,還是其他一些值數組……
無論如何,我可能會建議像 function
def f_model(omega, cm, rr, lr, zhat):
ll = lr * omega
scale = abs(zhat) * cm**2 / (rr**2 + ll**2)
fpara = scale * ll * omega
fperp = scale * rr * omega
return np.concatenate((fpara, fperp))
然后,您可能希望將 model 與此 function 的數據安排為對應於fpara
和fperp
的數據的串聯。
這種串聯將有效地將Fpara
和Fperp
在一起,並在擬合中平均加權它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.