决策树实战:california房价预测

Python3.7——决策树实战:california房价预测

网上有好多2.*版本的代码 但是本地安装的是python3.7版本,在学习中遇到很多问题,有很多地方和2.*版本的不一样,所以记录下来方便参考,侵权必删。

导入模块

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

加载数据

由于sklearn自带的数据集california_housing在后来的版本中去除了 需要自己手动下载数据集,而且数据格式也与之前不一致。
下载地址:链接:https://pan.baidu.com/s/1MED3CmImTSJcPK4lUWuMUQ
提取码:qtb2

house = np.loadtxt('cal_housing.data', delimiter=',')
house_feature_name=pd.read_csv('cal_housing.domain',sep=':',header = None)
house_feature_name=house_feature_name.values #DataFrame转化为数组

创建树模型

from sklearn import tree
dtr = tree.DecisionTreeRegressor(max_depth = 2)
#使用两列的特征进行训练 即传两个参数x, y
dtr.fit(house[:, [0, 1]], house[:,8])

要可视化显示 首先需要安装 graphviz

下载地址http://www.graphviz.org/download/
安装完成后需要配置环境变量

dot_data = \
    tree.export_graphviz(
        dtr,
        out_file = None,
        feature_names = house_feature_name[0:2,0],
        filled = True,
        impurity = False,
        rounded = True
    )

pip install pydotplus

import pydotplus
import os     
os.environ["PATH"] += os.pathsep + 'E:/python/Graphviz2.38/bin/'
graph = pydotplus.graph_from_dot_data(dot_data)
graph.get_nodes()[7].set_fillcolor("#FFF2DD")
graph.write_png("graph.png")
from IPython.display import Image
Image(graph.create_png())

在这里插入图片描述

保存到本地

graph.write_png('dtr_white_background.png')

将数据集进行划分,划分为训练集和测试集,并进行训练、验证

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = \
    train_test_split(house[:,0:8], house[:,8], test_size = 0.1, random_state = 42)
dtr = tree.DecisionTreeRegressor(random_state=42)
dtr.fit(x_train, y_train)
dtr.score(x_test, y_test) #评估

0.6361160159262982

使用随机森林

from sklearn.ensemble import RandomForestRegressor
rfr = RandomForestRegressor( random_state = 42)
rfr.fit(x_train, y_train)
rfr.score(x_test, y_test)

0.8105496535139884
很明显用随机森林得到的分数比单个树更高

用交叉验证选取参数

#用交叉验证选取参数
'''GridSearchCV(网络搜索交叉验证)用于系统地遍历模型的多种参数组合,通过交叉验证从而确定最佳参数,适用于小数据集。
常用属性
best_score_ :最佳模型下的分数
best_params_ :最佳模型参数
cv_results_ : 具体用法模型不同参数下交叉验证的结果
best_estimator_ : 最佳分类器之所以出现以上问题
'''

from sklearn.model_selection import  GridSearchCV

# 一般把参数写成字典的格式:
tree_param_grid = { 'min_samples_split': list((3, 6, 9)),'n_estimators': list((10,50,100))}

# 第一个参数是模型,第二个参数是待选的参数,cv:进行几次交叉验证
grid = GridSearchCV(RandomForestRegressor(), param_grid = tree_param_grid, cv = 5)
grid.fit(x_train, y_train)
grid.cv_results_, grid.best_params_, grid.best_score_

参考:https://blog.csdn.net/zhongguoxin12/article/details/84843397

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值