def show(self): """Plot the tree using matplotlib """ if self._tree is None: raise RuntimeError("Estimator not fitted, call `fit` first") import tree_plotter tree_plotter.createPlot(self._tree)
import tree_plotter import matplotlib.patches as mpatch def retrieveTree(i): listOfTrees = [{'不浮出水面是否可以生存': {'不能生存': '非鱼类', '可以生存': {'是否有脚蹼': {'没有': '非鱼类', '有': '鱼类'}}}}, {'不浮出水面是否可以生存': {'不能生存': '非鱼类', '可以生存': {'是否有脚蹼': {'没有': {'是否有头': {'没有': '非鱼类', '有': '鱼类'}}, '有': '非鱼类'}}}}, {'是否有脚蹼': {'没有': '非鱼类', '有': {'不浮出水面是否可以生存': {'可以生存': '鱼类', '不能生存': '非鱼类'}}}}] return listOfTrees[i] if __name__ == '__main__': myTree = retrieveTree(1) tree_plotter.createPlot(myTree)
# -*- coding: utf-8 -*- ''' 作者: 李高俊 版本: 1.0 日期: 2018/11/22/ 项目名称: 预测隐形眼睛类型 ''' import numpy as np import decisiontree_practice as tree_pra import tree_plotter as tree_plt """ 步骤: 1. 收集数据:已有数据集lense.txt 2. 准备数据:解析数据集,将其转换为能被程序理解的数据 3. 分析数据:快速检查数据,看看有无错误数据,使用createplot()绘制树形图 4. 训练模型:creattree函数 5. 测试模型:编写测试函数判断函数验证决策树的正误 6. 使用模型:储存树的结构,以便下次使用 """ fr = open('lenses.txt') lenses = [inst.strip().split('\t') for inst in fr.readlines()] lensesLabels = ['age', 'prescript', 'astigmatic', 'tearRate'] lensesTree = tree_pra.creatTree(lenses, lensesLabels) tree_plt.createPlot(lensesTree)
import decision_tree import json import tree_plotter fr = open(r'/home/zhaoguanyi/PycharmProjects/Decision Tree/watermelon.txt') listWm = [inst.strip().split('\t') for inst in fr.readlines()] # 读取数据集 print(listWm) labels = ['色泽', '根蒂', '敲声', '纹理', '脐部', '触感'] # 标签 Trees = decision_tree.createTree(listWm, labels) # 构建决策树 print(json.dumps(Trees, ensure_ascii=False)) # 打印决策树 # 测试 labels = ['色泽', '根蒂', '敲声', '纹理', '脐部', '触感'] for i in range(17): testData = listWm[i][:6] print(testData) testClass = decision_tree.classify(Trees, labels, testData) # 测试 print(json.dumps(testClass, ensure_ascii=False)) tree_plotter.createPlot(Trees) # 可视化决策树
import trees_classifier,tree_plotter import pprint as pr dataFile = open('lenses.txt') l = dataFile.readlines() dataSet1 = [] labels1=[] for line in l: line = line.strip() line = line.split('\t') dataSet1.append(line[0:-1]) labels1.append(line[-1]) colNames1 = ['age','preScript','astigmatic?','Tear-Rate'] root=trees_classifier.createTree(dataSet1,labels1,colNames1) pr.pprint(root) tree_plotter.createPlot(root)
import my_decision_tree import tree_plotter from sklearn import tree if __name__ == '__main__': fr = open('lenses.txt') lenses = [inst.strip().split('\t') for inst in fr.readlines()] lenses_labels = ['age', 'prescript', 'astigmatic', 'tear_rate'] lenses_tree = my_decision_tree.createTree(lenses, lenses_labels) print(lenses_tree) tree_plotter.createPlot(lenses_tree) # d = {'tear_rate': {'reduced': 'no lenses', 'normal': {'astigmatic': {'no': {'age': {'pre': 'soft', 'young': 'soft', # 'presbyopic': {'prescript': {'hyper': 'soft', 'myope': 'no lenses'}}}}, 'yes': {'prescript': {'hyper': {'age': # {'pre': 'no lenses', 'young': 'hard', 'presbyopic': 'no lenses'}}, 'myope': 'hard'}}}}}} # num = tree_plotter.getNumLeafs(d) # print(num) # clf = tree.DecisionTreeClassifier() # lenses = clf.fit(lenses, lenses_labels)
header_, data_set_, = get_formatted_data(fname) # create decision tree from the data decision_tree = create_tree(data_set_, header_) print('Print Generated Decision Tree in dictionary mode:\n{}\n'.format( decision_tree)) # making prediction pred_header = [ 'Occupied', 'Price', 'Music', 'Location', 'VIP', 'Favorite Beer' ] pred_values = ['Moderate', 'Cheap', 'Loud', ' City-Center', ' No', 'No'] result = predict(pred_header, pred_values[:], decision_tree) print('Prediction mode\nFor params:{}\nResult :{}\n'.format( pred_values, result)) # print tree in plain text results = tree_plotter_linear(decision_tree) print('\nDecision tree in print mode:') for result in results: if result: # not print empty lines print(','.join(result)) # generate and show graph of the tree print( '\n\nGraph output: (note that matplotlib part of code was from third party)' ) import tree_plotter tree_plotter.createPlot(decision_tree)