在Python中使用最小二乘法拟合Hermite级数到数据

在Python中使用最小二乘法拟合Hermite级数到数据

要将Hermite级数的最小二乘拟合应用于数据,使用Python的hermite.hermfit()方法。该方法按照从低到高的顺序返回Hermite系数。如果y是2-D的,则y矩阵的第k列中的数据的系数在第k列中。参数x是M个样本(数据)点(x[i],y[i])的x坐标。参数y是样本点的y坐标。可以使用一次polyfit来独立地拟合具有相同x坐标的多组样本点,只需将y传入包含每个列的一个数据集的2-D数组中。

参数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] = 1/sigma(y[i]),使得所有产品w[i]*y[i]的误差具有相同的方差。默认值为None。

步骤

首先,导入所需的库-

import numpy as np
from numpy.polynomial import hermite as H

横坐标−

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)

将Hermite系列的最小二乘拟合应用到数据上,可使用Python numpy中的hermite.hermfit()方法。该方法返回Hermite系数,按从低到高的顺序排列。如果y是2维的,在y的第k列数据的系数将在第k-列中。

c, stats = H.hermfit(x,y,3,full=True)
print("\nResult...\n",c)
print("\nResult...\n",stats)

示例

import numpy as np
from numpy.polynomial import hermite as H

# 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 Hermite series to data, use the hermite.hermfit() method in Python numpy

c, stats = H.hermfit(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...
   [-1.54632387  1.51958929  1.97346067  1.17759858  0.18851406 -0.43906085
    -0.18878755 -0.25952276 -0.10422342  0.17851603  0.12145051  1.42408375
     0.87115462 -1.03677161  1.01691995  0.45143153 -2.11382606  0.92466707
    -0.04160743  0.9302213   1.19532222  1.69238045  1.63260027 -0.38037316
     1.57013958  0.50920773 -0.19218013 -1.104298    0.10788693  0.68370213
     0.7219109   1.28598447 -0.92218973 -0.11028072 -0.49917013 -1.44008132
    -1.51616162 -0.80578712  1.47099231 -0.79775329 -1.0606385  -0.59517496
    -0.32977967  1.04847432 -2.1621314  -0.40009103 -0.84519     0.06397194
    -2.03655702 -0.28429534  0.47013787]

Result...
   [-0.03198532 -0.0005095 -0.11666602 0.08302362]

Result...
   [array([49.28934723]), 4, array([1.39825832, 1.20144978, 0.74600162, 0.21183404]), 1.1324274851176597e-14]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程