sklearn+python:線性迴歸案例
使用一階線性方程預測波士頓房價
載入的資料是隨sklearn一起釋出的,來自boston 1993年之前收集的506個房屋的資料和價格。load_boston()用於載入資料。
from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split import time from sklearn.linear_model import LinearRegression boston = load_boston() X = boston.data y = boston.target print("X.shape:{}. y.shape:{}".format(X.shape,y.shape)) print('boston.feature_name:{}'.format(boston.feature_names)) X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=3) model = LinearRegression() start = time.clock() model.fit(X_train,y_train) train_score = model.score(X_train,y_train) cv_score = model.score(X_test,y_test) print('time used:{0:.6f}; train_score:{1:.6f},sv_score:{2:.6f}'.format((time.clock()-start),train_score,cv_score))
輸出內容為:
X.shape:(506,13). y.shape:(506,) boston.feature_name:['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT'] time used:0.012403; train_score:0.723941,sv_score:0.794958
可以看到測試集上準確率並不高,應該是欠擬合。
使用多項式做線性迴歸
上面的例子是欠擬合的,說明模型太簡單,無法擬合數據的情況。現在增加模型複雜度,引入多項式。
打個比方,如果原來的特徵是[a,b]兩個特徵,
在degree為2的情況下, 多項式特徵變為[1,a,b,a^2,ab,b^2]。degree為其它值的情況依次類推。
多項式特徵相當於增加了資料和模型的複雜性,能夠更好的擬合。
下面的程式碼使用Pipeline把多項式特徵和線性迴歸特徵連起來,最終測試degree在1、2、3的情況下的得分。
from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split import time from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import Pipeline def polynomial_model(degree=1): polynomial_features = PolynomialFeatures(degree=degree,include_bias=False) linear_regression = LinearRegression(normalize=True) pipeline = Pipeline([('polynomial_features',polynomial_features),('linear_regression',linear_regression)]) return pipeline boston = load_boston() X = boston.data y = boston.target print("X.shape:{}. y.shape:{}".format(X.shape,random_state=3) for i in range(1,4): print( 'degree:{}'.format( i ) ) model = polynomial_model(degree=i) start = time.clock() model.fit(X_train,y_train) train_score = model.score(X_train,y_train) cv_score = model.score(X_test,y_test) print('time used:{0:.6f}; train_score:{1:.6f},cv_score))
輸出結果為:
X.shape:(506,) boston.feature_name:['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT'] degree:1 time used:0.003576; train_score:0.723941,sv_score:0.794958 degree:2 time used:0.030123; train_score:0.930547,sv_score:0.860465 degree:3 time used:0.137346; train_score:1.000000,sv_score:-104.429619
可以看到degree為1和上面不使用多項式是一樣的。degree為3在訓練集上的得分為1,在測試集上得分是負數,明顯過擬合了。
所以最終應該選擇degree為2的模型。
二階多項式比一階多項式好的多,但是測試集和訓練集上的得分仍有不少差距,這可能是資料不夠的原因,需要更多的訊據才能進一步提高模型的準確度。
正規方程解法和梯度下降的比較
除了梯度下降法來逼近最優解,也可以使用正規的方程解法直接計算出最終的解來。
根據吳恩達的課程,線性迴歸最優解為:
theta = (X^T * X)^-1 * X^T * y
其實兩種方法各有優缺點:
梯度下降法:
缺點:需要選擇學習率,需要多次迭代
優點:特徵值很多(1萬以上)時仍然能以不錯的速度工作
正規方程解法:
優點:不需要設定學習率,不需要多次迭代
缺點:需要計算X的轉置和逆,複雜度O3;特徵值很多(1萬以上)時特變慢
在分類等非線性計算中,正規方程解法並不適用,所以梯度下降法適用範圍更廣。
以上這篇sklearn+python:線性迴歸案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。