Scipy.optimize.leastsq
是一种拟合数据的便捷方式,但下面的工作是函数的最小化。Scipy.optimize
包含许多最小化函数,其中一些具有处理约束的能力。这里我解释一下fmin_slsqp
我知道的,也许其他人也可以;见Scipy.optimize 文档
fmin_slsqp
需要一个函数来最小化和参数的初始值。最小化的函数是残差的平方和。对于参数,我首先执行传统的最小平方拟合,并将结果用作约束最小化问题的初始值。然后有几种施加约束的方法(参见文档);更简单的是f_ieqcons
参数:它需要一个函数,该函数返回一个数组,其值必须始终为正(这就是约束)。如果对于所有最大值点,拟合函数低于该点,则该函数返回正值。
import numpy
import scipy.optimize as scimin
import matplotlib.pyplot as mpl
datax=numpy.array([1,2,3,4,5]) # data coordinates
datay=numpy.array([2.95,6.03,11.2,17.7,26.8])
constraintmaxx=numpy.array([0]) # list of maximum constraints
constraintmaxy=numpy.array([1.2])
# least square fit without constraints
def fitfunc(x,p): # model $f(x)=a x^2+c
a,c=p
return c+a*x**2
def residuals(p): # array of residuals
return datay-fitfunc(datax,p)
p0=[1,2] # initial parameters guess
pwithout,cov,infodict,mesg,ier=scimin.leastsq(residuals, p0,full_output=True) #traditionnal least squares fit
# least square fir with constraints
def sum_residuals(p): # the function we want to minimize
return sum(residuals(p)**2)
def constraints(p): # the constraints: all the values of the returned array will be >=0 at the end
return constraintmaxy-fitfunc(constraintmaxx,p)
pwith=scimin.fmin_slsqp(sum_residuals,pwithout,f_ieqcons=constraints) # minimization with constraint
# plotting
ax=mpl.figure().add_subplot(1,1,1)
ax.plot(datax,datay,ls="",marker="x",color="blue",mew=2.0,label="Datas")
ax.plot(constraintmaxx,constraintmaxy,ls="",marker="x",color="red",mew=2.0,label="Max points")
morex=numpy.linspace(0,6,100)
ax.plot(morex,fitfunc(morex,pwithout),color="blue",label="Fit without constraints")
ax.plot(morex,fitfunc(morex,pwith),color="red",label="Fit with constraints")
ax.legend(loc=2)
mpl.show()
在这个例子中,我在抛物线上拟合了一个假想的点样本。这是没有和有约束的结果(左侧的红十字):

我希望这对您的数据样本有用;否则,请发布您的数据文件之一,以便我们可以尝试使用真实数据。我知道我的示例没有处理数据上的误差线,但您可以通过修改残差函数轻松处理它们。