sklearn内置加利福尼亚州房价数据集建立决策树并利用graphviz和pydotplus绘制树模型

#导入模块
import matplotlib.pyplot as plt

import pandas as pd

#导入sklearn内置的房价数据集
from sklearn.datasets.california_housing import fetch_california_housing
housing = fetch_california_housing()

#输出数据集描述信息
print(housing.DESCR)

#查看数据集形状   20640条数据,每条数据8个特征
# print(housing.data.shape)

#使用sklearn导入决策树模块
from sklearn import tree
#建立决策树对象   传入参数指定树的最大深度为2
dtr = tree.DecisionTreeRegressor(max_depth = 2)
#传入特征值和目标值,这里只使用第6和7个特征
dtr.fit(housing.data[:, [6, 7]], housing.target)

#要可视化显示 首先需要安装 graphviz   http://www.graphviz.org/Download..php
#创建dot对象
dot_data = \
    tree.export_graphviz(
        dtr,
        out_file = None,
        feature_names = housing.feature_names[6:8],
        filled = True,
        impurity = False,
        rounded = True
    )

#导入dot绘图包
import pydotplus

#创建绘图对象
graph = pydotplus.graph_from_dot_data(dot_data)

#绘制图像保存到本地
graph.write_png("./data/dtr_white_background.png")

绘制决策树为

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个基于Sklearn的diabetes数据集的回归模型建立教程。请按照以下步骤进行: 1. 导入必要的库和数据集: ```python import pandas as pd from sklearn.datasets import load_diabetes from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import train_test_split diabetes = load_diabetes() X = pd.DataFrame(diabetes.data, columns=diabetes.feature_names) y = diabetes.target ``` 2. 将数据集划分为训练集和测试集: ```python X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 3. 创建回归模型并拟合训练数据: ```python regressor = DecisionTreeRegressor(max_depth=3, random_state=42) regressor.fit(X_train, y_train) ``` 4. 在测试集上评估模型表现: ```python score = regressor.score(X_test, y_test) print(f"R-squared score: {score:.2f}") ``` 这里,我们使用了R-squared得分来评估模型的表现。您可以根据需要使用其他评估指标。 5. 如果需要,您可以使用Graphviz库来可视化回归: ```python from sklearn.tree import export_graphviz import graphviz dot_data = export_graphviz(regressor, out_file=None, feature_names=diabetes.feature_names, filled=True, rounded=True, special_characters=True) graph = graphviz.Source(dot_data) graph.render("diabetes_regression_tree") graph ``` 这将生成一个名为"diabetes_regression_tree.pdf"的PDF文件,其中包含回归的可视化图。 希望这个教程对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值