在Python中使用最小二乘法拟合多项式数据
要对多项式数据进行最小二乘拟合,可以使用Python的Numpy库中的polynomial.polyfit()方法。该方法返回按照低到高排序的多项式系数。如果y是二维的,则coef的第k列表示拟合到y的第k列数据的多项式拟合。参数x是M个样本(数据)点的x坐标(x[i],y[i])。
参数y是样本点的y坐标。多个共享相同x坐标的样本点集可以通过一次polyfit调用来独立设置,只需将y作为一个包含每列一个数据集的二维数组进行传递。参数deg是拟合多项式的阶数。如果deg是一个整数,拟合将包括所有项直到deg的项。
参数rcond是拟合条件数的相对值。小于rcond的奇异值相对于最大奇异值将被忽略。默认值是len(x)*eps
,其中eps是平台浮点类型的相对精度,在大多数情况下约为2e-16。参数full是返回值性质的开关。当为False(默认值)时,只返回系数;当为True时,还返回奇异值分解的诊断信息。
参数w是权重。如果不为空,权重w[i]应用于x[i]处未平方的残差y[i] – y_hat[i]。理想情况下,权重应该选择为使所有产品w[i]*y[i]的误差具有相同方差。当使用逆方差加权时,使用w[i] = 1/ sigma(y[i])。默认值为None。
步骤
首先,导入所需的库−
import numpy as np
from numpy.polynomial import polynomial as P
The x-coordinate −
x坐标 –
x = np.linspace(-1,1,51)
显示x坐标-
print("X Co-ordinate...\n",x)
y坐标 –
y = x**3 - x + np.random.randn(len(x))
print("\nY Co-ordinate...\n",y)
要将多项式拟合到数据的最小二乘法,请使用Python NumPy中的polynomial.polyfit()。
c, stats = P.polyfit(x,y,3,full=True)
print("\nResult...\n",c)
print("\nResult...\n",stats)
示例
import numpy as np
from numpy.polynomial import polynomial as P
# The x-coordinate
x = np.linspace(-1,1,51)
# Display the x-coordinate
print("X Co-ordinate...\n",x)
# The y-coordinate
y = x**3 - x + np.random.randn(len(x))
print("\nY Co-ordinate...\n",y)
# To get the least-squares fit of a polynomial to data, use the polynomial.polyfit() in Python Numpy
# The method returns the Polynomial coefficients ordered from low to high. If y was 2-D, the coefficients in column k of coef represent the polynomial fit to the data in y’s k-th column.
c, stats = P.polyfit(x,y,3,full=True)
print("\nResult...\n",c)
print("\nResult...\n",stats)
输出
X Co-ordinate...
[-1. -0.96 -0.92 -0.88 -0.84 -0.8 -0.76 -0.72 -0.68 -0.64 -0.6 -0.56
-0.52 -0.48 -0.44 -0.4 -0.36 -0.32 -0.28 -0.24 -0.2 -0.16 -0.12 -0.08
-0.04 0. 0.04 0.08 0.12 0.16 0.2 0.24 0.28 0.32 0.36 0.4
0.44 0.48 0.52 0.56 0.6 0.64 0.68 0.72 0.76 0.8 0.84 0.88
0.92 0.96 1. ]
Y Co-ordinate...
[ 0.24282445 -0.48320773 -1.18068109 -0.48486683 0.80514762 0.48976259
0.31363813 -0.03382685 -0.92334611 0.86835062 0.24661201 0.9790978
0.03782101 0.12213365 -1.37248029 1.99891304 -0.09825977 1.74524931
0.70560858 0.15516069 0.69169705 0.76957712 -1.21919676 1.50064825
1.32101339 -2.51479992 -0.28998783 -1.24293076 0.45927699 -0.53484746
0.50455341 -0.06351788 -2.69585303 -0.46833578 1.4924168 -2.42374146
-1.91934499 -1.36311466 -1.23946547 -1.56822005 -0.79648036 1.58269324
-0.53682862 -0.90861958 -0.28174461 -0.10775622 0.58535687 1.06373501
-2.28991738 2.01597286 -0.75841069]
Result...
[-0.17198829 -1.84107674 0.09439374 2.39030912]
Result...
[array([60.43653521]), 4, array([1.38446749, 1.32119158, 0.50443316, 0.28853036]), 1.1324274851176597e-14]