1
|
|
|
""" |
2
|
|
|
Summary: |
3
|
|
|
Functions to save and store a model. The current keras |
4
|
|
|
function to do this does not work in python3. Therefore, we |
5
|
|
|
implemented our own functions until the keras functionality has matured. |
6
|
|
|
Example function calls in 'Tutorial mcfly on PAMAP2.ipynb' |
7
|
|
|
""" |
8
|
1 |
|
from keras.models import model_from_json |
9
|
1 |
|
import json |
10
|
1 |
|
import pickle |
11
|
1 |
|
import numpy as np |
12
|
|
|
|
13
|
1 |
|
def savemodel(model,filepath,modelname): |
|
|
|
|
14
|
|
|
""" Save model + weights + params TO json + npy + pkl file, respectively |
15
|
|
|
Input: |
16
|
|
|
- model (Keras object) |
17
|
|
|
- filepath: directory where the data will be stored |
18
|
|
|
- modelname: name of the model to be used in the filename |
19
|
|
|
""" |
20
|
1 |
|
json_string = model.to_json() # save architecture to json string |
21
|
1 |
|
with open(filepath + modelname + '_architecture.json', 'w') as outfile: |
22
|
1 |
|
json.dump(json_string, outfile, sort_keys = True, indent = 4, ensure_ascii=False) |
|
|
|
|
23
|
1 |
|
wweights = model.get_weights() #get weight from model |
24
|
1 |
|
np.save(filepath+modelname+'_weights',wweights) #save weights in npy file |
|
|
|
|
25
|
1 |
|
return None |
26
|
|
|
|
27
|
1 |
|
def loadmodel(filepath,modelname): |
|
|
|
|
28
|
|
|
""" Load model + weights FROM json + npy file, respectively |
29
|
|
|
Input: |
30
|
|
|
- filepath: directory where the data will be stored |
31
|
|
|
- modelname: name of the model to be used in the filename |
32
|
|
|
""" |
33
|
|
|
with open(filepath + modelname + '_architecture.json', 'r') as outfile: |
34
|
|
|
json_string_loaded = json.load(outfile) |
|
|
|
|
35
|
|
|
model_repro = model_from_json(json_string_loaded) |
36
|
|
|
wweights2 = model_repro.get_weights() # extracting the weights would give us the untrained/default weights |
|
|
|
|
37
|
|
|
wweights_recovered =np.load(filepath+modelname+'_weights.npy') #load the original weights |
|
|
|
|
38
|
|
|
model_repro.set_weights(wweights_recovered) # now set the weights |
39
|
|
|
return model_repro |
40
|
|
|
|
41
|
|
|
# If we would use standard Keras function, which stores model and weights |
42
|
|
|
# in HDF5 format it would look like code below. However, we did not use this |
43
|
|
|
# because |
44
|
|
|
# https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model |
45
|
|
|
# it is not compatible with default Keras version in python3. |
46
|
|
|
# from keras.models import load_model |
47
|
|
|
# import h5py |
48
|
|
|
# modelh5=models[0] |
49
|
|
|
# modelh5.save(resultpath+'mymodel.h5') |
50
|
|
|
# del modelh5 |
51
|
|
|
# modelh5 = load_model(resultpath+'mymodel.h5') |
52
|
|
|
|