數學建模-線性擬合
阿新 • • 發佈:2022-05-31
線性擬合
1.1 作用
為了得到資料之間的固有規律或者用當前資料來預測期望得到的資料。
1.2 原理
設x和y都是被觀測的量,且y是x的函式:y=f(x; b),曲線擬合就是通過x,y的觀測值來尋求引數b的最佳估計值,及尋求最佳的理論曲線y=f(x; b)
2操作步驟
例題資料
x | y |
---|---|
4.2 | 8.4 |
5.9 | 11.7 |
2.7 | 4.2 |
3.8 | 6.1 |
3.8 | 7.9 |
5.6 | 10.2 |
6.9 | 13.2 |
3.5 | 6.6 |
3.6 | 6 |
2.9 | 4.6 |
4.2 | 8.4 |
6.1 | 12 |
5.5 | 10.3 |
6.6 | 13.3 |
2.9 | 4.6 |
3.3 | 6.7 |
5.9 | 10.8 |
6 | 11.5 |
5.6 | 9.9 |
最小二乘法擬合公式:
python 程式碼:
import pandas as pd import numpy as np import matplotlib.pyplot as plt df=pd.read_excel("./data1.xlsx") num_df=df.to_numpy() x=num_df[:,0] print(x) y=num_df[:,1] print(y) n=df.shape[0]#獲取自變數 #計算k值 k=(n*np.sum(x*y) - np.sum(x)*np.sum(y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x)) #技術b值 b=(np.sum(np.power(x,2)) * np.sum(y) -np.sum(x) * np.sum(x*y)) / (n*np.sum(np.power(x,2)) - np.sum(x) * np.sum(x)) las = k*x + b #根據公式得到擬合函式 fig = plt.figure() #獲得figure物件 ax1 = fig.add_subplot(1,1,1) #新增一個圖紙 ax1.set_xlim([min(x)-0.5, max(x)+0.5]) #設定x軸刻度 ax1.set_ylim([min(y) -0.5, max(y) +0.5]) #設定y軸刻度 plt.plot(x,las,'k',label='fit') #畫出擬合函式 plt.plot(x,y,'o',label = 'sample') #畫出樣本資料 plt.grid() #新增網格線 ax1.legend(loc = 'best') #設定圖例的位置為最佳best
2.1通過計算擬合優度評價擬合好壞
擬合優度 | |
---|---|
總體平方和SST | |
誤差平方和SSE | |
迴歸平方和SSR | |
公式 | |
擬合優度 |
(擬合優度只適合線性擬合,R^2越接近1說明效果越好)
python程式碼:
def AGFI(x,y,k,b): z=k*x+b SST=np.sum(np.power(y - np.average(y),2)) SSE=np.sum(np.power(y - z, 2)) SSR=np.sum(np.power(z - np.average(y),2)) R_2=SSR / SST return R_2