sklearn学习——决策树回归

sklearn学习——决策树回归

1 数据集采用

采用波士顿房价数据集,下载地址
使用sklearn.datasets.load_boston即可加载相关数据。该数据集是一个回归问题。每个类的观察值数量是均等的,共有 506 个观察,13 个输入变量和1个输出变量
在这里插入图片描述在这里插入图片描述

2 配置环境

conda install scilit-learn
conda install numpy
conda install matplotlib

3 代码

from sklearn.datasets import load_boston
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeRegressor
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt
import numpy as np


# boston = load_boston()
# print(boston.shape)
# print(boston.data.shape)
# print(boston.target)
# print(boston.feature_names)

# 1.读取数据集
path = 'boston.txt' # 填写自己的数据,注意应用逗号,txt文本,前面是特征,最后一列是标签
data = np.loadtxt(path, dtype=float, delimiter=',')#读取样本集
# print(data)

# 2.划分数据与标签
x, y = np.split(data, indices_or_sections=(13,), axis=1)  # x为数据特征,y为标签,indices_or_sections=(4,)填列数-1
train_data, test_data, train_label, test_label = \
    train_test_split(x, y, random_state=1, train_size=0.75, test_size=0.25)
print(train_data)   # 训练数据的
print(test_data)    # 测试数据


# 训练模型
clf = DecisionTreeRegressor(criterion='mse'#输入"mse"使用均方误差mean squared error(MSE),输入“friedman_mse”使用费尔德曼均方误差
                                  , random_state=30      # 控制随机数
                                  , splitter='random'    # 控制随机数
                                  , max_depth=3        # 树深度
                                #  , min_samples_leaf=10   #分的叶子样本最小10
                                #  , min_samples_split=10  #节点样本数最小10
                                #  , max_features=5   #选取特征最大数目5
                                  )
clf.fit(train_data, train_label)

# 4.计算回归模型的准确率
print("训练集:", clf.score(train_data, train_label))# 训练的准确率
print("测试集:", clf.score(test_data, test_label))  # 测试的准确率

# print('predict_data:\n', test_data)
print('predict_data:\n', test_label)  # 测试数据的原本值
print('predict_result:\n', clf.predict(train_data))  #通过模型预测的值

4 运行结果

准确度:

在这里插入图片描述

原本值:
在这里插入图片描述
模型预测值:
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值