学习笔记:用回归树预测波士顿房价

代码如下:

# -*- coding: utf-8 -*-
"""
Created on Tue May 22 09:36:42 2018

@author: eagle
"""


# =============================================================================
# 回归树预测波士顿房价
# =============================================================================

from sklearn.datasets import load_boston
from sklearn.cross_validation import train_test_split
import numpy as np
from sklearn.preprocessing import StandardScaler

from sklearn.tree import DecisionTreeRegressor #回归树

from sklearn.metrics import r2_score,mean_squared_error,mean_absolute_error

#加载房价数据
boston = load_boston()      #共506条数据
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)
#print('The max target value is',np.max(boston.target)) #最大值
#print('The min target value is',np.min(boston.target)) #最小值
#print('The average target value is',np.mean(boston.target)) #平均值

#标准化
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.reshape(-1,1))
y_test = ss_y.transform(y_test.reshape(-1,1))

#回归树预测
dtr=DecisionTreeRegressor()
dtr.fit(X_train,y_train)
dtr_y_predict=dtr.predict(X_test)


#评价
#回归树
print('The scroe of uni_knr is:',dtr.score(X_test,y_test))
print('The r2-score of uni_knr is:',r2_score(y_test,dtr_y_predict))
print('The mean_squared_error of uni_knr is',mean_squared_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(dtr_y_predict)))
print('The mean_absolute_error of uni_knr is',mean_absolute_error(ss_y.inverse_transform(y_test),ss_y.inverse_transform(dtr_y_predict)))

但我发现,每运行一次评价的结果并不都一样,需要结合原理深入研究。

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