繁体   English   中英

使用scipy curve_fit进行正确拟合,包括x中的误差?

[英]Correct fitting with scipy curve_fit including errors in x?

我正在尝试使用scipy.optimize.curve_fit在其中scipy.optimize.curve_fit包含一些数据的直方图。 如果我想在y添加一个错误,我可以通过对拟合应用weight来实现。 但是如何在x应用误差(即直方图中由于分档引起的误差)?

我的问题也适用于使用curve_fitpolyfit进行线性回归时x误差; 我知道如何在y添加错误,而不是在x添加错误。

这里有一个例子(部分来自matplotlib文档 ):

import numpy as np
import pylab as P
from scipy.optimize import curve_fit

# create the data histogram
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)

# define fit function
def gauss(x, *p):
    A, mu, sigma = p
    return A*np.exp(-(x-mu)**2/(2*sigma**2))

# the histogram of the data
n, bins, patches = P.hist(x, 50, histtype='step')
sigma_n = np.sqrt(n)  # Adding Poisson errors in y
bin_centres = (bins[:-1] + bins[1:])/2
sigma_x = (bins[1] - bins[0])/np.sqrt(12)  # Binning error in x
P.setp(patches, 'facecolor', 'g', 'alpha', 0.75)

# fitting and plotting
p0 = [700, 200, 25]
popt, pcov = curve_fit(gauss, bin_centres, n, p0=p0, sigma=sigma_n, absolute_sigma=True)
x = np.arange(100, 300, 0.5)
fit = gauss(x, *popt)
P.plot(x, fit, 'r--')

现在,这个适合(当它没有失败时)确实考虑了y-errors sigma_n ,但我还没有找到一种方法来让它考虑sigma_x 我在scipy邮件列表上扫描了几个线程,发现了如何使用absolute_sigma值和Stackoverflow上有关非对称错误的帖子,但没有关于两个方向的错误。 有可能实现吗?

scipy.optmize.curve_fit使用标准的非线性最小二乘优化,因此只会最小化响应变量的偏差。 如果您想要考虑自变量中的错误,可以尝试使用正交距离回归的scipy.odr 顾名思义,它最大限度地减少了独立变量和因变量。

看看下面的示例。 fit_type参数确定scipy.odr是执行完整ODR( fit_type=0 )还是执行最小二乘优化( fit_type=2 )。

编辑

虽然这个例子起作用但没有多大意义,因为y数据是在噪声x数据上计算的,这只会导致不等间距的独立变量。 我更新了样本,现在还展示了如何使用RealData ,它允许指定数据的标准错误而不是权重。

from scipy.odr import ODR, Model, Data, RealData
import numpy as np
from pylab import *

def func(beta, x):
    y = beta[0]+beta[1]*x+beta[2]*x**3
    return y

#generate data
x = np.linspace(-3,2,100)
y = func([-2.3,7.0,-4.0], x)

# add some noise
x += np.random.normal(scale=0.3, size=100)
y += np.random.normal(scale=0.1, size=100)

data = RealData(x, y, 0.3, 0.1)
model = Model(func)

odr = ODR(data, model, [1,0,0])
odr.set_job(fit_type=2)
output = odr.run()

xn = np.linspace(-3,2,50)
yn = func(output.beta, xn)
hold(True)
plot(x,y,'ro')
plot(xn,yn,'k-',label='leastsq')
odr.set_job(fit_type=0)
output = odr.run()
yn = func(output.beta, xn)
plot(xn,yn,'g-',label='odr')
legend(loc=0)

适合嘈杂的数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM