gpt4 book ai didi

python - Tensorflow 2.0 : How to change the output signature while using tf. 保存模型

转载 作者:行者123 更新时间:2023-12-01 04:56:06 26 4
gpt4 key购买 nike

我想更改保存的模型的输入和输出签名,我使用 tf.Module 对象来构建主模型的操作。

class Generator(tf.Module):
def __init__(....):
super(Generator, self).__init__(name=name)
...
with self.name_scope:
...
@tf.Module.with_name_scope
def __call__(self, input):
...

@tf.function
def serve_function(self, input):
out = self.__call__(input)
return out



call = model.Generator.serve_function.get_concrete_function(tf.TensorSpec([None, 256, 256, 3], tf.float32))
tf.saved_model.save(model.Generator, os.path.join(train_log_dir, 'frozen'))

然后我正在加载模型,但我有“default_serving”和“output_0”作为签名,我该如何更改?

最佳答案

我通过定义 tf.function 找到了一种无需使用 tf.Module 即可定义输出签名的方法。返回一个输出字典,其中字典中使用的键将是输出名称。

# Create the model
model = ...

# Train the model
model.fit(...)

# Define where to save the model
export_path = "..."

@tf.function()
def my_predict(my_prediction_inputs):
inputs = {
'my_serving_input': my_prediction_inputs,
}
prediction = model(inputs)
return {"my_prediction_outputs": prediction}

my_signatures = my_predict.get_concrete_function(
my_prediction_inputs=tf.TensorSpec([None,None], dtype=tf.dtypes.float32, name="my_prediction_inputs")
)

# Save the model.
tf.saved_model.save(
model,
export_dir=export_path,
signatures=my_signatures
)

这会产生以下签名:
signature_def['serving_default']:
The given SavedModel SignatureDef contains the following input(s):
inputs['my_prediction_inputs'] tensor_info:
dtype: DT_FLOAT
shape: (-1, -1)
name: serving_default_my_prediction_inputs:0
The given SavedModel SignatureDef contains the following output(s):
outputs['my_prediction_outputs'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 1)
name: StatefulPartitionedCall:0
Method name is: tensorflow/serving/predict

关于python - Tensorflow 2.0 : How to change the output signature while using tf. 保存模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59142040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com