簡體   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