繁体   English   中英

如何保存虚拟 tensorflow model 服务?

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

我想保存虚拟 tensorflow model 以便稍后在 tensorflow 服务中使用它。 我尝试使用以下代码片段准备这样的 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,
)

运行代码以保存 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'")

我应该怎么做才能保存带有签名的虚拟 model,以便稍后在 tensorflow 服务中使用它?

根据model.call 文档,您应该始终使用__call__

称呼

不应直接调用此方法。 它仅在子类化 tf.keras.Model 时被覆盖。 要在输入上调用 model,请始终使用__call__()方法,即model(inputs) ,它依赖于底层的call()方法。

然后,我不确定应该如何处理列表中的多个输入,所以我只使用 lambda:

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

当我更改签名使其匹配时,可以保存 model。 不知道 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,
)

加载后,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