gpt4 book ai didi

python - 拟合派生 Python 的约束

转载 作者:行者123 更新时间:2023-12-01 08:55:26 24 4
gpt4 key购买 nike

在尝试创建优化算法时,我必须对我的集合的曲线拟合施加约束。

这是我的问题,我有一个数组:

Z = [10.3, 10, 10.2, ...]
L = [0, 20, 40, ...]

我需要找到一个符合 Z 的函数,其斜率条件是我正在寻找的函数的导数。

假设f是我的函数,f应该适合Z并且对f它的导数有一个条件,它不应该超过一个特殊值。

Python 中是否有任何库可以帮助我完成此任务?

最佳答案

COBYLA minimzer 可以处理此类问题。在下面的示例中,3 次多项式的拟合条件是导数处处为正。

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()

sample data and fit

关于python - 拟合派生 Python 的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52804492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com