将keras模型作为参数发送给Python中的外部函数

时间:2019-03-25 22:36:14

标签: python keras

我想在训练后将Keras模型发送到保存在另一个python文件中的另一个python函数?如何发送模型作为参数?谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您想将在脚本A中创建的模型转移到脚本B,以便可以在其中使用。

根据我的经验,在不同脚本中使用Keras模型的最简单方法是将模型作为文件保存到磁盘。 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')

然后可以通过将模型保存位置的文件名传递到第二个脚本来将模型传递到另一个Python文件(即通过命令行参数)。然后,该脚本可以从磁盘加载模型并使用它。

如果一次只具有1个模型,则可以选择一个文件名并将其硬编码到函数中。例如:

脚本A

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

脚本B(用于访问保存的模型)

from keras.models import load_model

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