当导数的值受到约束时,如何拟合多项式



对于x的某个值范围,有没有一种简单的方法可以得到对多项式函数f(x)的导数的最大值有约束的解?

正如对这个问题的回答一样,scipy.optimize中的curve_fit可以处理对单个系数的约束,如以下示例中所示:

def func(x, a, b, c, d):
return a + b * x + c * x ** 2 + d * x ** 3
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
popt_cons, _ = curve_fit(func, x, y, bounds=([-np.inf, 2, -np.inf, -np.inf], [np.inf, 2.001, np.inf, np.inf]))
print(popt_cons)
>>> [-0.14331349  2.         -0.95913556  0.10494372]

但是,如果我想要一个最佳拟合多项式,其中有一个约束,例如,对于某个范围的x值,加速度的最大值(二阶导数(,该怎么办?这意味着,通过对函数进行两次积分,对于010之间的x,对2*c + 6*d*x的值存在约束。有没有一种方法可以做到这一点,或者我必须从头开始构建它?

curve_fit方法不支持额外的约束。然而,您可以实现非线性最小二乘问题

min ||f(x, coeffs) - y||^2
s.t.    lb <= coeffs <= ub
f''(x, coeffs) <= max_val for all x_lb <= x <= x_ub

并用CCD_ 11求解。下面是一个如何通过np.polyvalnp.polyder实现的示例:

import numpy as np
from scipy.optimize import minimize
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
def objective(coeffs):
return np.linalg.norm(np.polyval(coeffs, x) - y)
def constraint(coeffs, deriv_order, x_lb, x_ub, max_val):
deriv_coeffs = np.polyder(coeffs, deriv_order)
# Evaluate the derivative for all x_lb <= x <= x_ub
deriv_value = np.polyval(deriv_coeffs, x[(x >= x_lb) & (x <= x_ub)])
return -1.0*deriv_value + max_val
# Each inequality constraint has the form fun(x) >= 0
cons = [{'type': 'ineq', 'fun': lambda coeffs: constraint(coeffs, 2, 0.0, 3.0, 20)}]
bnds = [(-np.inf, np.inf), (2, 5.001), (-np.inf, np.inf), (-np.inf, np.inf)]
poly_degree = 3
res = minimize(objective, x0=2.0*np.ones(poly_degree+1), bounds=bnds, constraints=cons)

注意,每个不等式约束都有fun(x) >= 0的形式,即我们有-f''(x, coeffs) + max_val >= 0,并且我们使用x_lb = 0.0x_ub = 3.0max_val = 20作为二阶导数。最后,res.x包含多项式系数。

最新更新