如何将从TFRecords读取的值用作tf.reshape的参数?

jks*_*hin 7 python tensorflow

def read_and_decode(filename_queue):
  reader = tf.TFRecordReader()
  _, serialized_example = reader.read(filename_queue)
  features = tf.parse_single_example(
      serialized_example,
      # Defaults are not specified since both keys are required.
      features={
          'image_raw': tf.FixedLenFeature([], tf.string),
          'label': tf.FixedLenFeature([], tf.int64),
          'height': tf.FixedLenFeature([], tf.int64),
          'width': tf.FixedLenFeature([], tf.int64),
          'depth': tf.FixedLenFeature([], tf.int64)
      })
  # height = tf.cast(features['height'],tf.int32)
  image = tf.decode_raw(features['image_raw'], tf.uint8)
  image = tf.reshape(image,[32, 32, 3])
  image = tf.cast(image,tf.float32)
  label = tf.cast(features['label'], tf.int32)
  return image, label
Run Code Online (Sandbox Code Playgroud)

我正在使用TFRecord来存储我的所有数据.函数read_and_decode来自TensorFlow提供的TFRecords示例.目前我通过预定义的值重塑:

image = tf.reshape(image,[32, 32, 3])
Run Code Online (Sandbox Code Playgroud)

但是,我现在使用的数据具有不同的尺寸.例如,我可以有一个[40,30,3]的图像(缩放这不是一个选项,因为我不希望它被扭曲).我想阅读不同维度的数据,并在数据扩充阶段使用random_crop来规避这个问题.我需要的是以下内容.

height = tf.cast(features['height'], tf.int32)
width = tf.cast(features['width'], tf.int32)
image = tf.reshape(image,[height, width, 3])
Run Code Online (Sandbox Code Playgroud)

但是,我似乎找不到办法做到这一点.谢谢你的帮助!

编辑:

ValueError: All shapes must be fully defined: [TensorShape([Dimension(None), Dimension(None), Dimension(None)]), TensorShape([])]

image = tf.reshape(image, tf.pack([height, width, 3]))
image = tf.reshape(image, [32,32,3])
Run Code Online (Sandbox Code Playgroud)

这两行确实存在问题.硬编码变量可以工作,但不能使用tf.pack().

mrr*_*rry 6

你已经非常接近有一个可行的解决方案了!现在没有自动的方法给 TensorFlow 一个由张量和数字组成的列表,并从中生成一个张量,这tf.reshape()是预期的。答案是使用tf.stack(),它明确地采用 N 维张量(或可转换为张量的事物)列表并将它们打包成 (N+1) 维张量。

这意味着你可以写:

features = ...  # Parse from an example proto.
height = tf.cast(features['height'], tf.int32)
width = tf.cast(features['width'], tf.int32)

image = tf.reshape(image, tf.stack([height, width, 3]))
Run Code Online (Sandbox Code Playgroud)