У меня проблема с отображением модели классификации текста на Tensorflow 1.12
.Я использую tf.estimator.inputs.pandas_input_fn
для чтения своих данных и tf.estimator.DNNClassifier
для обучения / оценки.Я тогда хотел бы служить моей модели.(Заранее извиняюсь, здесь трудно привести полный рабочий пример, но это очень похоже на пример, который TF дает на https://www.tensorflow.org/api_docs/python/tf/estimator/DNNClassifier)
В настоящее время я сохраняю свою модель с помощью ...
...
estimator.export_savedmodel("./TEST_SERVING/", self.serving_input_receiver_fn, strip_default_attrs=True)
...
def serving_input_receiver_fn(self):
"""An input receiver that expects a serialized tf.Example."""
# feature spec dictionary determines our input parameters for the model
feature_spec = {
'Headline': tf.VarLenFeature(dtype=tf.string),
'Description': tf.VarLenFeature(dtype=tf.string)
}
# the inputs will be initially fed as strings with data serialized by
# Google ProtoBuffers
serialized_tf_example = tf.placeholder(
dtype=tf.string, shape=None, name='input_example_tensor')
receiver_tensors = {'examples': serialized_tf_example}
# deserialize input
features = tf.parse_example(serialized_tf_example, feature_spec)
return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)
Это на самом деле не работает с ошибкой:
TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. Contents: SparseTensor(indices=Tensor("ParseExample/ParseExample:0", shape=(?, 2),
dtype=int64), values=Tensor("ParseExample/ParseExample:2", shape=(?,), dtype=string), dense_shape=Tensor("ParseExample/ParseExample:4", shape=(2,), dtype=int64)). Consider casting elements to a supported type.
Я пытался сохранить второй способ, делая:
def serving_input_receiver_fn(self):
"""Build the serving inputs."""
INPUT_COLUMNS = ["Headline","Description"]
inputs = {}
for feat in INPUT_COLUMNS:
inputs[feat] = tf.placeholder(shape=[None], dtype=tf.string, name=feat)
return tf.estimator.export.ServingInputReceiver(inputs, inputs)
Это на самом деле работает, пока япопробуйте проверить его с помощью saved_model_cli
.Некоторые выходные данные для saved_model_cli show --all --dir TEST_SERVING/1553879255/
:
MetaGraphDef with tag-set: 'serve' contains the following SignatureDefs:
signature_def['predict']:
The given SavedModel SignatureDef contains the following input(s):
inputs['Description'] tensor_info:
dtype: DT_STRING
shape: (-1)
name: Description:0
inputs['Headline'] tensor_info:
dtype: DT_STRING
shape: (-1)
name: Headline:0
The given SavedModel SignatureDef contains the following output(s):
outputs['class_ids'] tensor_info:
dtype: DT_INT64
shape: (-1, 1)
name: dnn/head/predictions/ExpandDims:0
outputs['classes'] tensor_info:
dtype: DT_STRING
shape: (-1, 1)
name: dnn/head/predictions/str_classes:0
outputs['logits'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 3)
name: dnn/logits/BiasAdd:0
outputs['probabilities'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 3)
name: dnn/head/predictions/probabilities:0
Method name is: tensorflow/serving/predict
Но теперь я не могу проверить это.
>>> saved_model_cli run --dir TEST_SERVING/1553879255/ --tag_set serve --signature_def predict --input_examples 'inputs=[{"Description":["What is going on"],"Headline":["Help me"]}]'
Traceback (most recent call last):
...
File "/Users/Josh/miniconda3/envs/python36/lib/python3.6/site-packages/tensorflow/python/tools/saved_model_cli.py", line 489, in _create_example_string
feature_list)
TypeError: 'What is going on' has type str, but expected one of: bytes
Хорошо, давайте превратим его в объект байтов, изменив на b["What is going on"]
и b["Help me"]
...
ValueError: Type <class 'bytes'> for value b'What is going on' is not supported for tf.train.Feature.
Есть идеи / мысли ??Спасибо!