第十章 决策树与随机森林
# 导入第三方模块
import pandas as pd
# 读入数据
Titanic = pd.read_csv(r'Titanic.csv')
Titanic.head()
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
# 删除无意义的变量,并检查剩余自字是否含有缺失值
Titanic.drop(['PassengerId','Name','Ticket','Cabin'], axis = 1, inplace = True)
Titanic.isnull().sum(axis = 0)
Survived 0
Pclass 0
Sex 0
Age 177
SibSp 0
Parch 0
Fare 0
Embarked 2
dtype: int64
# 对Sex分组,用各组乘客的平均年龄填充各组中的缺失年龄
fillna_Titanic = []
for i in Titanic.Sex.unique():update = Titanic.loc[Titanic.Sex == i,].fillna(value = {'Age': Titanic.Age[Titanic.Sex == i].mean()}, inplace = False)fillna_Titanic.append(update)
Titanic = pd.concat(fillna_Titanic)
# 使用Embarked变量的众数填充缺失值
Titanic.fillna(value = {'Embarked':Titanic.Embarked.mode()[0]}, inplace=True)
Titanic.head()
Survived | Pclass | Sex | Age | SibSp | Parch | Fare | Embarked | |
---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.000000 | 1 | 0 | 7.2500 | S |
4 | 0 | 3 | male | 35.000000 | 0 | 0 | 8.0500 | S |
5 | 0 | 3 | male | 30.726645 | 0 | 0 | 8.4583 | Q |
6 | 0 | 1 | male | 54.000000 | 0 | 0 | 51.8625 | S |
7 | 0 | 3 | male | 2.000000 | 3 | 1 | 21.0750 | S |
# 将数值型的Pclass转换为类别型,否则无法对其哑变量处理
Titanic.Pclass = Titanic.Pclass.astype('category')
# 哑变量处理
dummy = pd.get_dummies(Titanic[['Sex','Embarked','Pclass']])
# 水平合并Titanic数据集和哑变量的数据集
Titanic = pd.concat([Titanic,dummy], axis = 1)
# 删除原始的Sex、Embarked和Pclass变量
Titanic.drop(['Sex','Embarked','Pclass'], inplace=True, axis = 1)
Titanic.head()
Survived | Age | SibSp | Parch | Fare | Sex_female | Sex_male | Embarked_C | Embarked_Q | Embarked_S | Pclass_1 | Pclass_2 | Pclass_3 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 22.000000 | 1 | 0 | 7.2500 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 |
4 | 0 | 35.000000 | 0 | 0 | 8.0500 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 |
5 | 0 | 30.726645 | 0 | 0 | 8.4583 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 |
6 | 0 | 54.000000 | 0 | 0 | 51.8625 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0 |
7 | 0 | 2.000000 | 3 | 1 | 21.0750 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 |
# 导入第三方包
from sklearn import model_selection
# 取出所有自变量名称
predictors = Titanic.columns[1:]
# 将数据集拆分为训练集和测试集,且测试集的比例为25%
X_train, X_test, y_train, y_test = model_selection.train_test_split(Titanic[predictors], Titanic.Survived, test_size = 0.25, random_state = 1234)
# 导入第三方模块
from sklearn.model_selection import GridSearchCV
from sklearn import tree
# 预设各参数的不同选项值
max_depth = [2,3,4,5,6]
min_samples_split = [2,4,6,8]
min_samples_leaf = [2,4,8,10,12]
# 将各参数值以字典形式组织起来
parameters = {'max_depth':max_depth, 'min_samples_split':min_samples_split, 'min_samples_leaf':min_samples_leaf}
# 网格搜索法,测试不同的参数值
grid_dtcateg = GridSearchCV(estimator = tree.DecisionTreeClassifier(), param_grid = parameters, cv=10)
# 模型拟合
grid_dtcateg.fit(X_train, y_train)
# 返回最佳组合的参数值
grid_dtcateg.best_params_
{'max_depth': 3, 'min_samples_leaf': 4, 'min_samples_split': 2}
# 导入第三方模块
from sklearn import metrics
# 构建分类决策树
CART_Class = tree.DecisionTreeClassifier(max_depth=3, min_samples_leaf = 4, min_samples_split=2)
# 模型拟合
decision_tree = CART_Class.fit(X_train, y_train)
# 模型在测试集上的预测
pred = CART_Class.predict(X_test)
# 模型的准确率
print('模型在测试集的预测准确率:\n',metrics.accuracy_score(y_test, pred))
模型在测试集的预测准确率:0.8295964125560538
# 导入第三方包
import matplotlib.pyplot as plt
y_score = CART_Class.predict_proba(X_test)[:,1]
fpr,tpr,threshold = metrics.roc_curve(y_test, y_score)
# 计算AUC的值
roc_auc = metrics.auc(fpr,tpr)# 绘制面积图
plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')
# 添加边际线
plt.plot(fpr, tpr, color='black', lw = 1)
# 添加对角线
plt.plot([0,1],[0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)
# 添加x轴与y轴标签
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
# 显示图形
plt.show()
<Figure size 640x480 with 1 Axes>
# 需要在电脑中安装Graphviz
# https://graphviz.gitlab.io/_pages/Download/Download_windows.html
# 然后将解压文件中的bin设置到环境变量中
# 导入第三方模块
from sklearn.tree import export_graphviz
from IPython.display import Image
import pydotplus
from sklearn.externals.six import StringIO
# 绘制决策树
dot_data = StringIO()
export_graphviz(decision_tree,out_file=dot_data, feature_names=predictors,class_names=['Unsurvived','Survived'], # filled=True,rounded=True, special_characters=True
)
# 决策树展现
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
Image(graph.create_png())
---------------------------------------------------------------------------InvocationException Traceback (most recent call last)<ipython-input-10-35271d1803f9> in <module>()20 # 决策树展现21 graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
---> 22 Image(graph.create_png())~\Anaconda3\lib\site-packages\pydotplus\graphviz.py in <lambda>(f, prog)1795 self.__setattr__(1796 'create_' + frmt,
-> 1797 lambda f=frmt, prog=self.prog: self.create(format=f, prog=prog)1798 )1799 f = self.__dict__['create_' + frmt]~\Anaconda3\lib\site-packages\pydotplus\graphviz.py in create(self, prog, format)1958 if self.progs is None:1959 raise InvocationException(
-> 1960 'GraphViz\'s executables not found')1961 1962 if prog not in self.progs:InvocationException: GraphViz's executables not found
# 导入第三方包
from sklearn import ensemble
# 构建随机森林
RF_class = ensemble.RandomForestClassifier(n_estimators=200, random_state=1234)
# 随机森林的拟合
RF_class.fit(X_train, y_train)
# 模型在测试集上的预测
RFclass_pred = RF_class.predict(X_test)
# 模型的准确率
print('模型在测试集的预测准确率:\n',metrics.accuracy_score(y_test, RFclass_pred))
# 计算绘图数据
y_score = RF_class.predict_proba(X_test)[:,1]
fpr,tpr,threshold = metrics.roc_curve(y_test, y_score)
roc_auc = metrics.auc(fpr,tpr)
# 绘图
plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')
plt.plot(fpr, tpr, color='black', lw = 1)
plt.plot([0,1],[0,1], color = 'red', linestyle = '--')
plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
plt.show()
# 变量的重要性程度值
importance = RF_class.feature_importances_
# 构建含序列用于绘图
Impt_Series = pd.Series(importance, index = X_train.columns)
# 对序列排序绘图
Impt_Series.sort_values(ascending = True).plot('barh')
plt.show()
# 读入数据
NHANES = pd.read_excel(r'C:\Users\Administrator\Desktop\NHANES.xlsx')
NHANES.head()
print(NHANES.shape)
# 取出自变量名称
predictors = NHANES.columns[:-1]
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = model_selection.train_test_split(NHANES[predictors], NHANES.CKD_epi_eGFR, test_size = 0.25, random_state = 1234)
# 预设各参数的不同选项值
max_depth = [18,19,20,21,22]
min_samples_split = [2,4,6,8]
min_samples_leaf = [2,4,8]
parameters = {'max_depth':max_depth, 'min_samples_split':min_samples_split, 'min_samples_leaf':min_samples_leaf}
# 网格搜索法,测试不同的参数值
grid_dtreg = GridSearchCV(estimator = tree.DecisionTreeRegressor(), param_grid = parameters, cv=10)
# 模型拟合
grid_dtreg.fit(X_train, y_train)
# 返回最佳组合的参数值
grid_dtreg.best_params_
# 构建用于回归的决策树
CART_Reg = tree.DecisionTreeRegressor(max_depth = 20, min_samples_leaf = 2, min_samples_split = 4)
# 回归树拟合
CART_Reg.fit(X_train, y_train)
# 模型在测试集上的预测
pred = CART_Reg.predict(X_test)
# 计算衡量模型好坏的MSE值
metrics.mean_squared_error(y_test, pred)
# 构建用于回归的随机森林
RF = ensemble.RandomForestRegressor(n_estimators=200, random_state=1234)
# 随机森林拟合
RF.fit(X_train, y_train)
# 模型在测试集上的预测
RF_pred = RF.predict(X_test)
# 计算模型的MSE值
metrics.mean_squared_error(y_test, RF_pred)
# 构建变量重要性的序列
importance = pd.Series(RF.feature_importances_, index = X_train.columns)
# 排序并绘图
importance.sort_values().plot('barh')
plt.show()
第十章 决策树与随机森林相关推荐
- 使用泰坦尼克号数据进行决策树、随机森林
使用泰坦尼克号数据进行决策树.随机森林 决策树分类器 随机森林 决策树分类器 sklearn.tree.DecisionTreeClassifier(criterion='gini',max_dept ...
- 独家 | 决策树VS随机森林——应该使用哪种算法?(附代码链接)
作者:Abhishek Sharma 翻译:陈超 校对:丁楠雅 本文长度为4600字,建议阅读20分钟 本文以银行贷款数据为案例,对是否批准顾客贷款申请的决策过程进行了算法构建,并对比了决策树与随机森 ...
- ML之回归预测:利用十类机器学习算法(线性回归、kNN、SVM、决策树、随机森林、极端随机树、SGD、提升树、LightGBM、XGBoost)对波士顿数据集回归预测(模型评估、推理并导到csv)
ML之回归预测:利用十类机器学习算法(线性回归.kNN.SVM.决策树.随机森林.极端随机树.SGD.提升树.LightGBM.XGBoost)对波士顿数据集[13+1,506]回归预测(模型评估.推 ...
- 【机器学习基础】(五):通俗易懂决策树与随机森林及代码实践
与SVM一样,决策树是通用的机器学习算法.随机森林,顾名思义,将决策树分类器集成到一起就形成了更强大的机器学习算法.它们都是很基础但很强大的机器学习工具,虽然我们现在有更先进的算法工具来训练模型,但决 ...
- 决策树和随机森林(上)
决策树和随机森林 信息熵 熵 联合熵 条件熵 互信息 决策树学习算法 信息增益 ID3.C4.5.CART Bagging与随机森林 概念部分 思考:两点分布的信息熵 import numpy as ...
- 2.1.决策树和随机森林
2.1.决策树和随机森林 决策树(Decision Tree)是在已知各种情况发生概率的基础上,通过构成决策树来求取净现值的期望值大于等于零的概率,评价项目风险,判断其可行性的决策分析方法,是直观运用 ...
- 机器学习中的不平衡分类方法(part5)--决策树与随机森林
学习笔记吗,仅供参考,有错必纠 文章目录 决策树与随机森林 基本流程 决策树定义及结构 决策树学习步骤 划分选择 信息增益 增益率 基尼基数 剪枝处理 随机森林 决策树与随机森林 决策树(decisi ...
- python实现决策树算法sklearn_python sklearn-05:决策树及随机森林
1.决策树 2.随机森林 1.决策树(decision tree) 决策树一种简单的非线性模型,用来解决回归与分类问题. 通常是重复的将训练集解释变量分割成子集的过程.决策树的节点用方块表示,用来测试 ...
- 如何解读决策树和随机森林的内部工作机制?
随机森林在过去几年里得到了蓬勃的发展.它是一种非线性的基于树的模型,往往可以得到准确的结果.但是,随机森林的工作过程大都处于黑箱状态,往往难以解读和完全理解.近日,Pivotal Engineerin ...
最新文章
- 【Vue】Vue入门 -(本地篇+网络篇)代码示例及运行效果
- 谁能答对这道题?如有兴趣,请留下算法,呵呵~
- stylish和Tampermonkey样式及脚本
- rocketmq存储结构_rocketMq高性能存储设计
- mysql.exe跑满_解决并分析mysqld-nt.exe大量占用CPU问题
- vba mysql_VBA连接Mysql数据库
- android实现简单进度条ProgressBar
- 大一计算机引论知识点,计算机引论知识点2015精选.doc
- css磨砂效果背景和特殊背景
- Transformer-based模型的综述:AMMUS : A Survey of Transformer-based Pretrained Models in NLP
- cncert阅读报告
- kirin710f是什么处理器_hisiliconkirin710是什么处理器
- matlab关系矩阵布尔运算,[SketchUp]:布尔运算的运用,涨知识了
- 微信html5小游戏源码70种
- 游戏脚本开发思路总结
- 31岁了,阿里P6还有必要去吗?
- 访问者模式(Visitor模式)详解
- 【STM32】stm32独立看门狗(IWDG)
- 基于深度学习的轴承寿命预测实践,开发CNN、融合LSTM/GRU/ATTENTION
- PHP使用phpCAS对接CAS单点登陆系统