1. 程式人生 > >python 保存對象文件

python 保存對象文件

session 好用 load range bsp protocol ESS toc 執行

之前用 R 語言一直感覺 .Rdata 格式的文件很好用,可以把每次執行的中間文件保存便於下次調用,剛熟悉 Python 還沒接觸這塊知識,所以有時候做項目不太順手,索性上網搜了下,整理如下:

模型存檔

#############
# joblib 庫
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
# 模型保存
lr_model = LogisticRegression()
joblib.dump(lr_model, ‘xx.model‘)
# 模型載入
lr_model = joblib.load(‘xx.model‘)


#############
# pickle 庫
# 模型保存
import pickle
with open(‘lr_model.pickle‘, ‘wb‘) as fp:
    pickle.dump(lr_model, fp)
# 模型載入
with open(‘lr_model.pickle‘, ‘rb‘) as fp:
    lr_model = pickle.load(fp) 

  

對象保存

#############
# pickle 庫
import pickle
x, y = 1, range(10)
with open(‘xx.pickle‘, ‘wb‘) as fp:
    # 通過傳遞protocol = -1到dump()來減少文件大小
    pickle.dump([x, y], fp)
# 對象載入
with open(‘xx.pickle‘, ‘rb‘) as fp:
    x, y = pickle.load(fp)
print(x)


#############
# _pickle 庫
# 對象保存
import  _pickle as cpickle
x, y = 1, range(10)
with open(‘xx.pickle‘, ‘wb‘) as fp:
    # 通過傳遞protocol = -1到dump()來減少文件大小
    cpickle.dump([x, y], fp)
# 對象載入
del x, y 
with open(‘xx.pickle‘, ‘rb‘) as fp:
    x, y = cpickle.load(fp)
print(x)


############
# dill 庫
import dill
# 文件保存
filename = ‘globalsave.pkl‘
dill.dump_session(filename)
# 文件載入
dill.load_session(filename)


############
# 其他庫如:pmml,shelve

  

  

python 保存對象文件