python?sklearn?畫出決策樹并保存為PDF的實現(xiàn)過程
更新時間:2022年07月14日 15:11:41 作者:Dragon水魅
這篇文章主要介紹了python?sklearn?畫出決策樹并保存為PDF的實現(xiàn)過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
利用sklearn畫出決策樹并保存為PDF
下載Graphviz
進入官網下載并安裝:
https://graphviz.gitlab.io/_pages/Download/Download_windows.html
并將下列路徑配置為環(huán)境變量:
- 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中需要擬合的數(shù)據(jù) 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) # 重要參數(shù)可定制 graph = graphviz.Source(dot_data) graph.render(view=True, format="pdf", filename="decisiontree_pdf")
可以生成一張賊帥的決策樹PDF:

python sklearn 決策樹運用
數(shù)據(jù)形式(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 用的數(shù)據(jù)形式 數(shù)據(jù)型 矩陣
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
## 數(shù)據(jù)預處理
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是選擇決策樹節(jié)點的 標準 ,這里是按照“熵”為標準,即ID3算法;默認標準是gini index,即CART算法。
clf = tree.DecisionTreeClassifier()
clf = clf.fit(dummyX,dummyY)
print("clf:"+str(clf))
# 導入相關函數(shù),可視化決策樹
# 導出的結果是一個dot文件(在系統(tǒng)默認路勁),需要安裝Graphviz才能將它住哪華為PDF或png格式
# 輸出的dot文件可以使用graphvize軟件轉為PDF,graphvize安裝目錄中的bin目錄放入到環(huán)境變量的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)以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python?包(模塊?函數(shù)?類?定義?導入)使用詳解
這篇文章主要為大家介紹了python?包(模塊?函數(shù)?類?定義?導入)的使用詳細講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03
Python利用atexit模塊實現(xiàn)優(yōu)雅處理程序退出
Python的atexit模塊提供了一種方便的方式來注冊這些退出時執(zhí)行的函數(shù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-03-03

