-
Notifications
You must be signed in to change notification settings - Fork 0
/
save-load_Model.py
67 lines (44 loc) · 1.52 KB
/
save-load_Model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
'''
Save and Load ML modules
A Script, to save model in specific file and load it later in order to make predictions.
Serialize ML algorithms and save serialized format to a file.
Load file to deserialize models and use it to make new pridictions.
- Pickle
- Joblib
'''
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
seed = 7
filename = 'pima-indians-diabetes.data.csv'
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] dataframe = read_csv(filename, names=names)
array = dataframe.values
X = array[:,0:8]
Y = array[:,8]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state = seed)
# fit the model
model = LogisticRegressino()
model.fit(X_train, Y_train)
''' 1. Pickle '''
from pickle import dump
from pickle import load
# Save the model to disk
filename = 'finalized_model.sav'
dump(model, open(filename, 'wb'))
# some time later...
# load the model from disk
loaded_model = load(open(filename, 'rb'))
result = loaded_model.score(X_test, Y_test)
print(result)
''' 2. Joblib '''
# Useful for some machine learning algorithms that require a lot of parameters or store entire dataset
from sklearn.externals.joblib import dump
from sklearn.externals.joblib import load
# save the model to disk
filename = 'finalized_model.sav'
dump(model, filenmae)
# some time later
# load the model from disk
loaded_model = load(filename)
result = loaded_model.score(X_test,Y_test)
print(result)