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,1,0,5]) 10 #plt.title("") 11 # 每个小的方括号是一列 12 point=[[0,0.9],[0.2,1.9],[0.4,2.8],[0.6,3.3],[0.8,4.2]] 13 plt.xlabel("X") 14 plt.ylabel("Y") 15 Xsum = 0.0; 16 Isum = 0.0; 17 Ysum = 0.0; 18 X2sum = 0.0; 19 XYsum = 0.0; 20 21 22 23 for i in range(0,5): 24 25 xi=point[i][0]; 26 yi=point[i][1]; 27 plt.scatter(xi,yi,color="red"); 28 show_point = "["+ str(xi) +","+ str(yi) + "]"; 29 plt.text(xi,yi,show_point); 30 31 Xsum = Xsum+xi; 32 Isum = Isum+1; 33 Ysum = Ysum+yi; 34 X2sum = X2sum+xi**2; 35 XYsum = XYsum+xi*yi; 36 print Xsum; 37 print Isum; 38 print Ysum; 39 print X2sum; 40 print XYsum; 41 42 # 将矩阵运算化为 mat1 * mat3 = mat2 43 # _mat1 设为 mat1 的逆矩阵 44 # 则有 mat3 = _mat1 * mat2 45 # 每个小的方括号是一行 46 m1=[[Isum,Xsum],[Xsum, X2sum]]; 47 mat1 = np.matrix(m1); 48 m2=[[Ysum], [XYsum]]; 49 mat2 = np.matrix(m2); 50 _mat1 =mat1.getI(); 51 mat3 = _mat1*mat2 52 53 # 将矩阵转化为list来提取数据 54 # y = a+bx 55 m3=mat3.tolist(); 56 a = m3[0][0]; 57 b = m3[1][0]; 58 59 # 绘制回归线 60 x = np.linspace(0,1) 61 y = a + b*x; 62 plt.plot(x,y) 63 show_line = "y="+str(a)+"+"+str(b)+"x"; 64 plt.text(0.1,4,show_line,); 65 plt.show()