简体   繁体   English

如何保存虚拟 tensorflow model 服务?

[英]How to save dummy tensorflow model for serving?

I'd like to save dummy tensorflow model to use it later with tensorflow serving.我想保存虚拟 tensorflow model 以便稍后在 tensorflow 服务中使用它。 I've tried to prepare such model using following snippet:我尝试使用以下代码片段准备这样的 model:

import tensorflow as tf

input0 = tf.keras.Input(shape=[2], name="input_0", dtype="int32")
input1 = tf.keras.Input(shape=[2], name="input_1", dtype="int32")
output = tf.keras.layers.Add()([input0, input1])

model = tf.keras.Model(inputs=[input0, input1], outputs=output)

predict_function = tf.function(
    func=model.call,
    input_signature=[input0.type_spec, input1.type_spec],
)

signatures = {
    "predict": predict_function.get_concrete_function(
        [input0.get_shape(), input1.get_shape()],
    ),
}

model.save(
    filepath="some/dummy/path",
    signatures=signatures,
)

Running the code to save the model ends with following error:运行代码以保存 model 以以下错误结束:

AssertionError: Could not compute output KerasTensor(type_spec=TensorSpec(shape=(None, 2), dtype=tf.int32, name=None), name='add/add:0', description="created by layer 'add'")

What should I do to be able to save dummy model with signatures to use it later with tensorflow serving?我应该怎么做才能保存带有签名的虚拟 model,以便稍后在 tensorflow 服务中使用它?

According to the model.call documentation , you should always use __call__ :根据model.call 文档,您应该始终使用__call__

call称呼

This method should not be called directly.不应直接调用此方法。 It is only meant to be overridden when subclassing tf.keras.Model.它仅在子类化 tf.keras.Model 时被覆盖。 To call a model on an input, always use the __call__() method, ie model(inputs) , which relies on the underlying call() method.要在输入上调用 model,请始终使用__call__()方法,即model(inputs) ,它依赖于底层的call()方法。

Then, I am not sure how several inputs in a list should be handled, so I would just use a lambda:然后,我不确定应该如何处理列表中的多个输入,所以我只使用 lambda:

func = lambda x, y: model.__call__([x, y]),

When I changed the signatures such that they match, the model could be saved.当我更改签名使其匹配时,可以保存 model。 Don't know about tensorflow serving.不知道 tensorflow 服务。

import tensorflow as tf

input0 = tf.keras.Input(shape=[2], name="input_0", dtype="int32")
input1 = tf.keras.Input(shape=[2], name="input_1", dtype="int32")
output = tf.keras.layers.Add()([input0, input1])

model = tf.keras.Model(inputs=[input0, input1], outputs=output)

predict_function = tf.function(
    func = lambda x, y: model.__call__([x,y]),
    input_signature=[input0.type_spec, input1.type_spec],
)

signatures = {
    "predict": predict_function.get_concrete_function(
        input0.type_spec, input1.type_spec,
    ),
}

model.save(
    filepath="some/dummy/path",
    signatures=signatures,
)

After loading, the model seems to work correctly:加载后,model 似乎可以正常工作:

print(model([[5], [6]]))
tf.Tensor(11, shape=(), dtype=int32)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM