最简单的方法是使用 lmfit。
https://lmfit.github.io/lmfit-py/
它具有使用带有指定“参数”对象的 scipy 例程运行最小平方拟合的功能,该对象允许您指定可变/不可变、最小/最大和复杂关系:
%pylab inline
import lmfit
def sigmoid(x,x0,k):
y = 1./(1+np.exp(-k*(x-x0)))
return y
x = linspace(0,10,100)
x0 = 1
k = 1
y = sigmoid(x, x0, k)
noise = (np.random.rand(100) - 0.5) / 20
y_data = y + noise
def residuals(params, x, y_data):
x0 = params['x0'].value
k = params['k'].value
y_calc = sigmoid(x, x0, k)
return y_data - y_calc
parameters = lmfit.Parameters()
parameters.add("x0", value=1, vary=True, min=0.1, max=2.0)
parameters.add("k", value=1, vary=True, min=0.1, max=2.0)
result = lmfit.minimize(residuals, parameters, args=(x, y_data))
lmfit.report_fit(result.params)
plot(x, y_data)
plot(x, sigmoid(x, result.params['x0'].value, result.params['k'].value))
输出:
Populating the interactive namespace from numpy and matplotlib
[[Variables]]
x0: 1.01570966 +/- 0.012437 (1.22%) (init= 1)
k: 0.99250215 +/- 0.012903 (1.30%) (init= 1)
[[Correlations]] (unreported correlations are < 0.100)
C(x0, k) = 0.355