这是一个.csv文件的datasets/tennis.csv" rel="nofollow noreferrer">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']
这就是我头痛的地方
^{pr2}$我正在对存储在features_dataframe
中的feature(data)列执行一次热编码,这些列都是分类的并打印出来,返回
Index(['windy', 'outlook_overcast', 'outlook_rainy', 'outlook_sunny',
'temp_cool', 'temp_hot', 'temp_mild', 'humidity_high',
'humidity_normal'],
dtype='object')
我明白为什么需要执行一个热编码!sklearn无法处理分类列。在
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(target.values)
k = le.transform(target.values)
上面的代码将存储在target
中的目标列转换为integer,因为sklearn不能处理categories(YAY!)在
最后,对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,粘贴上面的有向图代码,以获得所创建的决策树的正确可视化效果!这里的问题是,对于更大的树和更大的数据集,它将很难解释,因为一个热编码的特征被显示为代表节点分割的特征名称!在
是否有一种解决方法,即决策树可视化将显示合并的特征名称,以表示从一个热编码特征中分离的节点?
我的意思是,有没有一种方法可以创建像this这样的决策树可视化
不使用一种热编码,而是为特定特性的类别使用任意整数代码,这可能更简单。在
您可以使用
pandas.factorize
对分类变量进行整型编码。在相关问题 更多 >
编程相关推荐