【发布时间】:2018-04-06 18:30:15
【问题描述】:
这是 .csv 文件的 link。这是一个经典的数据集,可以用来练习决策树!
import pandas as pd
import numpy as np
import scipy as sc
import scipy.stats
from math import log
import operator
df = pd.read_csv('tennis.csv')
target = df['play']
target.columns = ['play']
features_dataframe = df.loc[:, df.columns != 'play']
这是我头痛的开始
features_dataframe = pd.get_dummies(features_dataframe)
features_dataframe.columns
我正在对存储在features_dataframe 中的特征(数据)列执行一次热编码,这些列都是分类并打印,返回
Index(['windy', 'outlook_overcast', 'outlook_rainy', 'outlook_sunny',
'temp_cool', 'temp_hot', 'temp_mild', 'humidity_high',
'humidity_normal'],
dtype='object')
我明白为什么需要执行 one-hot 编码! sklearn 不适用于分类列。
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(target.values)
k = le.transform(target.values)
上面的代码将我存储在target 中的目标列转换为整数,因为 sklearn 不能处理类别(耶!)
现在最后,拟合 DecisionTreeClassifier,criterion = "entropy" 是我假设使用 ID3 的概念!
from sklearn import tree
from os import system
dtree = tree.DecisionTreeClassifier(criterion = "entropy")
dtree = dtree.fit(features_dataframe, k)
dotfile = open("id3.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = features_dataframe.columns)
dotfile.close()
文件id3.dot 有必要的代码,可以粘贴在site 上,将二合字母代码转换为适当的可理解的可视化!
为了方便您有效帮助我,我将id3.dot的代码贴在这里!
digraph Tree {
node [shape=box] ;
0 [label="outlook_overcast <= 0.5\nentropy = 0.94\nsamples = 14\nvalue = [5, 9]"] ;
1 [label="humidity_high <= 0.5\nentropy = 1.0\nsamples = 10\nvalue = [5, 5]"] ;
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
2 [label="windy <= 0.5\nentropy = 0.722\nsamples = 5\nvalue = [1, 4]"] ;
1 -> 2 ;
3 [label="entropy = 0.0\nsamples = 3\nvalue = [0, 3]"] ;
2 -> 3 ;
4 [label="outlook_rainy <= 0.5\nentropy = 1.0\nsamples = 2\nvalue = [1, 1]"] ;
2 -> 4 ;
5 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1]"] ;
4 -> 5 ;
6 [label="entropy = 0.0\nsamples = 1\nvalue = [1, 0]"] ;
4 -> 6 ;
7 [label="outlook_sunny <= 0.5\nentropy = 0.722\nsamples = 5\nvalue = [4, 1]"] ;
1 -> 7 ;
8 [label="windy <= 0.5\nentropy = 1.0\nsamples = 2\nvalue = [1, 1]"] ;
7 -> 8 ;
9 [label="entropy = 0.0\nsamples = 1\nvalue = [0, 1]"] ;
8 -> 9 ;
10 [label="entropy = 0.0\nsamples = 1\nvalue = [1, 0]"] ;
8 -> 10 ;
11 [label="entropy = 0.0\nsamples = 3\nvalue = [3, 0]"] ;
7 -> 11 ;
12 [label="entropy = 0.0\nsamples = 4\nvalue = [0, 4]"] ;
0 -> 12 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
}
转到here,并粘贴上面的有向图代码以获得所创建决策树的正确可视化!这里的问题是,对于更大的树和更大的数据集,将很难解释,因为一个热编码特征被显示为代表节点分裂的特征名称!
是否有解决方法,决策树可视化将显示合并的特征名称以表示从 one-hot-encoded 特征中拆分的节点?
我的意思是,有没有办法创建像 this 这样的决策树可视化
【问题讨论】:
-
我认为不在 scikit 中。您可以尝试其他可以按原样处理分类数据的库,例如 LightBGM,或 Weka 和 R 等工具。
标签: python scikit-learn graphviz decision-tree one-hot-encoding