擅长:python、mysql、java
<p>COBYLA Minizer可以处理这些问题。在下面的例子中,一个3次多项式的导数处处为正的约束条件被拟合。在</p>
<pre><code>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()
</code></pre>
<p><a href="https://i.stack.imgur.com/wmjPd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wmjPd.png" alt="sample data and fit"/></a></p>