决策树的划分以及案例
决策树的划分依据之一 - 信息增益
特征 A 对训练数据集 D 的信息增益 g(D,A), 定义为集合 D 的信息熵 H(D)于特征 A 给定条件下 D 的信息条件熵 H(D|A)之差, 即公式为: (看不懂...)
g(D,A)=H(D)-H(D|A)
注: 信息增益表示得知特征 X 的信息而使得类 Y 的信息的不确定减少的程度.
sklearn 常见决策树使用的算法
- ID3
信息增益 最大的准则 - C4.5
信息增益比 最大的准则 - CART
回归树: 平方误差 最小
分类树: 基尼系数 最小的准则 在 sklearn 中可以选择划分的默认原则
决策树 API
代码
import pandas as pd
from sklearn.feature_extraction import DictVectorizer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier,export_graphviz
def tree():
"""
决策树 分类 坦泰尼克号生存
:return: None
"""
# 获取数据
# 处理数据,找出特征值和目标值
titan = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt")
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)
# 进行处理(特征工程)特征-》类别-》one_hot编码
dict = DictVectorizer(sparse=False)
# orient="records" 固定写法 将每一行样本转换成一个字典
x_train = dict.fit_transform(x_train.to_dict(orient="records"))
print(dict.get_feature_names())
x_test = dict.transform(x_test.to_dict(orient="records"))
print(x_train)
# 使用决策树进行预测
dec = DecisionTreeClassifier()
dec.fit(x_train,y_train)
print("预测的准确率为:",dec.score(x_test,y_test))
# 数据可视化
export_graphviz(dec,out_file="./tree.dot",feature_names=['年龄', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=女性', 'sex=男性'])
return None
if __name__ == "__main__":
tree()
运行结果
['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male']
[[31.19418104 0. 0. 1. 0. 1. ]
[31.19418104 0. 0. 1. 0. 1. ]
[22. 0. 0. 1. 0. 1. ]
...
[36. 1. 0. 0. 0. 1. ]
[31.19418104 0. 1. 0. 0. 1. ]
[31.19418104 0. 0. 1. 0. 1. ]]
预测的准确率为: 0.8115501519756839
决策树的结构, 本地保存
windows 版本下载地址:http://www.graphviz.org/download/
将 graphviz 安装目录下的 bin 文件夹添加到 Path 环境变量中;
执行
dot -Tpng tree.dot -o tree.png
评论已关闭