Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow Keras load_model from Memory or Variable?

Tags:

Because tensorflow.keras.models.load_model input is path.

But I have to load it from file first, and decrypt it. then point to

load_model

if there have any idea to implementation it?

from tensorflow.keras.models import load_model
with open('mypath.h5'. mode='rb') as f:
    h5 = decrypt_func(f.read())

model = load_model(h5)

It works.

the solution is according to @jgorostegui

import tempfile
import h5py
from tensorflow.keras.models import load_model

temp = tempfile.TemporaryFile()
with open('mypath.h5'. mode='rb') as f:
    h5 = decrypt_func(f.read())
    temp.write(h5)
with h5py.File(temp, 'r') as h5file:
    model = load_model(h5file)
like image 788
Frank Liao Avatar asked Oct 07 '19 10:10

Frank Liao


1 Answers

Depending on the format that outputs the function decrypt_func it is possible to use h5py for loading the decriypted stream and then use the keras.models.load_model function to load the model, which supports h5py.File object type as input model apart from your mentioned string, path to the saved model.

with open('model.hdf5', 'rb') as f_hdl:
    h5 = decrypt_func(f_hdl.read())
    with h5py.File(h5, 'r') as h5_file:
        model = keras.models.load_model(h5_file)
like image 139
jgorostegui Avatar answered Nov 04 '22 18:11

jgorostegui