利用sklearn画出决策树并保存为PDF
下载Graphviz
python sklearn 决策树运用
数据形式(tree.csv)
利用sklearn画出决策树并保存为PDF 下载Graphviz进入官网下载并安装:
https://graphviz.gitlab.io/_pages/Download/Download_windows.html
并将下列路径配置为环境变量:
D:\software\Graphviz\bin
在cmd中测试:
dot -version
python代码
import numpy as np
import pandas as pd
from sklearn import tree
import graphviz
# x,y是sklearn中需要拟合的数据
x = np.array(exam_train)
y = np.array(classes_train)
clf = tree.DecisionTreeClassifier(criterion='entropy', class_weight='balanced', max_depth=25)
clf = clf.fit(x, y)
dot_data = tree.export_graphviz(clf, out_file=None, feature_names=None, filled=True, rounded=True) # 重要参数可定制
graph = graphviz.Source(dot_data)
graph.render(view=True, format="pdf", filename="decisiontree_pdf")
可以生成一张贼帅的决策树PDF:
python sklearn 决策树运用 数据形式(tree.csv)age look income orderly target
older ugly low yes no
young ugly high no no
young handsome low no no
young handsome high yes yes
young handsome medium yes yes
young handsome medium no no
python源代码:
# -*- coding:utf-8*-
# 将字典 转化为 sklearn 用的数据形式 数据型 矩阵
from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import preprocessing
from sklearn import tree
allElectronicsData = open('c:/pic/data/tree.csv','rb')
reader = csv.reader(allElectronicsData)
header = reader.next()
# print header
## 数据预处理
featureList = []
labelList = []
for row in reader:
# print row[-1]
labelList.append(row[-1])
# 下面这几步的目的是为了让特征值转化成一种字典的形式,就可以调用sk-learn里面的DictVectorizer,直接将特征的类别值转化成0,1值
rowDict = {}
for i in range(1, len(row) - 1):
rowDict[header[i]] = row[i]
featureList.append(rowDict)
for each in featureList:
print each
# Vectorize features
vec = DictVectorizer()
dummyX = vec.fit_transform(featureList).toarray()
print("dummyX:"+str(dummyX))
print(vec.get_feature_names())
# label的转化,直接用preprocessing的LabelBinarizer方法
lb = preprocessing.LabelBinarizer()
dummyY = lb.fit_transform(labelList)
print("dummyY:"+str(dummyY))
print("labelList:"+str(labelList))
#criterion是选择决策树节点的 标准 ,这里是按照“熵”为标准,即ID3算法;默认标准是gini index,即CART算法。
clf = tree.DecisionTreeClassifier()
clf = clf.fit(dummyX,dummyY)
print("clf:"+str(clf))
# 导入相关函数,可视化决策树
# 导出的结果是一个dot文件(在系统默认路劲),需要安装Graphviz才能将它住哪华为PDF或png格式
# 输出的dot文件可以使用graphvize软件转为PDF,graphvize安装目录中的bin目录放入到环境变量的Path中
# 使用如下命令
#cmd
# dot -Tpdf c:/tree.dot -o c:/tree.pdf
#下载地址:http://www.graphviz.org/Download_windows.php
#生成dot文件
with open("c:/tree.dot",'w') as f:
f = tree.export_graphviz(clf, feature_names= vec.get_feature_names(),out_file= f)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。