如何将某些系数约束的多项式拟合? [英] How to fit a polynomial with some of the coefficients constrained?

查看:228
本文介绍了如何将某些系数约束的多项式拟合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NumPy的polyfit(或类似方法)是否有一种简单的方法来获得将一个或多个系数限制为特定值的解决方案?

Using NumPy's polyfit (or something similar) is there an easy way to get a solution where one or more of the coefficients are constrained to a specific value?

例如,我们可以使用以下公式找到普通的多项式拟合:

For example, we could find the ordinary polynomial fitting using:

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])
z = np.polyfit(x, y, 3)

屈服

array([ 0.08703704, -0.81349206,  1.69312169, -0.03968254])

但是,如果我想要最合适的多项式,其中第三系数(在上述情况下为z[2])必须为1,该怎么办?还是我需要从头开始编写配件?

But what if I wanted the best fit polynomial where the third coefficient (in the above case z[2]) was required to be 1? Or will I need to write the fitting from scratch?

推荐答案

在这种情况下,我将使用 lmfit ;我很快就展示了它.

In this case, I would use curve_fit or lmfit; I quickly show it for the first one.

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import 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])

print(np.polyfit(x, y, 3))

popt, _ = curve_fit(func, x, y)
print(popt)

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)

xnew = np.linspace(x[0], x[-1], 1000)

plt.plot(x, y, 'bo')
plt.plot(xnew, func(xnew, *popt), 'k-')
plt.plot(xnew, func(xnew, *popt_cons), 'r-')
plt.show()

这将打印:

[ 0.08703704 -0.81349206  1.69312169 -0.03968254]
[-0.03968254  1.69312169 -0.81349206  0.08703704]
[-0.14331349  2.         -0.95913556  0.10494372]

因此,在不受约束的情况下,polyfitcurve_fit给出的结果相同(只是顺序不同),在受约束的情况下,固定参数为2.

So in the unconstrained case, polyfit and curve_fit give identical results (just the order is different), in the constrained case, the fixed parameter is 2, as desired.

该图如下所示:

lmfit中,您还可以选择是否适合参数,因此也可以将其设置为所需的值.

In lmfit you can also choose whether a parameter should be fitted or not, so you can then also just set it to a desired value.

这篇关于如何将某些系数约束的多项式拟合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆