如何用不对称误差条拟合曲线?
How to fit curve with asymmetric error bars?
我得到了一些数据作为一系列计算机模拟的结果,可能的结果为 1 和 0。它们有不对称的误差线。
I.E:
xdata = [...]
pdata = [...]
pdatamax = [...]
pdatamin = [...]
我想为我的数据拟合一条 S 形曲线,并尝试使用 scipy.optimize.curve_fit1
函数来实现:
def sigmoid(x,x0,k):
y = 1./(1+np.exp(-k*(x-x0)))
return y
popt, pcov = curve_fit(sigmoid, xdata, ydata)
curve_fit
显然只期望标准推导 sigma 作为参数。考虑到不对称误差条,我如何拟合曲线?
最简单的方法是使用 lmfit。
https://lmfit.github.io/lmfit-py/
它具有使用 scipy 例程和指定 "parameters" 对象的 运行 最小平方拟合功能,允许您指定 vary/not-vary、min/max 和复杂的关系:
%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
curve_fit()
接受从 SciPy 0.17.0.
开始的 bounds
参数
我得到了一些数据作为一系列计算机模拟的结果,可能的结果为 1 和 0。它们有不对称的误差线。
I.E:
xdata = [...]
pdata = [...]
pdatamax = [...]
pdatamin = [...]
我想为我的数据拟合一条 S 形曲线,并尝试使用 scipy.optimize.curve_fit1
函数来实现:
def sigmoid(x,x0,k):
y = 1./(1+np.exp(-k*(x-x0)))
return y
popt, pcov = curve_fit(sigmoid, xdata, ydata)
curve_fit
显然只期望标准推导 sigma 作为参数。考虑到不对称误差条,我如何拟合曲线?
最简单的方法是使用 lmfit。 https://lmfit.github.io/lmfit-py/
它具有使用 scipy 例程和指定 "parameters" 对象的 运行 最小平方拟合功能,允许您指定 vary/not-vary、min/max 和复杂的关系:
%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
curve_fit()
接受从 SciPy 0.17.0.
bounds
参数