1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
import numpy as np import matplotlib.pyplot as plt import sys,os
def loadData(): file_path = 'data/LR_in.txt' file = open(file_path) data_set = np.loadtxt(file) X0 = np.array([1.0 for i in range(data_set.shape[0])]) return np.c_[X0,data_set[:,:-1]],data_set[:,-1]
def calculateMethod(X_parameters, Y_parameters): X = np.mat(X_parameters) y = np.mat(Y_parameters).T tmp1 = np.dot(X.T,X).I tmp2 = np.dot(X.T,y) theta = np.dot(tmp1,tmp2) theta = np.array(theta) print(theta) return theta
def predictOut(X_parameters, theta): X = np.mat(X_parameters) theta = np.mat(theta) out = np.dot(X,theta) return out
def draw(X_parameters, Y_parameters,theta): plt.scatter(X_parameters[:,-1],Y_parameters,color='blue') Y_predict_out = predictOut(X_parameters,theta) plt.plot(X_parameters[:,-1],Y_predict_out,color='r',linewidth=4) plt.xlabel('Year') plt.ylabel('House Price') plt.show() return
def main(): X_parameters, Y_parameters = loadData() theta = calculateMethod(X_parameters,Y_parameters) draw(X_parameters,Y_parameters,theta) return
if __name__ == '__main__': main()
|