python PICKEL:处理(保存,加载)Python对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python PICKEL:处理(保存,加载)Python对象相关的知识,希望对你有一定的参考价值。

import pickle

## dave
path_variable = os.path.join(folder_output,'variable.pckl')
f = open(path_variable, 'wb')
pickle.dump(variable, f)
f.close()

## load
f = open(path_variable, 'rb')
variable_new = pickle.load(f)
f.close()
# Save Model Using joblib
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib

url = "https://goo.gl/vhm1eU"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
joblib.dump(model, 'finalized_model.pkl') 

# some time later...

# load the model from disk
loaded_model = joblib.load('finalized_model.pkl')
result = loaded_model.score(X_test, Y_test)
print(result)
# Save Model Using Pickle
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import pickle
url = "https://goo.gl/vhm1eU"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = read_csv(url, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train, Y_train)
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

# some time later...

# load the model from disk
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)

以上是关于python PICKEL:处理(保存,加载)Python对象的主要内容,如果未能解决你的问题,请参考以下文章

Python序列化模块-Pickel写入和读取文件

json 和 pickel 详解

每小时使用批处理文件重新加载 python 脚本

在 Python 中保存和加载大型字典的最快方法

基本自定义检查 python 模块加载失败

Python基础(字符编码与文件处理)