1 import pandas as pd 2 from sklearn.datasets import load_boston # 波士頓房價數據 3 from sklearn.model_selection import train_test_split # 拆分數據集 4 from sklearn.preprocessing import StandardScaler # 標准差標准化 5 from sklearn.linear_model import LinearRegression # 線性回歸模型 6 from sklearn.linear_model import SGDRegressor # 線性回歸模型 7 from sklearn.linear_model import Ridge # 嶺回歸 8 import matplotlib.pyplot as plt 9 import numpy as np 10 11 12 def show_res(y_true, y_predict): 13 """ 14 結果顯示 15 :param y_true: 真實房價 16 :param y_predict: 預測房價 17 :return: None 18 """ 19 # 1、創建畫布 20 21 plt.figure() 22 # 默認不支持中文 23 # 修改RC參數,來讓其支持中文 24 plt.rcParams['font.sans-serif'] = 'SimHei' 25 plt.rcParams['axes.unicode_minus'] = False 26 # 2、繪圖 27 x = np.arange(1, y_predict.shape[0] + 1) 28 # 真實值的走勢 29 plt.plot(x, y_true, marker="*", color="g", linestyle=":", markersize=4) 30 # 預測值的走勢 31 plt.plot(x, y_predict, marker="o", color="pink", markersize=4) 32 33 # 增加圖例 34 plt.legend(["真實房價", "預測房價"]) 35 # 增加標題 36 plt.title("波士頓房價真實與預測房價走勢圖") 37 38 # 保存圖片---如果在show之后保存圖片,那么圖片是完全空白的 39 plt.savefig("./波士頓房價真實與預測房價走勢圖.png") 40 # 3、展示 41 plt.show() 42 43 44 # 1、加載數據 45 boston_data = load_boston() 46 # print("boston_data:\n", boston_data) 47 48 # 2、獲取特征值、獲取目標值、獲取特征名稱 49 feature = boston_data["data"] 50 print("feature:\n", feature) 51 print("feature 的形狀:\n", feature.shape) 52 53 # 54 target = boston_data["target"] 55 print("target:\n", target) 56 print("target 的形狀:\n", target.shape) 57 58 # 59 feature_names = boston_data["feature_names"] 60 print("feature_names:\n", feature_names) 61 print("feature_names 的形狀:\n", feature_names.shape) 62 print("*" * 100) 63 64 # 3、可以將boston_data 保存到本地 65 # df.to_xxx pandas 中數據保存形式 66 # 將特征值轉化為df 67 # df_feature = pd.DataFrame(data=feature, columns=feature_names) 68 # print("df_feature:\n", df_feature) 69 # # 將目標值轉化為df 70 # df_target = pd.DataFrame(data=target, columns=["MEDV"]) 71 # print("df_target:\n", df_target) 72 # print("*" * 100) 73 # 74 # # 拼接特征值與目標值 75 # res_data = pd.concat((df_feature, df_target), axis=1) 76 # print("res_data:\n", res_data) 77 # 78 # # 保存數據 79 # res_data.to_excel("./boston_data.xlsx", index=False) 80 81 # 3、拆分數據集 82 # 之前 手動拆分 data 為完整數據集: data[:400,:] 訓練集 data[400:,:]測試集 83 # 拆分數據集 84 # 參數1 特征值 85 # 參數2 目標值 86 # 參數3 test_size ---測試集占比 87 # 特征值(訓練集的特征值、測試集的特征值) 目標值(訓練集的目標值、測試集的目標值) 88 # 隨機拆分---默認的 89 # random_state ---給定值,把數據集拆分固定 90 # 如果要進行超參數優化,數據集必須固定 91 # 訓練集:測試集 = 7:3 92 # 訓練集、驗證集、測試集 = 8:1:1 93 # 驗證集----驗證超參數 94 train_x, test_x, train_y, test_y = train_test_split(feature, target, test_size=0.3, random_state=1) 95 print("訓練集的特征值:\n", train_x) 96 print("訓練集的特征值:\n", train_x.shape) 97 print("訓練集的目標值:\n", train_y) 98 print("訓練集的目標值:\n", train_y.shape) 99 print("測試集的特征值:\n", test_x) 100 print("測試集的特征值:\n", test_x.shape) 101 print("測試集的目標值:\n", test_y) 102 print("測試集的目標值:\n", test_y.shape) 103 print("*" * 100) 104 105 # 檢測缺失值、處理缺失值 ---這個數據集無缺失值處理 106 # 處理異常值 ---這個數據集無異常值處理 107 # 標准化處理----法1 108 # # (1)實例化對象 109 stand = StandardScaler() 110 # # (2)標准化數據 111 # # 需要標准化哪些數據????--量級相差較大 112 # # 特征值需要標准化,目標值不需要標准化 113 # # 線性回歸求解---w,b 114 # # 特征值標准化,目標值不標准化,---w,b,如果得到新的標准化之后的特征值,代入模型,得到的預測值是真實的房價 115 # # fit_transform ---(x - x.mean() / x.std()) 116 # (1)計算自身的指標(2)進行轉化數據 117 train_x = stand.fit_transform(train_x) 118 test_x = stand.fit_transform(test_x) 119 120 print("標准化之后的數據:\n", train_x) 121 print("標准化之后的數據:\n", test_x) 122 123 # 標准化處理---法2 124 # (1)實例化對象 125 # stand = StandardScaler() 126 # # (2)標准化數據 127 # # 計算指標 128 # stand.fit(train_x) 129 # # 轉化 130 # train_x = stand.transform(train_x) 131 # # 利用訓練集的特征值的指標來轉化測試集的特征 132 # test_x = stand.transform(test_x) 133 134 135 # # 線性回歸算法進行房價預測 136 # # LinearRegression 基於正規方程的求解方式的線性回歸 137 # # 應用於數據較小,特征較少,模型構建不復雜的情況下 138 # (1)構建算法實例 139 lr = LinearRegression() 140 # (2)訓練數據 141 lr.fit(train_x, train_y) 142 # (3)預測數據 143 y_predict = lr.predict(test_x) 144 145 # 獲取准確率 146 score = lr.score(test_x, test_y) 147 148 # 獲取權重與偏置 149 weight = lr.coef_ 150 bias = lr.intercept_ 151 152 print("准確率為:\n", score) 153 print("權重為:\n", weight) 154 print("偏置為:\n", bias) 155 print("預測值:\n", y_predict) 156 157 # (1)構建算法實例 158 # 用於數據量較大、特征較多、模型較大的情況下 159 # 隨機梯度下降優化算法進行求解w,b 160 # 梯度方向---隨機的 161 # 學習率--- 162 # penalty= "l2" 正則化--L2正則化,alpha--正則化力度 163 # learning_rate = "invscaling" --默認學習率 164 # 想要更改學習率 165 # (1)將learning_rate ="constant",(2)再去更改eta0的值 166 # 更改的學習率:不能過大,可能會造成梯度爆炸現象--會出現NaN的結果, 167 # 也不能過小,會造成梯度消失,只訓練而損失與准確率不變的情況 168 # sgd = SGDRegressor() 169 # # (2)訓練數據 170 # sgd.fit(train_x, train_y) 171 # # (3)預測數據 172 # y_predict = sgd.predict(test_x) 173 # 174 # # 獲取准確率 175 # score = sgd.score(test_x, test_y) 176 # 177 # # 獲取權重與偏置 178 # weight = sgd.coef_ 179 # bias = sgd.intercept_ 180 # 181 # print("准確率為:\n", score) 182 # print("權重為:\n", weight) 183 # print("偏置為:\n", bias) 184 # print("預測值:\n", y_predict) 185 186 187 # (1)構建算法實例 188 # 線性回歸 + L2正則化 ---嶺回歸 189 # 數據量較小,特征較少、模型不復雜的情況,也可以使用嶺回歸 190 # rd = Ridge() 191 # # (2)訓練數據 192 # rd.fit(train_x, train_y) 193 # # (3)預測數據 194 # y_predict = rd.predict(test_x) 195 # 196 # # 獲取准確率 197 # score = rd.score(test_x, test_y) 198 # 199 # # 獲取權重與偏置 200 # weight = rd.coef_ 201 # bias = rd.intercept_ 202 # 203 # print("准確率為:\n", score) 204 # print("權重為:\n", weight) 205 # print("偏置為:\n", bias) 206 # print("預測值:\n", y_predict) 207 208 # 增加可視化---看真實值的走勢 與預測值之間走勢 209 show_res(test_y, y_predict)

