Completed
Push — master ( f056ac...c62777 )
by Dafne van
06:01
created

loadmodel()   A

Complexity

Conditions 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 4.5185

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 15
ccs 1
cts 7
cp 0.1429
crap 4.5185
rs 9.4285
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
14 1
def savemodel(model, filepath, modelname):
15
    """ Save model + weights + params TO json + npy + pkl file, respectively
16
    Input:
17
    - model (Keras object)
18
    - filepath: directory where the data will be stored
19
    - modelname: name of the model to be used in the filename
20
    """
21 1
    json_string = model.to_json()  # save architecture to json string
22 1
    with open(filepath + modelname + '_architecture.json', 'w') as outfile:
23 1
        json.dump(json_string, outfile, sort_keys=True, indent=4,
24
                  ensure_ascii=False)
25 1
    wweights = model.get_weights()  # get weight from model
26 1
    np.save(filepath + modelname + '_weights',
27
            wweights)  # save weights in npy file
28 1
    return None
29
30
31 1
def loadmodel(filepath, modelname):
32
    """ Load model + weights FROM json + npy file, respectively
33
    Input:
34
    - filepath: directory where the data will be stored
35
    - modelname: name of the model to be used in the filename
36
    """
37
    with open(filepath + modelname + '_architecture.json', 'r') as outfile:
38
        json_string_loaded = json.load(outfile)
39
    model_repro = model_from_json(json_string_loaded)
40
    # wweights2 = model_repro.get_weights()
41
    #  extracting the weights would give us the untrained/default weights
42
    wweights_recovered = np.load(
43
        filepath + modelname + '_weights.npy')  # load the original weights
44
    model_repro.set_weights(wweights_recovered)  # now set the weights
45
    return model_repro
46
47
# If we would use standard Keras function, which stores model and weights
48
# in HDF5 format it would look like code below. However, we did not use this
49
# because
50
# https://keras.io/getting-started/faq/#how-can-i-save-a-keras-model
51
# it is not compatible with default Keras version in python3.
52
# from keras.models import load_model
53
# import h5py
54
# modelh5=models[0]
55
# modelh5.save(resultpath+'mymodel.h5')
56
# del modelh5
57
# modelh5 = load_model(resultpath+'mymodel.h5')
58