线性拟合
学习笔记!
一、用最小二乘法进行线性拟合
给定一组数据做拟合直线 p(x) = a + bx ,均方误差为
,在微积分理论中,Q(a,b)的极小值要满足
整理成矩阵的形式:
这称为拟合曲线的法方程。
用消元法或克莱姆方法解出方程:
二、算例
数据集:x= 13,15,16,21,22,23,25,29,30,31,36,40,42,55,60,62,64,70,72,100,130
y= 11,10,11,12,12,13,13,12,14,16,17,13,14,22,14,21,21,24,17,23,34程序实现:
#线性拟合:y=a+bx import numpy as np x_array =
np.array([13,15,16,21,22,23,25,29,30,31,36,40,42,55,60,62,64,70,72,100,130])#x_array,y_array是我们要拟合的数据
y_array =
np.array([11,10,11,12,12,13,13,12,14,16,17,13,14,22,14,21,21,24,17,23,34]) m =
len(x_array) #方程个数 sum_x = np.sum(x_array) sum_y = np.sum(y_array) sum_xy =
np.sum(x_array * y_array) sum_xx = np.sum(x_array **2 )
a=(sum_y*sum_xx-sum_x*sum_xy)/(m*sum_xx-(sum_x)**2)
b=(m*sum_xy-sum_x*sum_y)/(m*sum_xx-(sum_x)**2) print("p = {:.4f} +
{:.4f}x".format(a,b))
输出结果:p = 8.2084 + 0.1795x数据可视化展示:
热门工具 换一换