使用三种不同的核函数(回归)对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)))

你可能感兴趣的:(机器学习)