首页 > 解决方案 > 对两个未知因变量使用curve_fit,这种方法正确吗?

问题描述

我是 python 新手,我在我的模型中使用 curve_fit 进行不同的计算,我的一个方程包括两个未知变量,所以我不可能手动检查我的代码是否正确。

我的方程式是

ln(S(b)/S(b50))= -b D + 1/6 b**2 D**2 K

我的未知数是 D 和 K

ln(S(b)/S(b50)) 是我的 ydata b 是我的 xdata

所以我使用了以下内容:

xdata = np.array([50,300,600,1000])
ydata_beforelog = np.array([426.0938, 259.2896, 166.8042, 80.9248])
ydata = np.log(ydata_before/426.0938)

def func(x, D, K):
    return (-x * D) + (1/6 * (x **2)* (D **2) * K)

popt, pcov = curve_fit(func, xdata, ydata)
popt[0] = popt[0] * 1000 # I need that for unit scaling

popt = ([ 1.48687053, -0.46540487])
'''

I would assume that those are my D and K?

标签: pythoncurve-fitting

解决方案


请允许我建议使用lmfithttps://lmfit.github.io/lmfit-py) - 免责声明:我是主要作者。这会改变你的身材,看起来像这样:

import numpy as np
from lmfit import Model

xdata = np.array([50,300,600,1000])
ydata_before = np.array([426.0938, 259.2896, 166.8042, 80.9248])
ydata = np.log(ydata_before/426.0938)

def func(x, D, K):
    return (-x * D) + (1/6 * (x **2)* (D **2) * K)

# create model from this function
mymodel = Model(func)

# create a dictionary of named parameters using the argument names of 
# your model function, so 'D' and 'K'.  Give initial values:
params = mymodel.make_params(D=1.5, K=-1)

# do the fit: fitting ydata with the parameters and
# independent variable "x" as defined by your model function:
result = mymodel.fit(ydata, params, x=xdata)

# print the results and fit statistics or just get the best-fit parameters:
print(result.fit_report())

for key, param in result.params.items():
    print(param)

也就是说,您通过 name引用参数。此填充将打印出来:

[[Model]]
    Model(func)
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 12
    # data points      = 4
    # variables        = 2
    chi-square         = 0.00709560
    reduced chi-square = 0.00354780
    Akaike info crit   = -21.3382982
    Bayesian info crit = -22.5657095
[[Variables]]
    D:  0.00148687 +/- 1.9408e-04 (13.05%) (init = 1.5)
    K: -0.46540487 +/- 0.71331763 (153.27%) (init = -1)
[[Correlations]] (unreported correlations are < 0.100)
    C(D, K) =  0.977
<Parameter 'D', value=0.0014868705336113577 +/- 0.000194, bounds=[-inf:inf]>
<Parameter 'K', value=-0.4654048673207782 +/- 0.713, bounds=[-inf:inf]>

推荐阅读