数学建模-线性拟合

线性拟合

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

最小二乘法拟合公式:
^k=n∑i=1nxiyi-∑i=1nyi∑i=1nxin∑i=1nx2i-∑i=1nxi∑i=1nxi

^b=∑i=1nx2i∑i=1nyi-∑i=1nxi∑i=1nxiyin∑i=1nx2i-∑i=1nxi∑i=1nxi

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

image

2.1通过计算拟合优度评价拟合好坏

拟合优度 R2
总体平方和SST SST=∑i=1n(yi-y_)2
误差平方和SSE SSE=∑i=1n(yi-y^i)2
回归平方和SSR SSE=∑i=1n(y^i-y_i)2
公式 SST=SSE十SSR
拟合优度 0≤R2=SSRSST=SST-SSESST=1-SSESST≤1

(拟合优度只适合线性拟合,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
posted @ 2022-05-31 16:41  玥瑕  阅读(711)  评论(0)    收藏  举报