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()