我正在嘗試保存我的模型,以便從 tf-serving 呼叫時輸出為:
{
"results": [
{ "label1": x.xxxxx, "label2": x.xxxxx },
{ "label1": x.xxxxx, "label2": x.xxxxx }
]
}
wherelabel1和label2是我的標簽,x.xxxxx是該標簽的概率。
這就是我正在嘗試的:
class TFModel(tf.Module):
def __init__(self, model: tf.keras.Model) -> None:
self.labels = ['label1', 'label2']
self.model = model
@tf.function(input_signature=[tf.TensorSpec(shape=(1, ), dtype=tf.string)])
def prediction(self, pagetext: str):
return
{ 'results': tf.constant([{k: v for dct in [{self.labels[c]: f"{x:.5f}"} for (c,x) in enumerate(results[i])] for k, v in dct.items()}
for i in range(len(results.numpy()))])}
# and then save it:
tf_model_wrapper = TFModel(classifier_model)
tf.saved_model.save(tf_model_wrapper.model,
saved_model_path,
signatures={'serving_default':tf_model_wrapper.prediction}
)
旁注:顯然,在 TensorFlow v2.0 中,如果signatures省略它應該首先掃描物件@tf.function(根據此:https ://www.tensorflow.org/api_docs/python/tf/saved_model/save )但實際上沒有似乎不起作用。相反,模型成功保存并且沒有錯誤并且@tf.function沒有呼叫,而是回傳默認輸出。
我從上面得到的錯誤是:
ValueError: Got a non-Tensor value <tf.Operation 'PartitionedCall' type=PartitionedCall> for key 'output_0' in the output of the function __inference_prediction_125493 used to generate the SavedModel signature 'serving_default'. Outputs for functions used as signatures must be a single Tensor, a sequence of Tensors, or a dictionary from string to Tensor.
由于這個錯誤,我將結果包裝在tf.constant上面,認為這可能是一個快速修復,但我認為這是我太天真并且沒有正確理解張量。
在得知 [所有輸出必須是回傳值] 之前,我嘗試了很多其他的東西。1
如何將輸出更改為我想要的?
uj5u.com熱心網友回復:
您可以將張量視為多維向量,即具有固定大小和維度并包含共享相同型別的元素的結構。您的回傳值是字串和字典串列之間的映射。字典串列不能轉換為張量,因為不能保證維數及其大小是恒定的,也不能保證每個元素共享相同的型別。
您可以改為回傳網路的原始輸出,它應該是一個張量,并在 tensorflow-serving 之外進行后期處理。
如果你真的想在你的問題中做類似的事情,你可以使用字串的張量,你可以使用這樣的代碼:
labels = tf.constant(['label1', 'label2'])
# if your batch size is dynamic, you can use tf.shape on your results variable to find it at runtime
batch_size = 32
# assuming your model returns something with the shape (N,2)
results = tf.random.uniform((batch_size,2))
res_as_str = tf.strings.as_string(results, precision=5)
return {
"results": tf.stack(
[tf.tile(labels[None, :], [batch_size, 1]), res_as_str], axis=-1
)
}
輸出將是一個字典,將值“結果”映射到維度的張量(Batch, number of labels, 2),最后一個維度包含標簽名稱及其對應的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/531228.html
