为了节省计算时间,很多时候数据都会直接被存储在磁盘上。在python中,需要使用python模块pickle序列化对象,序列化对象可以在磁盘上保存对象,并在需要的时候读取出来。例如,使用pickle模块存储决策树:
import pickle
#创建数据集
def createDataSet():
dataSet = [[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no']]
labels = ['no surfacing', 'flippers']
return dataSet, labels
#存储
def storeTree(inputTree, filename):
import pickle
fw = open(filename, 'wb') #以二进制读写方式打开文件
pickle.dump(inputTree, fw) #pickle.dump(对象, 文件,[使用协议])。序列化对象
# 将要持久化的数据“对象”,保存到“文件”中,使用有3种,索引0为ASCII,1是旧式2进制,2是新式2进制协议,不同之处在于后者更高效一些。
#默认的话dump方法使用0做协议
fw.close() #关闭文件
#读取
def grabTree(filename):
import pickle
fr = open(filename, 'rb')
return pickle.load(fr) #读取文件,反序列化
myDat, labels = createDataSet()
myTree = treePlotter.retrieveTree(0)
storeTree(myTree, 'classifierStorage.txt')
#生成的txt文件保存在当前的文件目录下
print(grabTree('classifierStorage.txt'))
Note :在python2中可以使用:
fw = open(filename, 'w')
fr = open(filename)
若在python3中使用,则会出现报错:
TypeError: write() argument must be str, not bytes
此时,需要使用’wb’二进制形式读取文件。若出现报错:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
则是没有使用’rb’二进制形式打开文件。