加载以前保存的没有自定义图层的模型时,缺少get_config [英] get_config missing while loading previously saved model without custom layers
问题描述
加载先前保存的模型时遇到问题.
I have a problem with loading the previously saved model.
这是我的保存:
def build_rnn_lstm_model(tokenizer, layers):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(len(tokenizer.word_index) + 1, layers,input_length=843),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(layers, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01), bias_regularizer=l2(0.01))),
tf.keras.layers.Dense(layers, activation='relu', kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01)),
tf.keras.layers.Dense(layers/2, activation='relu', kernel_regularizer=l2(0.01), bias_regularizer=l2(0.01)),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.summary()
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy',f1,precision, recall])
print("Layers: ", len(model.layers))
return model
model_path = str(Path(__file__).parents[2]) + os.path.sep + 'model'
data_train_sequence, data_test_sequence, labels_train, labels_test, tokenizer = get_training_test_data_local()
model = build_rnn_lstm_model(tokenizer, 32)
model.fit(data_train_sequence, labels_train, epochs=num_epochs, validation_data=(data_test_sequence, labels_test))
model.save(model_path + os.path.sep + 'auditor_model', save_format='tf')
此后,我可以看到 auditor_model
已保存在 model
目录中.
After this I can see that auditor_model
is saved in model
directory.
现在我想用以下方式加载该模型:
now I would like to load this model with:
model = tf.keras.models.load_model(model_path + os.path.sep + 'auditor_model')
但是我得到了
ValueError:无法恢复_tf_keras_metric类型的自定义对象现在.请确保该图层实现
get_config
并保存时from_config
.另外,请使用调用load_model()
时,custom_objects
arg.
ValueError: Unable to restore custom object of type _tf_keras_metric currently. Please make sure that the layer implements
get_config
andfrom_config
when saving. In addition, please use thecustom_objects
arg when callingload_model()
.
我已经在 TensorFlow
文档中阅读了有关 custom_objects
的信息,但是我不了解如何实现它,因为我没有使用自定义层,而是使用了预定义的层.
I have read about custom_objects
in TensorFlow
docs but I don't understand how to implement it while I use no custom layers but the predefined ones.
任何人都可以给我提示如何使其工作吗?我使用TensorFlow 2.2和Python3
Could anyone give me a hint how to make it work? I use TensorFlow 2.2 and Python3
推荐答案
您的示例缺少 f1
, precision
和 recall
的定义职能.如果内置指标例如'f1'
(请注意这是一个字符串)不适合您的用例,您可以按以下方式传递 custom_objects
:
Your example is missing the definition of f1
, precision
and recall
functions. If the builtin metrics e.g. 'f1'
(note it is a string) do not fit your usecase you can pass the custom_objects
as follows:
def f1(y_true, y_pred):
return 1
model = tf.keras.models.load_model(path_to_model, custom_objects={'f1':f1})
这篇关于加载以前保存的没有自定义图层的模型时,缺少get_config的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!