python实现决策树的保存和调用

总目录:Python数据分析整理

本文数据以及大部分代码来自《机器学习实战》

机器学习实战

决策树的保存和调用


决策树的保存和调用

前面讲到将训练的决策树绘制成简单易懂的图片,

trees.py下的代码

def classify(inputTree, featLabels, testVec):
    print(featLabels)
    firstStr = list(inputTree.keys())[0]
    secondDict = inputTree[firstStr]
    print(firstStr)
    print(featLabels)
    featIndex = featLabels.index(firstStr)
    key = testVec[featIndex]
    valueOfFeat = secondDict[key]
    if isinstance(valueOfFeat, dict):
        classLabel = classify(valueOfFeat, featLabels, testVec)
    else:
        classLabel = valueOfFeat
    return classLabel

def dumpTree(inputTree, filename):
    import pickle
    fw = open(filename, 'wb')
    pickle.dump(inputTree, fw)
    fw.close()

def loadTree(filename):
    import pickle
    fr = open(filename, 'rb')
    return pickle.load(fr)

测试代码如下:

import pandas as pd
import numpy as np
import trees
from math import log

data_file = pd.read_csv('file.txt', sep='\t')
data_file = data_file.iloc[:,1:]
a = data_file.values
b = a.tolist()

the_label1 = list(data_file.keys()[:-1])
the_label2 = list(data_file.keys()[:-1])

mytree = trees.createTree(b, the_label1)

trees.dumpTree(mytree, 'mytree')
new_trees = trees.loadTree('mytree')
print(new_trees)

dd = trees.classify(new_trees, the_label2, ['L1', 'R1'])
print(dd)

之前的数据集和模型的训练在上一张,不过有个问题,我也不知道the_label1为啥经过函数mytree = trees.createTree(b, the_label1)后值变了,我并没有重新赋值给the_label1啊,没有办法,只好新建了个变量the_label2解决问题。

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值