1. 程式人生 > >使用三種不同的核函式(迴歸)對Boston房價進行預測,同時對測試資料做出預測

使用三種不同的核函式(迴歸)對Boston房價進行預測,同時對測試資料做出預測

from sklearn.datasets import load_boston
from sklearn.svm import SVR
from sklearn.cross_validation import train_test_split
from sklearn.metrics import r2_score,mean_squared_error,mean_absolute_error
from sklearn.preprocessing import StandardScaler
#匯入資料
boston = load_boston()
#檢視資料資訊
print(boston.DESCR)
X = boston.data
y = boston.target 
#對資料進行分割
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.25,random_state=33)
ss_X = StandardScaler()
ss_y =StandardScaler()
#分別對訓練和測試資料的特徵及目標值進行標準化處理
X_train = ss_X.fit_transform(X_train)
X_test = ss_X.transform(X_test)
y_train = ss_y.fit_transform(y_train)
y_test = ss_y.transform(y_test)
#使用三種不同的核函式配置的支援向量機迴歸模型進行訓練,並對測試資料進行預測
#1.採用線性核函式配置的支援向量機進行迴歸訓練
linear_svr =  SVR(kernel='linear')
linear_svr.fit(X_train,y_train)
linear_svr_predict = linear_svr.predict(X_test)
#2.使用多項式核函式配置的支援向量機進行訓練
poly_svr = SVR(kernel='poly')
poly_svr.fit(X_train,y_train)
poly_y_predict = poly_svr.predict(X_test)
#3.使用徑向基函式配置支援向量機進行訓練
rbf_svr = SVR(kernel='rbf')
rbf_svr.fit(X_train,y_train)
rbf_y_predict = rbf_svr.predict(X_test)


#輸出評估結果kernel = 'linear'
print('The value of default measurement of kernal=linear',linear_svr.score(X_test,y_test))
#使用r2__score模組,並輸出評估結果
print('The value of R-squared of kernal=linear is',r2_score(y_test,linear_svr_predict))
#使用mean_squared_error模組,輸出評估結果
print('The mean squared error of kernal=linear is',mean_squared_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(linear_svr_predict)))
#使用mean_absolute_error模組,輸出評估結果
print('The mean sbsolute error of kernal=linear is',mean_absolute_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(linear_svr_predict)))
print('\n'*2)
#輸出評估結果kernel = 'poly'
print('The value of default measurement of kernal=linear',poly_svr.score(X_test,y_test))
#使用r2__score模組,並輸出評估結果
print('The value of R-squared of kernal=linear is',r2_score(y_test,poly_y_predict))
#使用mean_squared_error模組,輸出評估結果
print('The mean squared error of kernal=linear is',mean_squared_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(poly_y_predict)))
#使用mean_absolute_error模組,輸出評估結果
print('The mean sbsolute error of kernal=linear is',mean_absolute_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(poly_y_predict)))
print('\n'*2)
#輸出評估結果kernel = 'rbf'
print('The value of default measurement of kernal=rbf',rbf_svr.score(X_test,y_test))
#使用r2__score模組,並輸出評估結果
print('The value of R-squared of kernal=rbf is',r2_score(y_test,rbf_y_predict))
#使用mean_squared_error模組,輸出評估結果
print('The mean squared error of kernal=rbf is',mean_squared_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(rbf_y_predict)))
#使用mean_absolute_error模組,輸出評估結果
print('The mean sbsolute error of kernal=rbf is',mean_absolute_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(rbf_y_predict)))