【问题标题】:Does the tf.data.Dataset support to generate dictionary structure?tf.data.Dataset 是否支持生成字典结构?
【发布时间】:2018-01-17 23:10:00
【问题描述】:

以下是 [https://www.tensorflow.org/programmers_guide/datasets] 中的一段代码。在此示例中,map 函数是一个用户定义的函数,用于读取数据。而在map函数中,我们需要设置输出类型为[tf.uint8, label.dtype]

import cv2

# Use a custom OpenCV function to read the image, instead of the standard
# TensorFlow `tf.read_file()` operation.
def _read_py_function(filename, label):
  image_decoded = cv2.imread(image_string, cv2.IMREAD_GRAYSCALE)
  return image_decoded, label

# Use standard TensorFlow operations to resize the image to a fixed shape.
def _resize_function(image_decoded, label):
  image_decoded.set_shape([None, None, None])
  image_resized = tf.image.resize_images(image_decoded, [28, 28])
  return image_resized, label

  filenames = ["/var/data/image1.jpg", "/var/data/image2.jpg", ...]
  labels = [0, 37, 29, 1, ...]

dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))
dataset = dataset.map(
  lambda filename, label: tuple(tf.py_func(
    _read_py_function, [filename, label], [tf.uint8, label.dtype])))
dataset = dataset.map(_resize_function)

我的问题是,如果我们想将_read_py_function() 输出一个Python 字典,那么我们如何设置outptu 类型呢?是否存在tf.dict 等继承数据类型?例如:

def _read_py_function(filename):
  image_filename = filename[0]
  label_filename = filename[1]
  image_id = filename[2]
  image_age = filename[3]
  image_decoded = cv2.imread(image_filename, cv2.IMREAD_GRAYSCALE)
  image_decoded = cv2.imread(label_fielname, cv2.IMREAD_GRAYSCALE)
  return {'image':image_decoded, 'label':label_decoded, 'id':image_id, 'age':image_age}

那么,我们如何设计dataset.map()函数呢?

【问题讨论】:

  • 您使用的是哪个 TensorFlow 版本?我相信 TensorFlow 1.4 确实支持字典,而 1.2 不支持(但确实支持元组)。
  • 嗨@de1,感谢您的评论!我正在使用 1.4。

标签: tensorflow tensorflow-datasets tensorflow-estimator


【解决方案1】:

tf.data.Dataset.map 调用的函数中返回字典应该可以正常工作。

这是一个例子:

dataset = tf.data.Dataset.range(10)
dataset = dataset.map(lambda x: {'a': x, 'b': 2 * x})
dataset = dataset.map(lambda y: y['a'] + y['b'])

res = dataset.make_one_shot_iterator().get_next()

with tf.Session() as sess:
    for i in range(10):
        assert sess.run(res) == 3 * i

【讨论】:

  • 嗨,Moindrot 先生,谢谢!目前我还是先将数据转换成TFRecords,然后将数据(图像+文本)序列化成TFRecords。以后我会尝试你的方法时,我会给出反馈。非常感谢!
【解决方案2】:

要添加到上述答案,这也有效:

dataset = tf.data.Dataset.range(10)
dataset = dataset.map(lambda x: {'a': x, 'b': 2 * x})

res = dataset.make_one_shot_iterator().get_next()

with tf.Session() as sess:
    for i in range(10):
        curr_res = sess.run(res)
        assert curr_res['a'] == i
        assert curr_res['b'] == 2 * i

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2018-07-13
    相关资源
    最近更新 更多