赞
踩
1. 决策树
决策树就像程序的if-else结构,是用于分割数据的一种分类方法。
from sklearn.tree import DecisionTreeClassifier
对于复杂的预测问题,通过建立树模型产生分支节点,被划分成两个二叉树或多个多叉树较为简单的子集,从结构上划分为不同的子问题。将依规则分割数据集的过程不断递归下去。随着树的深度不断增加,分支节点的子集越来越小,所需要提的问题数也逐渐简化。当分支节点的深度或者问题的简单程度满足一定的停止规则时, 该分支节点会停止分裂,得到最终需要的数据。
决策树算法采用树形结构,使用层层推理来实现最终的分类。决策树由下面3种元素构成:
根节点:包含样本的全集。
内部节点:对应特征属性测试。
叶节点:代表决策的结果。
信息熵:信源的不确定度。信息是用来消除不确定性的。
H为信息熵,单位为比特;P(x)为x的概率。
信息增益:当得知一个特征条件之后,减少的信息熵的大小。
特征A对训练数据集D的信息增益为集合D的信息熵与D在特征A已经给定时的信息条件熵之差:
DecisionTreeClassifier(criterion=’gini’, max_depth=None,random_state=None)
参数:
criterion:默认是基尼系数(gini),也可以选择信息增益的熵(entropy)。
max_depth:树的深度大小
random_state:随机数种子
返回值:决策树对象,方法decision_path返回路径
例1:泰坦尼克号
需求:用泰坦尼克号上乘客信息描述,预测泰坦尼克号上的别乘客的生存状态。
链接:https://pan.baidu.com/s/1dxhPKt2hAVXOfu-eLmPm7w
提取码:a09l
- import pandas as pd
- from sklearn.feature_extraction import DictVectorizer
- from sklearn.model_selection import train_test_split
- from sklearn.tree import DecisionTreeClassifier
-
- titan = pd.read_csv("titanic.csv")
- # 处理数据,找出特征值和目标值
- x = titan[['pclass', 'age', 'sex']]
- y = titan['survived']
- # 缺失值处理
- x['age'].fillna(x['age'].mean(), inplace=True)
- # 分割数据集到训练集合测试集
- x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
- # 特征工程
- dict = DictVectorizer(sparse=False)
- x_train = dict.fit_transform(x_train.to_dict(orient="records"))
- x_test = dict.transform(x_test.to_dict(orient="records"))
- # 用决策树进行预测
- dec = DecisionTreeClassifier()
- dec.fit(x_train, y_train)
- # 预测准确率
- print("预测的准确率:", dec.score(x_test, y_test))

输出:
预测的准确率: 0.8145896656534954
决策树的保存
sklearn.tree.export_graphviz() 该函数能够导出.dot格式
export_graphviz(estimator, out_file='tree.dot', feature_names=dict.get_feature_names())
使用graphviz工具能够将dot文件转换为png或pdf等格式。
决策树的优点: 理解较为简单,输出的树木可以可视化; 需要很少的数据准备(比如说不需要数据归一化)。
决策树的缺点: 可能会生成过于复杂的树,形成过拟合,减少分类的准确程度; 只有较少不同的数据信息可能会生成完全不同的树,因此决策树可能不稳定。
2. 随机森林
随机森林是由很多决策树构成的,不同决策树之间没有关联。 进行分类任务时,森林中的每一棵决策树分别进行判断和分类,每个决策树得到一个自己的分类结果,决策树的分类结果中分类最多的那个结果会被随机森林当成最终的结果。
from sklearn.ensemble import RandomForestClassifier
RandomForestClassifier(n_estimators=10, criterion=’gini’, max_depth=None, bootstrap=True, random_state=None)
参数:
n_estimators:integer,optional(default = 10) 森林里的树木数量
criteria:string,可选(default =“gini”)分割特征的测量方法
max_depth:integer或None,可选(默认=无)树的最大深度
bootstrap:boolean,optional(default = True)是否在构建树时使用放回抽样
例2:用随机森林计算上面的泰坦尼克号案例
- import pandas as pd
- from sklearn.ensemble import RandomForestClassifier
- from sklearn.feature_extraction import DictVectorizer
- from sklearn.model_selection import train_test_split, GridSearchCV
-
- titan = pd.read_csv("titanic.csv")
- # 处理数据,找出特征值和目标值
- x = titan[['pclass', 'age', 'sex']]
- y = titan['survived']
- # 缺失值处理
- x['age'].fillna(x['age'].mean(), inplace=True)
- # 分割数据集到训练集合测试集
- x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
- # 特征工程
- dict = DictVectorizer(sparse=False)
- x_train = dict.fit_transform(x_train.to_dict(orient="records"))
- x_test = dict.transform(x_test.to_dict(orient="records"))
- # 随机森林进行预测 (超参数调优)
- rf = RandomForestClassifier()
- param = {"n_estimators": [120, 200, 300, 500, 800, 1200], "max_depth": [5, 8, 15, 25, 30]}
- # 网格搜索与交叉验证
- gc = GridSearchCV(rf, param_grid=param, cv=2)
- gc.fit(x_train, y_train)
- print("准确率:", gc.score(x_test, y_test))
- print("查看选择的参数模型:", gc.best_params_)

输出:
准确率: 0.8419452887537994
查看选择的参数模型: {'max_depth': 5, 'n_estimators': 120}
随机森林的优点:可以出来高维度的数据,并且不用降维,无需做特征选择;可以判断特征的重要程度;可以判断出不同特征之间的相互影响;不容易过拟合;对于不平衡的数据集来说,它可以平衡误差。
随机森林的缺点:对于有不同取值的属性的数据,取值划分较多的属性会对随机森林产生更大的影响,所以随机森林在这种数据上产出的属性权值是不可信的。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。