我有一个 Keras(顺序)模型,可以使用 Tensorflow 1.13 中的自定义签名定义进行保存,如下所示:
from tensorflow.saved_model.utils import build_tensor_info
from tensorflow.saved_model.signature_def_utils import predict_signature_def, build_signature_def
model = Sequential() // with some layers
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
score_signature = predict_signature_def(
inputs={'waveform': model.input},
outputs={'scores': model.output})
metadata = build_signature_def(
outputs={'other_variable': build_tensor_info(tf.constant(1234, dtype=tf.int64))})
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
builder.add_meta_graph_and_variables(
sess=sess,
tags=[tf.saved_model.tag_constants.SERVING],
signature_def_map={'score': score_signature, 'metadata': metadata})
builder.save()
将模型迁移到 TF2 keras 很酷:),但我不知道如何使用与上面相同的签名保存模型。我应该使用新的吗tf.saved_model.save()
or tf.keras.experimental.export_saved_model()
?上面的代码在TF2中应该怎么写呢?
关键要求:
- 该模型具有分数签名和元数据签名
- 元数据签名包含 1 个或多个常量
解决方案是创建一个tf.Module
每个签名定义都有函数:
class MyModule(tf.Module):
def __init__(self, model, other_variable):
self.model = model
self._other_variable = other_variable
@tf.function(input_signature=[tf.TensorSpec(shape=(None, None, 1), dtype=tf.float32)])
def score(self, waveform):
result = self.model(waveform)
return { "scores": results }
@tf.function(input_signature=[])
def metadata(self):
return { "other_variable": self._other_variable }
然后保存模块(不是模型):
module = MyModule(model, 1234)
tf.saved_model.save(module, export_path, signatures={ "score": module.score, "metadata": module.metadata })
在 TF2 上使用 Keras 模型进行测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)