python sklearn 决策树模型
程序员文章站
2024-02-16 15:32:46
...
python sklearn 决策树模型
"""
决策树模型
相似的输入必会产生相似的输出
"""
import sklearn.datasets as sd
import sklearn.utils as su
import sklearn.tree as st
import sklearn.metrics as sm
# 加载数据集 波士顿房价
boston = sd.load_boston()
print(boston.data.shape)
print(boston.target.shape)
print(boston.feature_names)
print(boston.data[0])
print(boston.target[0])
# 打乱数据集 拆分 训练集、测试集
x, y = su.shuffle(boston.data, boston.target, random_state=7)
train_size = int(len(x) * 0.8)
train_x, train_y, test_x, test_y = \
x[:train_size], y[:train_size], x[train_size:], y[train_size:]
# 构建决策树模型 单颗树
model = st.DecisionTreeRegressor(max_depth=4)
model.fit(train_x, train_y)
prd_test_y = model.predict(test_x) # 预测
# 计算评估结果
print("R2得分:", sm.r2_score(test_y, prd_test_y))
print("平均绝对值误差:", sm.mean_absolute_error(test_y, prd_test_y))