The COBYLA minimzer can handle such problems. In the following example a polynomial of degree 3 is fitted with the constraint that the derivative is positive everywhere.
from matplotlib import pylab as plt
import numpy as np
from scipy.optimize import minimize
def func(x, pars):
a,b,c,d=pars
return a*x**3+b*x**2+c*x+d
x = np.linspace(-4,9,60)
y = func(x, (.3,-1.8,1,2))
y += np.random.normal(size=60, scale=4.0)
def resid(pars):
return ((y-func(x,pars))**2).sum()
def constr(pars):
return np.gradient(func(x,pars))
con1 = {'type': 'ineq', 'fun': constr}
res = minimize(resid, [.3,-1,1,1], method='cobyla', options={'maxiter':50000}, constraints=con1)
print res
f=plt.figure(figsize=(10,4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
ax1.plot(x,y,'ro',label='data')
ax1.plot(x,func(x,res.x),label='fit')
ax1.legend(loc=0)
ax2.plot(x,constr(res.x),label='slope')
ax2.legend(loc=0)
plt.show()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…