В настоящее время я работаю с Tenorflow Estimator API, и у меня возникли проблемы с запутанными вариантами обслуживания, которые доступны. Моя путаница возникает из-за очень подробной документации по тензорному потоку.
Это моя цель:
Используйте тензор потока-обслуживанияpretion_service_pb2, отправив сериализованное прото-сообщение в виде строки в функцию ServingInputReceiver моей экспортированной модели оценщика. Я ожидаю, что функция ServingInputReceiver получит сериализованную прототипную строку на тензоре «input», который затем десериализует ее до функций «ink» (= массив переменной длины поплавка) и «shape» (= fixedlength int64).
Это моя (реализация модели google quickdraw) Функция ввода:
def _parse_tfexample_fn(example_proto, mode):
"""Parse a single record which is expected to be a tensorflow.Example."""
feature_to_type = {
"ink": tf.VarLenFeature(dtype=tf.float32),
"shape": tf.FixedLenFeature([2], dtype=tf.int64)
}
if mode != tf.estimator.ModeKeys.PREDICT:
# The labels won't be available at inference time, so don't add them
# to the list of feature_columns to be read.
feature_to_type["class_index"] = tf.FixedLenFeature([1], dtype=tf.int64)
parsed_features = tf.parse_single_example(example_proto, feature_to_type)
parsed_features["ink"] = tf.sparse_tensor_to_dense(parsed_features["ink"])
if mode != tf.estimator.ModeKeys.PREDICT:
labels = parsed_features["class_index"]
return parsed_features, labels
else:
return parsed_features # In prediction, we have no labels
Это моя функция ввода обслуживания:
def serving_input_receiver_fn():
"""An input receiver that expects a serialized tf.Example."""
feature_to_type = {"ink": tf.VarLenFeature(dtype=tf.float32), "shape": tf.FixedLenFeature([2], dtype=tf.int64)}
serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input')
parsed_features = tf.parse_example(serialized_tf_example, feature_to_type)
parsed_features["ink"] = tf.sparse_tensor_to_dense(parsed_features["ink"])
return tf.estimator.export.ServingInputReceiver(parsed_features, serialized_tf_example)
Это мой запрос client.py:
features = {}
features["ink"] = tf.train.Feature(float_list=tf.train.FloatList(value=np_ink.flatten()))
features["shape"] = tf.train.Feature(int64_list=tf.train.Int64List(value=np_ink.shape))
f = tf.train.Features(feature=features)
data = tf.train.Example(features=f)
serialized=data.SerializeToString() # tensor to byte string
request.inputs['input'].ParseFromString(tf.contrib.util.make_tensor_proto(serialized, shape=[1], verify_shape=True))
И это ошибка, которую я получаю после вызова функции Predict в client.py
grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="input tensor alias not found in signature: ink. Inputs expected to be in the set {input}.")
Я попробовал следующие функции обслуживания:
ServingInputReceiver и build_raw_serving_input_receiver_fn дают мне ту же ошибку grpc. Когда я использую build_parsing_serving_input_receiver_fn , это даже не экспортирует мою модель. Я попытался обернуть голову вокруг документации, но она не очень полезна, и я не понимаю, когда использовать какую функцию ввода.