如何保存和加载自定义 siamese bert 模型

how to save and load custom siamese bert model

我正在学习如何训练 siamese bert 网络的教程:

https://keras.io/examples/nlp/semantic_similarity_with_bert/

一切都很好,但我不确定在训练并保存模型后保存模型的最佳方法是什么。 有什么建议吗?

我正在尝试

model.save('models/bert_siamese_v1')

这会创建一个包含 save_model.bp keras_metadata.bp 和两个子文件夹(变量和资产)的文件夹

然后我尝试加载它:

model.load_weights('models/bert_siamese_v1/')

它给了我这个错误:

2022-03-08 14:11:52.567762: W tensorflow/core/util/tensor_slice_reader.cc:95] Could not open models/bert_siamese_v1/: Failed precondition: models/bert_siamese_v1; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator?

最好的方法是什么?

尝试使用 tf.saved_model.save 保存您的模型:

tf.saved_model.save(model, 'models/bert_siamese_v1')
model = tf.saved_model.load('models/bert_siamese_v1')

您在保存过程中收到的警告可以apparently忽略。加载模型后,您可以使用它进行推理 f(test_data):

f = model.signatures["serving_default"]
x1 = tf.random.uniform((1, 128), maxval=100, dtype=tf.int32)
x2 = tf.random.uniform((1, 128), maxval=100, dtype=tf.int32)
x3 = tf.random.uniform((1, 128), maxval=100, dtype=tf.int32)
print(f)
print(f(attention_masks = x1, input_ids = x2, token_type_ids = x3))
ConcreteFunction signature_wrapper(*, token_type_ids, attention_masks, input_ids)
  Args:
    attention_masks: int32 Tensor, shape=(None, 128)
    input_ids: int32 Tensor, shape=(None, 128)
    token_type_ids: int32 Tensor, shape=(None, 128)
  Returns:
    {'dense': <1>}
      <1>: float32 Tensor, shape=(None, 3)
{'dense': <tf.Tensor: shape=(1, 3), dtype=float32, numpy=array([[0.40711606, 0.13456087, 0.45832306]], dtype=float32)>}

看来你有两个选择

 model.save_weights('./checkpoints/my_checkpoint')
   
 model = create_model()
   
 model.load_weights('./checkpoints/my_checkpoint') 

调用 model.save 以在单个 file/folder 中保存模型的架构、权重和训练配置。这允许您导出模型,以便在不访问原始 Python 代码* 的情况下使用它。由于 optimizer-state 已恢复,您可以从中断的地方继续训练。

保存模型

# Create and train a new model instance.
model = create_model()
model.fit(train_images, train_labels, epochs=5)

# Save the entire model as a SavedModel.
!mkdir -p saved_model
model.save('saved_model/my_model')

加载模型

new_model = tf.keras.models.load_model('saved_model/my_model')

您似乎混合了两种方法,保存模型和加载权重。