機器學習——線性回歸

  • 2020 年 1 月 19 日
  • 筆記

導入類庫

 1 from sklearn.externals import joblib   2 from sklearn.model_selection import train_test_split   3 from sklearn.datasets import load_boston   4 from sklearn.preprocessing import StandardScaler   5 from sklearn.linear_model import LinearRegression   6 from sklearn.metrics import r2_score   7 from sklearn import neighbors   8 import pandas as pd   9 import numpy as np  10 import seaborn as sns  11 import matplotlib.pyplot as plt  12 import sklearn.preprocessing as sp  13 import sklearn.pipeline as pl

小知識

1 # np.column_stack:取行排列數組  2 # np.vstack:取列排列數組  3 # a = np.array([1,2])  4 # b = np.array([3,4])  5 # print(np.vstack((a,b)))  6 # array([[1, 2],[3, 4]])  7 # print(np.column_stack((a,b)))  8 # array([[1, 3],[2, 4]])

獲取波士頓房價數據

1 # 獲取波士頓房價數據  2 lb = load_boston()  3 # 將房價數據轉換為每行包括影響因素和房價的DataFrame  4 df = pd.DataFrame(np.column_stack((lb.data, lb.target)),  5                   columns=['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD',  6                            'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV'])  7 cols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']  8 print(df)  9 print(df[cols])

多變數圖

 1 def pairplot_analyse():   2     '''   3     style:whitegrid-白色網格圖   darkgrid-黑色網格圖  ticks-散點圖   dark white   4     context:notebook    paper   talk    poster      # size: paper < talk < poster < notebook   5     palette:調色板   6     kind:使用回歸   7     diag_kind:改變對角圖   8     markers:改變點形狀   9     :return:  10     '''  11     sns.set(style='dark', context='notebook')  12     sns.pairplot(df[cols], height=2, palette='husl', kind='reg', diag_kind='kde', markers='+')  13     plt.tight_layout()  14     plt.show()

熱點圖

 1 def heatmap_analyse():   2     '''   3     cbar:柱子   4     annot:標記   5     square:方形   6     fmt:數據格式   7     yticklabels:y軸標籤   8     xticklabels:x軸標籤   9     :return:  10     '''  11     # 計算皮爾遜相關係數  12     corr = np.corrcoef(df[cols].values.T)  13     # 生成熱點圖  14     hm = sns.heatmap(corr, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={'size': 15}, yticklabels=cols,  15                      xticklabels=cols)  16     plt.show()

回歸方法是一種對數值型連續隨機變數進行預測和建模的監督學習演算法。使用案例一般包括房價預測、股票走勢或測試成績等連續變化的案例; 回歸任務的特點是標註的數據集具有數值型的目標變數。也就是說,每一個觀察樣本都有一個數值型的標註真值以監督演算法。

線性回歸

 1 def bostn_linear():   2     '''   3     線性回歸直接預測房子價格   4     :return:   5     '''   6   7     # 獲取數據   8     lb = load_boston()   9  10     # 分割數據集為訓練集和測試集 test_size:分割比例  11     x_train, x_test, y_train, y_test = train_test_split(lb.data, lb.target, test_size=0.25)  12  13     # print(y_train, y_test)  14     # 特徵值和目標值是都必須進行標準化處理,實例化兩個標準化API  15     std_x = StandardScaler()  16  17     x_train = std_x.fit_transform(x_train)  18     # 用轉化訓練集的標準歸一化測試集:上是fit_transform,下是transform  19     x_test = std_x.transform(x_test)  20  21     # 目標值  22     std_y = StandardScaler()  23     # -1表示自動識別行數  24     y_train = std_y.fit_transform(y_train.reshape(-1, 1))  25     y_test = std_y.transform(y_test.reshape(-1, 1))  26  27     # estimator  28     # 正規方程求解方式預測結果  29     # 創建線性回歸對象  30     lr = LinearRegression()  31     # 訓練數據  32     lr.fit(x_train, y_train)  33     print(lr.coef_)  # 權值  34  35     # 保存訓練好的模型  36     joblib.dump(lr, './test.pkl')  37  38     # 預測測試集的房子價格  39     # y_lr_predict = std_y.inverse_transform(lr.predict(x_test))  40     orgin = std_y.inverse_transform(y_test[3])  # 轉換成原格式  41     print('orgin value is:::::', orgin)  42     y_lr_predict = std_y.inverse_transform(lr.predict(np.array([x_test[3]])))  # predict參數是二維數組  43  44     print('正規方程測試集裡面每個房子的預測價格:', y_lr_predict)  45     # print('正規方程R2評分:', r2_score(std_y.inverse_transform(y_test), y_lr_predict))  46     # print('正規方程R2評分:', r2_score(orgin, y_lr_predict))     #r2_score,參數1:原測試數據,參數2:預測數據

原影像與預測影像對比

 1 def log_fit():   2     x = np.linspace(0, 20, 50)   3     y = x ** 3 + np.random.random(50, ) * 100   4     # pf = sp.PolynomialFeatures(3)   5   6     lr = LinearRegression()   7     # modle = pl.make_pipeline(pf,lr)   8     lr.fit(x.reshape(-1, 1), y)   9     x_predict = lr.predict(x.reshape(-1, 1))  10     print(x_predict)  11  12     plt.scatter(x, y)  # 曲線:原曲線  13     plt.scatter(x, x_predict, c='r')  # 直線:預測曲線  14     plt.show()

房價預測實例

 1 def test_fj():   2     X = np.array([[500, 3, 0.3], [1000, 1, 0.6], [750, 2, 0.3], [600, 5, 0.2], [1200, 1, 0.6]], dtype=float)   3     Y = np.array([10000, 9000, 8000, 12000, 8500], dtype=float)   4   5     x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.25)   6     print(x_train, x_test)   7     print('===================================================')   8     print(y_train, y_test)   9  10     std_x = StandardScaler()  11     x_train = std_x.fit_transform(x_train)  12     x_test = std_x.transform(x_test)  13  14     std_y = StandardScaler()  15     y_train = std_y.fit_transform(y_train.reshape(-1, 1))  16     y_test = std_y.transform(y_test.reshape(-1, 1))  17  18     lr = LinearRegression()  19     lr.fit(x_train, y_train)  20     print(lr.coef_)  21  22     # orign = std_y.inverse_transform(y_test[1])  23     # print('orign is value:::::',orign)  24     # y_lr_predict = std_y.inverse_transform(lr.predict(np.array([x_test[1]])))  25     y_lr_predict = std_y.inverse_transform(lr.predict(x_test))  26  27     print('房價:', y_lr_predict)  28     print('評分:', r2_score(std_y.inverse_transform(y_test), y_lr_predict))  29  30  31 def price_predict():  32     # 數據有三個特徵:距離地鐵距離、附近小學、小區綠化率  33     X = np.array([[500, 3, 0.3], [1000, 1, 0.6], [750, 2, 0.3], [600, 5, 0.2], [1200, 1, 0.6]], dtype=float)  34     # 具有三個特徵的房屋對應的房價  35     Y = np.array([10000, 9000, 8000, 12000, 8500], dtype=float)  36  37     std_x = StandardScaler()  38     x_train = std_x.fit_transform(X)  39  40     std_y = StandardScaler()  41     y_train = std_y.fit_transform(Y.reshape(-1, 1))  42     # 構建線性預測模型  43     lr = LinearRegression()  44     # 模型在歷史數據上進行訓練,Y.reshape(-1,1)將Y變為二維數組,fit函數參數要求是二維數組  45     lr.fit(x_train, y_train.reshape(-1, 1))  46     # 使用訓練模型預測新房屋價格  47     distance = input('請輸入新房屋距離地鐵的距離:')  48     school = input('請輸入附近小學數量:')  49     green = input('請輸入小區綠化率:')  50     x_predict = std_x.transform(np.array([[distance, school, green]], dtype=float))  51     print(std_y.inverse_transform(lr.predict(x_predict)))  52     # print(lr.predict(np.array([[distance, school, green]], dtype=float)))  53     # print(lr.predict(np.array([[1300, 3, 0.4]])))  54  55  56 if __name__ == '__main__':  57     pairplot_analyse()  58     # heatmap_analyse()  59     # bostn_linear()  60     # log_fit()  61     # test_fj()  62     # price_predict()  63     pass

 線性回歸的幾個特點:  1. 建模速度快,不需很複雜的計算,數據量大的情況下依然運行速度很快;  2. 可以根據係數給出每個變數的理解和解釋 ; 3. 對異常值敏感。