您好,登錄后才能下訂單哦!
這篇文章主要介紹“python實現線性回歸的代碼怎么寫”,在日常操作中,相信很多人在python實現線性回歸的代碼怎么寫問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”python實現線性回歸的代碼怎么寫”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
在簡單線性回歸中,通過調整a和b的參數值,來擬合從x到y的線性關系。下圖為進行擬合所需要優化的目標,也即是MES(Mean Squared Error),只不過省略了平均的部分(除以m)。
對于簡單線性回歸,只有兩個參數a和b,通過對MSE優化目標求極值(最小二乘法),即可求得最優a和b如下,所以在訓練簡單線性回歸模型時,也只需要根據數據求解這兩個參數值即可。
下面使用波士頓房價數據集中,索引為5的特征RM (average number of rooms per dwelling)來進行簡單線性回歸。其中使用的評價指標為:
# 以sklearn的形式對simple linear regression 算法進行封裝 import numpy as np import sklearn.datasets as datasets from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from sklearn.metrics import mean_squared_error,mean_absolute_error np.random.seed(123) class SimpleLinearRegression(): def __init__(self): """ initialize model parameters self.a_=None self.b_=None def fit(self,x_train,y_train): training model parameters Parameters ---------- x_train:train x ,shape:data [N,] y_train:train y ,shape:data [N,] assert (x_train.ndim==1 and y_train.ndim==1),\ """Simple Linear Regression model can only solve single feature training data""" assert len(x_train)==len(y_train),\ """the size of x_train must be equal to y_train""" x_mean=np.mean(x_train) y_mean=np.mean(y_train) self.a_=np.vdot((x_train-x_mean),(y_train-y_mean))/np.vdot((x_train-x_mean),(x_train-x_mean)) self.b_=y_mean-self.a_*x_mean def predict(self,input_x): make predictions based on a batch of data input_x:shape->[N,] assert input_x.ndim==1 ,\ """Simple Linear Regression model can only solve single feature data""" return np.array([self.pred_(x) for x in input_x]) def pred_(self,x): give a prediction based on single input x return self.a_*x+self.b_ def __repr__(self): return "SimpleLinearRegressionModel" if __name__ == '__main__': boston_data = datasets.load_boston() x = boston_data['data'][:, 5] # total x data (506,) y = boston_data['target'] # total y data (506,) # keep data with target value less than 50. x = x[y < 50] # total x data (490,) y = y[y < 50] # total x data (490,) plt.scatter(x, y) plt.show() # train size:(343,) test size:(147,) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3) regs = SimpleLinearRegression() regs.fit(x_train, y_train) y_hat = regs.predict(x_test) rmse = np.sqrt(np.sum((y_hat - y_test) ** 2) / len(x_test)) mse = mean_squared_error(y_test, y_hat) mae = mean_absolute_error(y_test, y_hat) # notice R_squared_Error = 1 - mse / np.var(y_test) print('mean squared error:%.2f' % (mse)) print('root mean squared error:%.2f' % (rmse)) print('mean absolute error:%.2f' % (mae)) print('R squared Error:%.2f' % (R_squared_Error))
輸出結果:
mean squared error:26.74
root mean squared error:5.17
mean absolute error:3.85
R squared Error:0.50
數據的可視化:
多元線性回歸中,單個x的樣本擁有了多個特征,也就是上圖中帶下標的x。
其結構可以用向量乘法表示出來:
為了便于計算,一般會將x增加一個為1的特征,方便與截距bias計算。
而多元線性回歸的優化目標與簡單線性回歸一致。
通過矩陣求導計算,可以得到方程解,但求解的時間復雜度很高。
下面使用正規方程解的形式,來對波士頓房價的所有特征做多元線性回歸。
import numpy as np from PlayML.metrics import r2_score from sklearn.model_selection import train_test_split import sklearn.datasets as datasets from PlayML.metrics import root_mean_squared_error np.random.seed(123) class LinearRegression(): def __init__(self): self.coef_=None # coeffient self.intercept_=None # interception self.theta_=None def fit_normal(self, x_train, y_train): """ use normal equation solution for multiple linear regresion as model parameters Parameters ---------- theta=(X^T * X)^-1 * X^T * y assert x_train.shape[0] == y_train.shape[0],\ """size of the x_train must be equal to y_train """ X_b=np.hstack([np.ones((len(x_train), 1)), x_train]) self.theta_=np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train) # (featere,1) self.coef_=self.theta_[1:] self.intercept_=self.theta_[0] def predict(self,x_pred): """給定待預測數據集X_predict,返回表示X_predict的結果向量""" assert self.intercept_ is not None and self.coef_ is not None, \ "must fit before predict!" assert x_pred.shape[1] == len(self.coef_), \ "the feature number of X_predict must be equal to X_train" X_b=np.hstack([np.ones((len(x_pred),1)),x_pred]) return X_b.dot(self.theta_) def score(self,x_test,y_test): Calculate evaluating indicator socre --------- x_test:x test data y_test:true label y for x test data y_pred=self.predict(x_test) return r2_score(y_test,y_pred) def __repr__(self): return "LinearRegression" if __name__ == '__main__': # use boston house price dataset for test boston_data = datasets.load_boston() x = boston_data['data'] # total x data (506,) y = boston_data['target'] # total y data (506,) # keep data with target value less than 50. x = x[y < 50] # total x data (490,) y = y[y < 50] # total x data (490,) # train size:(343,) test size:(147,) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3,random_state=123) regs = LinearRegression() regs.fit_normal(x_train, y_train) # calc error score=regs.score(x_test,y_test) rmse=root_mean_squared_error(y_test,regs.predict(x_test)) print('R squared error:%.2f' % (score)) print('Root mean squared error:%.2f' % (rmse))
輸出結果:
R squared error:0.79
Root mean squared error:3.36
import sklearn.datasets as datasets from sklearn.linear_model import LinearRegression import numpy as np from sklearn.model_selection import train_test_split from PlayML.metrics import root_mean_squared_error np.random.seed(123) if __name__ == '__main__': # use boston house price dataset boston_data = datasets.load_boston() x = boston_data['data'] # total x size (506,) y = boston_data['target'] # total y size (506,) # keep data with target value less than 50. x = x[y < 50] # total x size (490,) y = y[y < 50] # total x size (490,) # train size:(343,) test size:(147,) x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=123) regs = LinearRegression() regs.fit(x_train, y_train) # calc error score = regs.score(x_test, y_test) rmse = root_mean_squared_error(y_test, regs.predict(x_test)) print('R squared error:%.2f' % (score)) print('Root mean squared error:%.2f' % (rmse)) print('coeffient:',regs.coef_.shape) print('interception:',regs.intercept_.shape)
R squared error:0.79 Root mean squared error:3.36 coeffient: (13,) interception: ()
到此,關于“python實現線性回歸的代碼怎么寫”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。