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

2024-01-10

我需要你的帮助,我现在有点陷入困境。

我重新训练了一个分类张量流模型,它给出了非常好的结果。 现在我想通过张量流服务来服务它。 我设法提供了它,但是当我使用它时,无论输入是什么,它总是给我相同的结果。

我认为导出模型的方式有问题,但我不知道是什么。下面是我的代码。

有人可以帮助我吗?非常感谢大家

这是将我的输入图像转换为 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()

我也遇到过同样的问题,我已经与之斗争了一段时间了。最后事实证明,我在模型中发送了 float32 的 Double 类型,并且不知何故,tensowflow 将这个 double 转换为 0 值。这意味着,无论您通过 RPC 发送什么,在模型中都将被视为 0。希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • 仅合并 R 中不同数据帧中的一列或两列

    我有两组数据框 下面是每行的前五行 First Data frame Name sampel sort name id supplier usage ABC 10000079 811121 1 DEF 10000182 541513 4 S
  • 难以捕获执行就地状态更新的子流程的输出

    所以我试图将 HandBrakeCLI 的输出捕获为 Python 子进程 这对于 stderr 来说不是问题 因为每次更新都会在类似文件的管道中创建一个新行 但是 使用标准输出 HandBrakeCLI 会进行就地更新 但我很难捕获它们
  • 如何在查询字符串中使用回车或换行?

    客户可以在文本区域中输入行 并将其保存在数据库中 如果客户返回站点 他可以加载之前输入的数据 但是 换行符和回车符不会显示在文本区域中 我可以将它们放在查询字符串中 例如通过 ASCII 编码 A 或 D 但 java 不喜欢这样并抛出 I
  • Swift 中块参数的文档标记格式是什么?

    如果您添加文档标记 则 Swift 中块的参数会显示该块的参数表 但我不知道如何填写该表 我已经在Xcode 标记参考格式 https developer apple com library ios documentation Xcode
  • 更改 Mac Catalyst 上 UITextField 或 UITextView 的提示颜色

    如何以编程方式更改 mac Catalyst 上 UITextField 提示的颜色 提示存在 但颜色与 UITextField 相同 提示在 iOS 上显示正确的颜色 我尝试失败 tintColor 代码 iOS 和 Mac Cataly
  • firebase的app token在什么时期发生变化以及如何管理?

    我是 firebase 的新手 我就像一个小孩学走路一样学习它 到目前为止 我已经成功使用 firebase 框架为我的手机生成的令牌向我自己的手机发送消息 现在这就是棘手的地方 在我看来 有一种方法叫做onTokenRefresh in
  • AWS Dynamo 不会自动缩小规模

    Here are the parameters I have set on the table And here is what I see for the capacity over time 为什么它仍保持在 25 个写入单元 难道不应
  • 将对象转换为类似类型

    在斯卡拉 我有两个 Any 类型的对象 如果可能的话 我想将对象转换为正确的 Ordered 特征 然后将它们与 你可以通过以下方式实现Ordering类型类别 def compare T Ordering Manifest a AnyRe
  • 如何使用 FireDAC 在 Firebird 3.0 上启用 WireCompression [重复]

    这个问题在这里已经有答案了 我希望使用 WireCompression 连接到 Firebird Server 3 0 这是自 3 0 版以来的新功能 我很难做到这一点 我能找到的唯一记录说明是在 firebird conf 中将 Wire
  • Firefox 扩展中的 IP 地址查找

    我正在编写一个 Firefox 扩展 我需要找到当前加载页面的 IP 地址 我可以使用 window location host 获取页面的主机名 但是有什么方法可以找到该主机名的 ip 吗 我尝试在 Mozilla 开发人员中心寻找答案
  • 使用 mod_wsgi 在 Apache 上部署多个 django 应用程序

    我想在同一主机中部署两个不同的 django 应用程序 第一个对应于 url site1 第二个对应于 url site2 这是我的配置 LoadModule wsgi module modules mod wsgi so WSGIScri
  • 如何编写 a-> b -> b -> b 类型的函数来折叠树

    一些背景 我在Haskell中有一个以下类型的foldT函数 类似于foldr 但用于树 foldT a gt b gt b gt b gt b gt Tree a gt b 该foldT仅将类型 a gt b gt b gt b 作为输入
  • Overflow-x:hidden 仍然可以滚动

    问题是 我有一个全宽的栏菜单 它是通过在右侧和左侧创建一个大边距来制作的 该边距应裁剪为overflow x hidden 而且它是 没有滚动条 一切 视觉上 都很好 但是 如果您拖动页面 使用 Mac Lion 或向右滚动 页面会显示一个
  • Bootstrap模式:关闭当前,打开新的

    我已经寻找了一段时间 但找不到解决方案 我想要以下内容 在 Bootstrap 模式中打开 URL 我当然有这个工作 所以内容是动态加载的 当用户按下此模式内的按钮时 我希望当前的模式隐藏 之后立即 我希望使用新的 URL 用户单击的 打开
  • 如何获取chrome当前版本的当前URL

    我想获取 chrome 当前版本的当前 URL 所以 我尝试使用这种方式 http www codeproject com Questions 648906 how to get current URL for chrome ver 29
  • + 不支持的操作数类型:“float”和“datetime.timedelta”,“出现在索引 5”)

    我有一个数据集 其中一个输入包含日期和时间 首先 我编写了代码来查找 X3 列中 5 值的第一个时间 然后将该时间转换为 0 然后我尝试将 timedelta hours 1 添加到范围为 6 的内容中 然后它给了我这个错误 unsuppo
  • 如何将错误 403 重定向到 .htaccess 中的 root

    我对 Apache 不是很坚定 所以如果这个问题看起来有点明显 请原谅 我想通过 htaccess 文件将特定目录中导致错误 403 的请求重定向到我的网络服务器根目录 所以https thedomain com secretlair ht
  • 分配器和工作线程端点队列在同一台机器上

    我正在使用 NServiceBus 3 2 2 0 尝试在同一台机器上测试分配器和工作人员 我注意到经销商正在创建以下队列 端点队列 EndPointQueue distributor control EndPointQueue distr
  • Google Mock:使用全局模拟对象可以吗?

    在所有有关的文档中gmock我总是发现模拟对象在测试中被实例化 如下所示 TEST Bim Bam MyMockClass myMockObj EXPECT CALL MyMockObj foo 因此 每次测试都会创建和销毁该对象 我相信创
  • Tensorflow:服务模型始终返回相同的预测

    我需要你的帮助 我现在有点陷入困境 我重新训练了一个分类张量流模型 它给出了非常好的结果 现在我想通过张量流服务来服务它 我设法提供了它 但是当我使用它时 无论输入是什么 它总是给我相同的结果 我认为导出模型的方式有问题 但我不知道是什么