符合派生Python的约束 [英] Fitting with constraints on derivative Python
问题描述
在尝试创建优化算法时,我不得不对集合的曲线拟合施加约束。
While trying to create an optimization algorithm, I had to put constraints on the curve fitting of my set.
这是我的问题,我有一个数组:
Here is my problem, I have an array :
Z = [10.3, 10, 10.2, ...]
L = [0, 20, 40, ...]
我需要找到适合 Z $的函数c $ c>的条件是坡度,这是我要寻找的函数的导数。
I need to find a function that fits Z
with condition on slope which is the derivative of the function I'm looking for.
假设 f
是我的功能, f
应该适合 Z
并在 f $上有条件
Suppose f
is my function, f
should fit Z
and have a condition on f
its derivative, it shouldnt exceed a special value.
python中是否有任何库可以帮助我完成此任务?
Are there any libraries in python that can help me achieve this task ?
推荐答案
COBYLA minimzer可以处理此类问题。在下面的示例中,阶数为3的多项式符合以下条件:导数在任何地方都是正数。
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()
这篇关于符合派生Python的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!