如何将某些系数约束的多项式拟合?

编程入门 行业动态 更新时间:2024-10-21 07:36:24
本文介绍了如何将某些系数约束的多项式拟合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用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?

推荐答案

在这种情况下,我将使用 curve_fit 或 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]

因此,在不受约束的情况下,polyfit和curve_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.

更多推荐

如何将某些系数约束的多项式拟合?

本文发布于:2023-07-27 23:07:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多项式   系数   如何将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!