user3443033
user3443033

Reputation: 779

Sending keras model as an argument to external function in Python

I want to send the Keras model after training to another python function which is saved in another python file? How can I send the model as an argument? Thank you.

Upvotes: 1

Views: 1045

Answers (1)

0x0B1
0x0B1

Reputation: 330

If I understand it correctly, you want to transfer the model created in script A to script B so it can be used there.

To my experience, the easiest way of using a Keras model in a different script, is to save the model to disk as a file. As described here in the Keras docs:.

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

Passing on the model to a different Python file (i.e. via a commandline argument), can be then be done by passing the filename of where you saved that model to the second script. This script can then load the model from disk and use it.

In case you only have 1 model at a time, you could pick a filename and hardcode it into your functions. For example:

Script A

# assuming you already have a model stored in 'model'
model.save('my_stored_model.h5')

Script B (which accesses the saved model)

from keras.models import load_model

def function_a():
    model = load_model('my_stored_model.h5')
    return model.predict(...)

Upvotes: 1

Related Questions