使用 NumPy 的 polyfit
(或类似的东西)是否有一种简单的方法来获得一个或多个系数被限制为特定值的解决方案?
例如,我们可以使用以下方法找到普通的多项式拟合:
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 的最佳拟合多项式怎么办?还是我需要从头开始编写配件?
最佳答案
在这种情况下,我会使用 curve_fit
或 lmfit
;我很快就展示了第一个。
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,如愿.
剧情如下:
在 lmfit
中,您还可以选择是否应拟合参数,因此您也可以将其设置为所需的值(检查 this answer)。
关于python - 如何拟合一些系数受限的多项式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48469889/