最小二乘拟合二元直线

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最小二乘拟合二元直线相关的知识,希望对你有一定的参考价值。

 

 1 #encoding=utf-8
 2 from  matplotlib import pyplot as plt
 3 import  numpy as np
 4 from mpl_toolkits.mplot3d import Axes3D
 5 # 生成画布
 6 fig = plt.figure();
 7 ax = Axes3D(fig);
 8 
 9 point=[[2,3,48],[4,5,50],[5,7,51],[8,9,55],[9,12,56]];
10 plt.xlabel("X1")
11 plt.ylabel("X2")
12 Isum = 0.0;
13 X1sum = 0.0;
14 X2sum = 0.0;
15 X1_2sum = 0.0;
16 X1X2sum = 0.0;
17 X2_2sum = 0.0;
18 Ysum = 0.0;
19 X1Ysum = 0.0
20 X2Ysum = 0.0;
21 
22 for i in range(0,len(point)):
23 
24     x1i=point[i][0];
25     x2i=point[i][1];
26     yi=point[i][2];
27     # 显示数据点
28     ax.scatter(x1i, x2i, yi, color="red");
29     show_point = "["+ str(x1i) +","+ str(x2i)+","+str(yi) + "]";
30     ax.text(x1i,x2i,yi,show_point);
31     # 求矩阵中的值
32     Isum = Isum+1;
33     X1sum = X1sum+x1i;
34     X2sum = X2sum+x2i;
35     X1_2sum = X1_2sum+x1i**2;
36     X1X2sum = X1X2sum+x1i*x2i;
37     X2_2sum = X2_2sum+x2i**2;
38     Ysum = Ysum+yi;
39     X1Ysum = X1Ysum+x1i*yi;
40     X2Ysum = X2Ysum+x2i*yi;
41 
42 # 将矩阵运算化为 mat1 * mat3 = mat2
43 # _mat1 设为 mat1 的逆矩阵
44 # 则有 mat3 =  _mat1 * mat2
45 m1=[[Isum,X1sum,X2sum],[X1sum,X1_2sum,X1X2sum],[X2sum,X1X2sum,X2_2sum]];
46 mat1 = np.matrix(m1);
47 m2=[[Ysum],[X1Ysum],[X2Ysum]];
48 mat2 = np.matrix(m2);
49 _mat1 =mat1.getI();
50 mat3 = _mat1*mat2
51 
52 # 将矩阵转化为list来提取数据
53 # y = a0+a1x1+a2x2
54 m3=mat3.tolist();
55 a0 = m3[0][0];
56 a1 = m3[1][0];
57 a2 = m3[2][0];
58 # 绘制回归线
59 x1 = np.linspace(0,10)
60 x2 = np.linspace(0,15)
61 y = a0+a1*x1+a2*x2;
62 ax.plot(x1,x2,y);
63 # plt.plot(x,y)
64 show_line = "y="+str(a0)+"+"+str(a1)+"x1"+"+"+str(a2)+"x2";
65 ax.text(0,0,40,show_line);
66 
67 plt.show();

 

以上是关于最小二乘拟合二元直线的主要内容,如果未能解决你的问题,请参考以下文章

halcon之最小二乘拟合直线

PCL最小二乘法进行平面拟合原理

Python最小二乘法拟合与作图

PCL 平面拟合——最小二乘

数据拟合:最小二乘二维圆拟合的C++实现(另一种方法)

线性最小二乘两种方法