1. 程式人生 > >自定義決策樹儲存——python pickle模組實現

自定義決策樹儲存——python pickle模組實現

定義兩個函式,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',否則會出現異常。