Forums

saved tensorflow keras model wont work when loaded globally, but works loaded in a function

this doesn't work:

from tensorflow.keras.models import model_from_json
json_file = open('.../model.json', 'r')
loaded_model_json = json_file.read()
cnn_model = model_from_json(loaded_model_json)
cnn_model.load_weights("../model.h5")

def func():
     my_prediction = cnn_model(data)

but this does work:

from tensorflow.keras.models import model_from_json    
def func():
     json_file = open('.../model.json', 'r')
     loaded_model_json = json_file.read()
     cnn_model = model_from_json(loaded_model_json)
     cnn_model.load_weights("../model.h5")
     my_prediction = cnn_model(data)

I have other global variables that seem to work fine. I just don't want to load the model everytime the function is called. Any tips?

Thanks

What do you mean by "doesn't work"?