在Python中使用最小二乘法拟合勒让德级数到数据
要使用最小二乘法拟合勒让德级数到数据,可以在Python的numpy中使用legendre.legfit()方法。该方法返回从低到高排序的勒让德系数。如果y是2维的,那么数据在y的第k列的系数将在第k列中。
参数x是M个采样点(数据点)的x坐标(x[i], y[i])。参数y是采样点的y坐标。可以通过将包含每列一个数据集的2维数组y传递给polyfit来同时拟合共享相同x坐标的几组采样点。
参数deg是拟合多项式的次数。如果deg是一个整数,所有符合deg及以下的项将包含在拟合中。参数rcond是拟合的相对条件数。相对于最大奇异值,小于rcond的奇异值将被忽略。默认值为len(x)*eps,其中eps是平台浮点类型的相对精度,在大多数情况下约为2e-16。参数full是返回值的类型开关。当为False(默认值)时,仅返回系数;当为True时,还返回奇异值分解的诊断信息。
参数w是权重。如果不为None,则权重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 legendre as L
横坐标 –
x = np.linspace(-1,1,51)
展示 x 坐标 −
print("X Co-ordinate...\n",x)
纵坐标-
y = x**3 - x + np.random.randn(len(x))
print("\nY Co-ordinate...\n",y)
为了将数据拟合为勒让德级数的最小二乘拟合,可以在Python的numpy中使用legendre.legfit()方法。 该方法返回从低到高排序的勒让德系数。如果y是二维的,则y的第k列的数据的系数在第k列中。
c, stats = L.legfit(x,y,3,full=True)
print("\nResult...\n",c)
print("\nResult...\n",stats)
示例
import numpy as np
from numpy.polynomial import legendre as L
# 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 Legendre series to data, use the legendre.legfit() method in Python numpy
c, stats = L.legfit(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...
[-5.28795520e-02 -7.61252904e-03 7.35194215e-02 -1.33072588e-01
-1.21785636e+00 7.75679385e-02 6.55168668e-01 1.42872448e+00
8.42326214e-01 2.49667989e+00 9.58942508e-01 -2.67332869e-01
-7.85575928e-01 1.93333045e+00 7.32492468e-01 5.23576961e-01
-1.91529521e+00 -1.41434385e+00 4.44787373e-01 3.81831261e-01
3.74128321e-01 1.20562789e+00 1.44870029e+00 1.01091575e-03
8.94334713e-01 1.22342199e+00 9.52055370e-01 -7.29520012e-01
-2.42648820e-01 -9.78434555e-02 1.27468237e-01 9.39489448e-01
1.08795136e+00 2.31230197e+00 1.93107556e-02 -6.13335407e-01
1.93170835e-01 -8.77958854e-01 -3.59868085e-01 4.31331759e-01
7.24929856e-01 -2.22736540e-01 -1.29623093e+00 4.13226024e-01
7.82155644e-01 -1.56618537e-01 1.25043737e+00 6.32386988e-01
-2.75716271e-01 8.80669895e-02 -3.20225560e-01]
Result...
[ 0.29249467 -0.10521942 -0.24847572 0.2010877 ]
Result...
[array([39.35467561]), 4, array([1.0425003 , 1.02126704, 0.97827074, 0.95561139]), 1.1324274851176597e-14]