1. 程式人生 > >最小二乘法多項式曲線擬合原理與實現 zz

最小二乘法多項式曲線擬合原理與實現 zz

博客 del p s 並且 多項式 聯網 python mar 程序

概念

最小二乘法多項式曲線擬合,根據給定的m個點,並不要求這條曲線精確地經過這些點,而是曲線y=f(x)的近似曲線y= φ(x)。

原理

[原理部分由個人根據互聯網上的資料進行總結,希望對大家能有用]

給定數據點pi(xi,yi),其中i=1,2,…,m。求近似曲線y= φ(x)。並且使得近似曲線與y=f(x)的偏差最小。近似曲線在點pi處的偏差δi= φ(xi)-y,i=1,2,...,m。

常見的曲線擬合方法:

1.使偏差絕對值之和最小

技術分享

2.使偏差絕對值最大的最小

技術分享

3.使偏差平方和最小

技術分享

按偏差平方和最小的原則選取擬合曲線,並且采取二項式方程為擬合曲線的方法,稱為最小二乘法。

推導過程:

1. 設擬合多項式為:

技術分享

2. 各點到這條曲線的距離之和,即偏差平方和如下:

技術分享

技術分享

技術分享

.......

技術分享

4. 將等式左邊進行一下化簡,然後應該可以得到下面的等式:

技術分享

技術分享

.......

技術分享


5. 把這些等式表示成矩陣的形式,就可以得到下面的矩陣:

技術分享

6. 將這個範德蒙得矩陣化簡後可得到:

技術分享

7. 也就是說 運行前提:

  1. Python運行環境與編輯環境;
  2. Matplotlib.pyplot圖形庫,可用於快速繪制2D圖表,與matlab中的plot命令類似,而且用法也基本相同。

代碼:

[python] view plain copy
  1. # coding=utf-8
  2. ‘‘‘‘‘
  3. 作者:Jairus Chan
  4. 程序:多項式曲線擬合算法
  5. ‘‘‘
  6. import matplotlib.pyplot as plt
  7. import math
  8. import numpy
  9. import random
  10. fig = plt.figure()
  11. ax = fig.add_subplot(111)
  12. #階數為9階
  13. order=9
  14. #生成曲線上的各個點
  15. x = numpy.arange(-1,1,0.02)
  16. y = [((a*a-1)*(a*a-1)*(a*a-1)+0.5)*numpy.sin(a*2) for a in x]
  17. #ax.plot(x,y,color=‘r‘,linestyle=‘-‘,marker=‘‘)
  18. #,label="(a*a-1)*(a*a-1)*(a*a-1)+0.5"
  19. #生成的曲線上的各個點偏移一下,並放入到xa,ya中去
  20. i=0
  21. xa=[]
  22. ya=[]
  23. for xx in x:
  24. yy=y[i]
  25. d=float(random.randint(60,140))/100
  26. #ax.plot([xx*d],[yy*d],color=‘m‘,linestyle=‘‘,marker=‘.‘)
  27. i+=1
  28. xa.append(xx*d)
  29. ya.append(yy*d)
  30. ‘‘‘‘‘for i in range(0,5):
  31. xx=float(random.randint(-100,100))/100
  32. yy=float(random.randint(-60,60))/100
  33. xa.append(xx)
  34. ya.append(yy)‘‘‘
  35. ax.plot(xa,ya,color=‘m‘,linestyle=‘‘,marker=‘.‘)
  36. #進行曲線擬合
  37. matA=[]
  38. for i in range(0,order+1):
  39. matA1=[]
  40. for j in range(0,order+1):
  41. tx=0.0
  42. for k in range(0,len(xa)):
  43. dx=1.0
  44. for l in range(0,j+i):
  45. dx=dx*xa[k]
  46. tx+=dx
  47. matA1.append(tx)
  48. matA.append(matA1)
  49. #print(len(xa))
  50. #print(matA[0][0])
  51. matA=numpy.array(matA)
  52. matB=[]
  53. for i in range(0,order+1):
  54. ty=0.0
  55. for k in range(0,len(xa)):
  56. dy=1.0
  57. for l in range(0,i):
  58. dy=dy*xa[k]
  59. ty+=ya[k]*dy
  60. matB.append(ty)
  61. matB=numpy.array(matB)
  62. matAA=numpy.linalg.solve(matA,matB)
  63. #畫出擬合後的曲線
  64. #print(matAA)
  65. xxa= numpy.arange(-1,1.06,0.01)
  66. yya=[]
  67. for i in range(0,len(xxa)):
  68. yy=0.0
  69. for j in range(0,order+1):
  70. dy=1.0
  71. for k in range(0,j):
  72. dy*=xxa[i]
  73. dy*=matAA[j]
  74. yy+=dy
  75. yya.append(yy)
  76. ax.plot(xxa,yya,color=‘g‘,linestyle=‘-‘,marker=‘‘)
  77. ax.legend()
  78. plt.show()

運行效果:

技術分享

本博客中所有的博文都為筆者(Jairus Chan)原創。

如需轉載,請標明出處:http://blog.csdn.net/JairusChan。

如果您對本文有任何的意見與建議,請聯系筆者(JairusChan)。

最小二乘法多項式曲線擬合原理與實現 zz