Tensorflow:服务模型始终返回相同的预测

4
我需要您的帮助,我现在遇到一点困难。
我重新训练了一个分类TensorFlow模型,效果相当不错。 现在我想通过TensorFlow Serving来提供服务。 我已经成功地提供了服务,但是当我使用它时,无论输入是什么,它总是给出相同的结果。
我认为我导出模型的方式有些问题,但我想不出来具体是什么。以下是我的代码。
有人能帮我吗?非常感谢大家!
这是将我的输入图像转换为可读对象以供tf使用的函数:
def read_tensor_from_image_file(file_name, input_height=299, input_width=299,
            input_mean=0, input_std=255):
  input_name = "file_reader"
  output_name = "normalized"
  file_reader = tf.read_file(file_name, input_name)
  if file_name.endswith(".png"):
    image_reader = tf.image.decode_png(file_reader, channels = 3,
                                   name='png_reader')
  elif file_name.endswith(".gif"):
image_reader = tf.squeeze(tf.image.decode_gif(file_reader,
                                              name='gif_reader'))
  elif file_name.endswith(".bmp"):
image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')
  else:
image_reader = tf.image.decode_jpeg(file_reader, channels = 3,
                                    name='jpeg_reader')
  float_caster = tf.cast(image_reader, tf.float32)
  dims_expander = tf.expand_dims(float_caster, 0);
  resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
  normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
  sess = tf.Session()
  result = sess.run(normalized)

  return result,normalized

这是我如何导出我的模型:

  # Getting graph from the saved pb file
  graph = tf.Graph()
  graph_def = tf.GraphDef()
  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())
  with graph.as_default():
    tf.import_graph_def(graph_def)

  # below, var "t" is the result of the transformation, "tf_input" a tensor before computation.
  t,predict_inputs_tensor = read_tensor_from_image_file(file_name,
                              input_height=input_height,
                              input_width=input_width,
                              input_mean=input_mean,
                              input_std=input_std)

  input_name = "import/" + input_layer
  output_name = "import/" + output_layer

  input_operation = graph.get_operation_by_name(input_name);
  output_operation = graph.get_operation_by_name(output_name);

  # Let's predict result to get an exemple output
  with tf.Session(graph=graph) as sess:
    results = sess.run(output_operation.outputs[0],
                  {input_operation.outputs[0]: t})
  results = np.squeeze(results)


  # Creating labels 
  class_descriptions = []
  labels = load_labels(label_file)
  for s in labels:
    class_descriptions.append(s)
  classes_output_tensor = tf.constant(class_descriptions)      
  table = 
 tf.contrib.lookup.index_to_string_table_from_tensor(classes_output_tensor)
 classes = table.lookup(tf.to_int64(labels))

  top_k = results.argsort()[-len(labels):][::-1]
  scores_output_tensor, indices =tf.nn.top_k(results, len(labels))

  # Display
  for i in top_k:
    print(labels[i], results[i])


  version=1
  path="/Users/dboudeau/depot/tensorflow-for-poets-2/tf_files"

  tf.app.flags.DEFINE_integer('version', version, 'version number of the model.')
  tf.app.flags.DEFINE_string('work_dir', path, 'your older model  directory.')
  tf.app.flags.DEFINE_string('model_dir', '/tmp/magic_model', 'saved model directory')
  FLAGS = tf.app.flags.FLAGS

  with tf.Session() as sess:
      classify_inputs_tensor_info = 
tf.saved_model.utils.build_tensor_info(predict_inputs_tensor)

  export_path = os.path.join(
      tf.compat.as_bytes(FLAGS.model_dir)
      ,tf.compat.as_bytes(str(FLAGS.version))
      )

  print(export_path)
  builder = tf.saved_model.builder.SavedModelBuilder(export_path)

  # define the signature def map here        

predict_inputs_tensor_info=tf.saved_model.utils.build_tensor_info(predict_inputs_tensor) classes_output_tensor_info=tf.saved_model.utils.build_tensor_info(classes_output_tensor) scores_output_tensor_info=tf.saved_model.utils.build_tensor_info(scores_output_tensor)

  classification_signature = (
    tf.saved_model.signature_def_utils.build_signature_def(
              inputs={
                  tf.saved_model.signature_constants.CLASSIFY_INPUTS:
                      classify_inputs_tensor_info
              },
              outputs={
                  tf.saved_model.signature_constants.CLASSIFY_OUTPUT_CLASSES:
                      classes_output_tensor_info,
                  tf.saved_model.signature_constants.CLASSIFY_OUTPUT_SCORES:
                      scores_output_tensor_info
              },
              method_name=tf.saved_model.signature_constants.
              CLASSIFY_METHOD_NAME))

  prediction_signature = (
          tf.saved_model.signature_def_utils.build_signature_def(
              inputs={'images': predict_inputs_tensor_info},
              outputs={
                  'classes': classes_output_tensor_info,
                  'scores': scores_output_tensor_info
              },

method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME
          ))

  legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')

  # This one does'
  final_sdn={

tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY:classification_signature

默认服务签名定义键:分类签名。
  builder.add_meta_graph_and_variables(
      sess, [tf.saved_model.tag_constants.SERVING],
      signature_def_map=final_sdn,
      legacy_init_op=legacy_init_op)

  builder.save()

我有完全相同的问题。你有进展了吗? - Ozum Safa
2个回答

5

我曾经也遇到同样的问题,为此苦战了一段时间。最后发现是我在模型中使用了 float32 类型,但是却发送了 Double 类型的数据。不知何故,tensorflow 把这个 double 类型的值转换成了 0 值。这意味着,无论你通过 RPC 发送什么数据,在模型中都会被认为是 0。希望这能有所帮助。


嗨,我进行了两个测试:首先我检查了RPC客户端部分,我创建了两个不同图像的proto。正如预期的那样,作为输入使用的proto是完全不同的。对我来说,这意味着发送到服务模型的输入是不同的。 第二个测试是检查传递给创建服务签名的张量信息。以下是我得到的值。我看不出你描述的错误可能发生在哪里?再次感谢@Ozum Safa的帮助 - Machin
`>>> predict_inputs_tensor_info name: "truediv:0" dtype: DT_FLOAT tensor_shape { dim { size: 1 } dim { size: 224 } dim { size: 224 } dim { size: 3 } }
classes_output_tensor_info name: "Const:0" dtype: DT_STRING tensor_shape { dim { size: 15 } }
scores_output_tensor_info name: "TopKV2:0" dtype: DT_FLOAT tensor_shape { dim { size: 15 } } `
- Machin

0
如果有人仍在寻找不同的答案,请查看此答案:
Tensorflow Serving on pretrained Keras ResNet50 model returning always same predictions
我也遇到了同样的问题,尝试了所有其他选项,例如检查预处理函数,将输入dtype从uint更改为float32/64。我以为这是由于辍学而发生的,但后来发现这是由于tensorflow的global_variables_initializer引起的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接