現實世界的曲線關系都是通過增加多項式實現的,現在解決多項式回歸問題
住房價格樣本
樣本圖像
import matplotlib.font_manager as fm import matplotlib.pyplot as plt myfont = fm.FontProperties(fname='C:\Windows\Fonts\simsun.ttc') # plt.figure() # 實例化作圖變量 plt.title('房價面積價格樣本', fontproperties = myfont) # 圖像標題 plt.xlabel('面積(平方米)', fontproperties = myfont) # x軸文本 plt.ylabel('價格(萬元)', fontproperties = myfont) # y軸文本 # plt.axis([30, 400, 100, 400]) plt.grid(True) # 是否繪制網格線 X = [[50], [100], [150], [200], [250], [300]] y = [[150], [200], [250], [280], [310], [330]] X_test = [[250], [300]] # 用來做最終效果測試 y_test = [[310], [330]] # 用來做最終效果測試 # plt.plot(X, y, 'b.')#點 # plt.plot(X, y, 'b-')#線 plt.scatter(X, y, marker='*',color='blue',label='房價面積價格樣本') plt.show()
用線性回歸
添加以下代碼
model = LinearRegression() model.fit(X, y) print('一元線性回歸 r-squared', model.score(X_test, y_test)) X2 = [[30], [400]] y2 = model.predict(X2) plt.plot(X2, y2, 'g-') plt.show()
實際情況是,如果房屋面積一味的增加,房價並不會線性增長,因此線性關系已經無法描述真實的房價問題
采用多項式回歸
首先我們用二次多項式
# 實例化一個二次多項式特征實例 quadratic_featurizer = PolynomialFeatures(degree=2) # 用二次多項式對樣本X值做變換 X_train_quadratic = quadratic_featurizer.fit_transform(X) # 創建一個線性回歸實例 regressor_model = LinearRegression() # 以多項式變換后的x值為輸入,代入線性回歸模型做訓練 regressor_model.fit(X_train_quadratic, y) # 設計x軸一系列點作為畫圖的x點集 xx = np.linspace(30, 400, 100) # 把訓練好X值的多項式特征實例應用到一系列點上,形成矩陣 xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1)) yy_predict = regressor_model.predict(xx_quadratic) # 用訓練好的模型作圖 plt.plot(xx, yy_predict, 'r-') X_test_quadratic = quadratic_featurizer.transform(X_test) print('二次回歸 r-squared', regressor_model.score(X_test_quadratic, y_test)) # # plt.show() # 展示圖像
繼續三次回歸
cubic_featurizer = PolynomialFeatures(degree=3) X_train_cubic = cubic_featurizer.fit_transform(X) regressor_cubic = LinearRegression() regressor_cubic.fit(X_train_cubic, y) xx_cubic = cubic_featurizer.transform(xx.reshape(xx.shape[0], 1)) plt.plot(xx, regressor_cubic.predict(xx_cubic)) X_test_cubic = cubic_featurizer.transform(X_test) print('三次回歸 r-squared', regressor_cubic.score(X_test_cubic, y_test)) plt.show() # 展示圖像
可以看到三次回歸比二次回歸效果又好了一些,但是不是很明顯。所以二次回歸更可能是最適合的回歸模型,三次回歸可能有過擬合現象
參考:http://www.aboutyun.com/thread-19073-1-1.html