定义两个函数,storeTree用于把决策树以二进制形式保存到文件中,grabTree从文件中读出决策树到内存

文件后缀名为.pkl

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pickle


def storeTree(inputTree, filename):
    """Serialize the decision tree and save it to a pickle file."""
    
    fw = open(filename,'wb')
    pickle.dump(inputTree,fw)
    fw.close()
 

def grabTree(filename):
    """Convert the decision tree file into memory."""
    
    fr = open(filename,'rb')
    return pickle.load(fr)

注:这里打开方式得写成'wb'和'rb',否则会出现异常。 

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐