keras TF2如何删除SavedModel的自定义签名并重新导出模型

ht4b089n  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(139)

我目前有一个保存的模型,它使用自定义签名,但它需要有serving_default签名def,所以它应该看起来像这样:signature_def['serving_default'] .
如果我执行saved_model_cli show,则当前显示

signature_def['image_quality']:
  The given SavedModel SignatureDef contains the following input(s):
    inputs['input_image'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 224, 224, 3)
        name: input_1:0
  The given SavedModel SignatureDef contains the following output(s):
    outputs['quality_prediction'] tensor_info:
        dtype: DT_FLOAT
        shape: (-1, 10)
        name: dense_1/Softmax:0
  Method name is: tensorflow/serving/predict

有没有办法在tensorflow 2中删除自定义名称并重新导出模型,以获得serving_default签名?

qkf9rpyu

qkf9rpyu1#

您可以使用所需的签名创建新模型。
1.加载您的模型

M = tf.saved_model.load(export_dir='/path/to/saved/model')

1.使用所需的签名创建新模型

class MyModel(tf.Module):
  def __init__(self, M):
    self.model = M

  @tf.function(input_signature=[tf.TensorSpec([(None, 224, 224, 3)], tf.float32)])
  def fn(self, image):
    output = self.model.signatures['image_quality'](image)
    return {
        'quality_prediction': outputs['quality_prediction'],
    }
  

pruned = MyModel(M)
tf.saved_model.save(
  pruned,
  '/path/where/you/want/your/new/model',
  signatures = {'serving_default': pruned.fn},
  options=tf.saved_model.SaveOptions(experimental_custom_gradients=False),
)

1.测试以确保签名符合您的预期:

E = tf.saved_model.load(export_dir='/path/where/you/want/your/new/model')

fn = E.signatures['serving_default']

print ("Inputs:")
for x in fn.inputs:
  print("  ", x)
print ("Outputs:")
for k,v in fn.structured_outputs.items():
    print("  ", k, v)

相关问题