决策树回归器模型API:
import sklearn.tree as st
#创建决策树回归模型, 决策树最大深度为4
model=st.DecisionTreeClassifier(max_depth=4)
#训练模型
# train_x:二维数组样本数据
# train_y:训练集中对应每行样本的结果
model.fit(train_x,train_y)
#预测模型
pred_test_y=model.predict(test_x)
预测房价:
import sklearn.datasets as sd
import sklearn.utils as su
import sklearn.tree as st
import sklearn.metrics as sm
import numpy as np
boston=sd.load_boston()
#拆分训练集与测试集
x,y=su.shuffle(
boston.data,boston.target,random_state=7)
train_size=int(len(x)*0.8)
train_x,test_x,train_y,test_y=x[:train_size],x[train_size:],y[:train_size],y[train_size:]
#构建决策树模型
model=st.DecisionTreeRegressor(max_depth=4)
model.fit(train_x,train_y)
pred_test_y=model.predict(test_x)
#评估结果
r=sm.r2_score(test_y,pred_test_y)
print(r)