【问题标题】:Saving predicted tensor to image in TensorFlow - Graph finalized将预测张量保存到 TensorFlow 中的图像 - 最终确定的图形
【发布时间】:2018-05-09 01:41:39
【问题描述】:

我能够使用自己的数据在 TensorFlow 中训练模型。模型的输入和输出是图像。我现在尝试获取预测的输出并将其保存到 png 图像文件中以查看发生了什么。不幸的是,我在运行以下我创建的用于预测测试的函数时遇到错误。我的目标是保存也是图像的预测,以便我可以使用普通图像查看器打开它。

更多的代码。我主要是创建一个估算器

def predict_element(my_model, features):
  eval_input_fn = tf.estimator.inputs.numpy_input_fn(
    x=features,
    num_epochs=1,
    shuffle=False)

  eval_results = my_model.predict(input_fn=eval_input_fn)

  predictions = eval_results.next() #this returns a dict with my tensors
  prediction_tensor = predictions["y"] #get the tensor from the dict

  image_tensor = tf.reshape(prediction_tensor, [IMG_WIDTH, -1]) #reshape to a matrix due my returned tensor is a 1D flat one
  decoded_image = tf.image.encode_png(image_tensor)
  write_image = tf.write_file("output/my_output_image.png", decoded_image)

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(write_image))

def get_input():
  filename_dataset = tf.data.Dataset.list_files("features/*.png")
  label_dataset = tf.data.Dataset.list_files("labels/*.png")

  # Make a Dataset of image tensors by reading and decoding the files.
  image_dataset = filename_dataset.map(lambda x: tf.cast(tf.image.decode_png(tf.read_file(x), channels=1),tf.float32))
  l_dataset = label_dataset.map(lambda x: tf.cast(tf.image.decode_png(tf.read_file(x),channels=1),tf.float32))

  image_reshape = image_dataset.map(lambda x: tf.reshape(x, [IM_WIDTH * IM_HEIGHT]))
  label_reshape = l_dataset.map(lambda x: tf.reshape(x, [IM_WIDTH * IM_HEIGHT]))

  iterator = image_reshape.make_one_shot_iterator()
  iterator2 = label_reshape.make_one_shot_iterator()

  next_img = iterator.get_next()
  next_lbl = iterator2.get_next()

  features = []
  labels = []
  # read all 10 images and labels and put it in the array
  # so we can pass it to the estimator
  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(10):
      t1, t2 = sess.run([next_img, next_lbl])
      features.append(t1)
      labels.append(t2)

  return {"x": np.array(features)}, np.array(labels)

def main(unused_argv):
    features, labels = get_input() # creating the features dict {"x": }
    my_estimator = tf.estimator.Estimator(model_fn=my_cnn_model, model_dir="/tmp/my_model")

    predict_element(my_estimator, features)

错误是

图表已完成,无法修改

通过一些简单的 print() 语句,我可以看到用

检索字典

eval_results = my_model.predict(input_fn=eval_input_fn)

很可能是最终确定图表的那个。 我绝对不知道该做什么或在哪里寻找解决方案。如何保存输出?

我在我的 model_fn 中试过这个:

#the last layer of my network is dropout
predictions = {
   "y": dropout
    }

  if mode == tf.estimator.ModeKeys.PREDICT:
    reshape1 = tf.reshape(dropout, [-1,IM_WIDTH, IM_HEIGHT])
    sliced = tf.slice(reshape1, [0,0,0], [1, IM_WIDTH, IM_HEIGHT])
    encoded = tf.image.encode_png(tf.cast(sliced, dtype=tf.uint8))
    outputfile = tf.write_file(params["output_path"], encoded)
    return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)

我的问题是我无法传回“输出文件”节点,因此我可以使用它。

【问题讨论】:

  • 您收到的错误是什么?
  • Graph is finalized and cannot be modified 是阻止我使用我的预测的错误。

标签: python tensorflow


【解决方案1】:

您的图表已完成,无法修改。您可以将此 tensorflow 操作添加到您的模型(在运行它之前),也可以简单地编写一些单独保存图像的 python 代码(不使用 tensorflow)。也许我会找到一些我的旧代码作为示例。

您也可以创建第二个图,然后您可以在不更改现有模型图的情况下使用 tensorflow。

您必须区分图形节点和评估对象。 tf.reshape 不将数组作为输入,而是将图形节点作为输入。 https://www.tensorflow.org/programmers_guide/graphs

【讨论】:

  • 但是我必须在哪里添加这个操作。在我的model_fn中?我传递给预测函数的特征字典有一批 10 张图像,因此我得到了 10 个预测。如何将它们保存为单个图像?我无法使用切片函数来获得单个预测张量?!
  • 第一个问题:是的,如果您想使用 tensorflow 图操作,请将它们添加到估计器模型/图定义中。我曾经在训练期间这样做过。但是,当您收到字典时,您应该能够将其减少为单个数组,然后将其保存为图像,例如使用 PyPNG
  • 我在问题帖子中添加了我尝试过的内容。你能看看吗?
  • 据我所知,您的预测输出没有改变。此外,Tensorflow 图现在将图像保存为 png 文件。这应该可以解决您的问题,如您原始问题中的第二句话所示。
  • 是的,预测字典没有变化,因为我无法扩展它。 Tensorflow 正在计算条目,当我在其中添加更多条目时向我抛出了一个错误。但无论如何,我现在设法通过实现第二个图形来重塑、编码和保存预测,从而得到我想要的。非常感谢您的帮助:)
【解决方案2】:

对于遇到相同问题的每个人,这是我的解决方案。我不知道这是否是正确的方法,但它有效。

在我的预测函数中,我为整形、切片、编码和保存创建了第二个图表,如下所示:

  pred_dict = eval_results.next() #generator the predict function returns
  preds = pred_dict["y"] #get the predictions from the dict

  #create the second graph
  g = tf.Graph()
  with g.as_default():
    inp = tf.Variable(preds)
    reshape1 = tf.reshape(printnode, [IM_WIDTH, IM_HEIGHT, -1])
    sliced = tf.slice(reshape1, [0,0,0], [ IM_WIDTH, IM_HEIGHT,1])
    reshaped = tf.reshape(sliced, [IM_HEIGHT, IM_WIDTH, 1])
    encoded = tf.image.encode_png(tf.image.convert_image_dtype(reshaped,tf.uint16))
    outputfile = tf.write_file("/tmp/pred_output/prediction_img.png", encoded)
    with tf.Session() as sess:
      sess.run(tf.global_variables_initializer())
      sess.run(outputfile)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-13
    • 2021-09-27
    • 2018-08-08
    • 2018-03-16
    • 2017-11-22
    • 1970-01-01
    • 2017-12-25
    • 2018-01-10
    相关资源
    最近更新 更多