码迷,mamicode.com
首页 > 其他好文 > 详细

(九)最小二乘拟合二次曲线

时间:2017-12-11 11:18:15      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:odi   blog   att   text   4sum   mat   sum   回归线   log   

 

 1 #coding=utf-8
 2 from numpy import *
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 
 6 plt.close()
 7 fig=plt.figure()
 8 plt.grid(True)
 9 plt.axis([0,8,0,8])
10 #plt.title("")
11 point=[[1,2],[2,3],[3,6],[4,7],[6,5],[7,3],[8,2]];
12 plt.xlabel("X")
13 plt.ylabel("Y")
14 Xsum = 0.0;
15 X2sum = 0.0;
16 X3sum = 0.0;
17 X4sum = 0.0;
18 Isum = 0.0;
19 Ysum = 0.0;
20 XYsum = 0.0;
21 X2Ysum = 0.0;
22 
23 
24 
25 for i in range(0,len(point)):
26 
27     xi=point[i][0];
28     yi=point[i][1];
29     plt.scatter(xi,yi,color="red");
30     show_point = "["+ str(xi) +","+ str(yi) + "]";
31     plt.text(xi,yi,show_point);
32 
33     Xsum = Xsum+xi;
34     X2sum = X2sum+xi**2;
35     X3sum = X3sum + xi**3;
36     X4sum = X4sum + xi**4;
37     Isum = Isum+1;
38     Ysum = Ysum+yi;
39     XYsum = XYsum+xi*yi;
40     X2Ysum = X2Ysum + xi**2*yi;
41 
42 # # 将矩阵运算化为 mat1 * mat3 = mat2
43 # # _mat1 设为 mat1 的逆矩阵
44 # # 则有 mat3 =  _mat1 * mat2
45 m1=[[Isum,Xsum, X2sum],[Xsum, X2sum, X3sum],[X2sum, X3sum, X4sum]];
46 mat1 = np.matrix(m1);
47 m2=[[Ysum], [XYsum], [X2Ysum]];
48 mat2 = np.matrix(m2);
49 _mat1 =mat1.getI();
50 mat3 = _mat1*mat2
51 
52 # 将矩阵转化为list来提取数据
53 # y = a+bx+cx2
54 m3=mat3.tolist();
55 a = m3[0][0];
56 b = m3[1][0];
57 c = m3[2][0];
58 # 绘制回归线
59 x = np.linspace(0,8)
60 y = a + b*x + c*x**2;
61 plt.plot(x,y)
62 show_line = "y="+str(a)+"+("+str(b)+"x)"+"+("+str(c)+"x2)";
63 plt.text(0.1,7.5,show_line,);
64 plt.show()

 

(九)最小二乘拟合二次曲线

标签:odi   blog   att   text   4sum   mat   sum   回归线   log   

原文地址:http://www.cnblogs.com/the-wang/p/8021525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!