该程序分为三部分:
1、查看数据
2、通过数据样本的个别特征,搭建决策树,并 可使化
3、将数据分为训练集和测试集,搭建决策树和随机森林,并进行测试和评估!
#添加基本的库
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
加载数据
from sklearn.datasets.california_housing import fetch_california_housing
housing = fetch_california_housing()
print(housing.DESCR)
查看数据类型
housing.data.shape
housing.data[0]
建立决策树
from sklearn import tree
dtr = tree.DecisionTreeRegressor(max_depth = 2)
#创建深度为2的决策树
dtr.fit(housing.data[:, [6, 7]], housing.target)
#利用数据建模
#print(help(tree.export_graphviz))
#要可视化显示 首先需要安装 graphviz http://www.graphviz.org/Download..php
import pydotplus
dot_data = tree.export_graphviz(dtr,out_file =None,
feature_names = housing.feature_names[6:8],
filled = True,
impurity = False,
)
#pip install pydotplus
import pydotplus
graph = pydotplus.graph_from_dot_data(dot_data)
graph.get_nodes()[7].set_fillcolor("#FFF2DD")
from IPython.display import Image
Image(graph.create_png())
#交叉验证将数据集划分成训练集和测试集
from sklearn.model_selection import train_test_split
#交叉验证函数,划分训练集和测试集
data_train, data_test, target_train, target_test = \
train_test_split(housing.data, housing.target, test_size = 0.1, random_state = 42)
#搭建决策树
dtr = tree.DecisionTreeRegressor(random_state = 42)
dtr.fit(data_train, target_train)
#评估
dtr.score(data_test, target_test)
评估分类正确率为:
0.637355881715626
使用随机森林进行分类
先调试函数,选取合适的随机森林的参数
#使用交叉验证选取参数
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(data_train, target_train)
grid.best_params_, grid.best_score_
#,grid.cv_results_
运行结果为:
({‘min_samples_split’: 6, ‘n_estimators’: 100}, 0.8067555108702777)
将上述的结果中合适的参数,加入重新创建的随机森林函数中
#使用参数从新训练随机森林
rfr = RandomForestRegressor( min_samples_split=3,n_estimators = 100,random_state = 42)
rfr.fit(data_train, target_train)
rfr.score(data_test, target_test)
运行结果:
0.8088623476993486
相对于决策树,随机森林的分类的正确提告了将近20%。