【问题标题】:Construct TfRecord for image-text paired data为图文配对数据构建 TfRecord
【发布时间】:2019-04-20 23:44:15
【问题描述】:

我坚持让 tfrecords 为图像-文本对数据工作。

这是从图像特征的 numpy 数组和文本文件创建 tfrecord 的代码,

def npy_to_tfrecords(numpy_array, text_file, output_file):
      f = open(text_file)

      # write records to a tfrecords file
      writer = tf.python_io.TFRecordWriter(output_file)

      # Loop through all the features you want to write
      for X, line in zip(numpy_array, f) :
         #let say X is of np.array([[...][...]])
         #let say y is of np.array[[0/1]]

         txt = "{}".format(line[:-1])
         txt = txt.encode()

         # Feature contains a map of string to feature proto objects
         feature = {}
         feature['x'] = tf.train.Feature(float_list=tf.train.FloatList(value=X.flatten()))
         feature['y'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[txt]))

         # Construct the Example proto object
         example = tf.train.Example(features=tf.train.Features(feature=feature))

         # Serialize the example to a string
         serialized = example.SerializeToString()

         # write the serialized objec to the disk
         writer.write(serialized)
      writer.close()

在此之后我无法制作数据集:

def load_data_tfr():

   train = tf.data.TFRecordDataset("train.tfrecord")

   # example proto decode
   def _parse_function1(example_proto):
      keys_to_features = {'x': tf.FixedLenFeature(2048, tf.float32),
                          'y': tf.VarLenFeature(tf.string) } 
      parsed_features = tf.parse_single_example(example_proto, keys_to_features)
      return {"x": parsed_features['x'], "y":  parsed_features['y']} # ['x'], parsed_features['y']

   # Parse the record into tensors.
   train = train.map(_parse_function1)

   return train

我保留 .得到错误:

train_data = load_data_tfr()
random.shuffle(train_data)
for i in reversed(range(1, len(x))): TypeError: object of type 'MapDataset' has no len()

有什么帮助吗?谢谢。

【问题讨论】:

    标签: python tensorflow tensorflow-datasets tfrecord


    【解决方案1】:

    MapDataset 没有长度。

    所以,将这两行放在代码的最顶部。

    import tensorflow as tf
    tf.enable_eager_execution()
    

    然后试试

    iterator = train_data.make_one_shot_iterator()
    image, label = iterator.get_next()
    

    当然,我假设您的 tfrecord 部分没有任何错误。

    根据 Tensorflow 教程,图像以字节格式保存,而不是 np 数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2021-04-23
      • 2018-11-12
      • 2022-10-08
      • 2023-03-29
      • 2020-01-27
      • 1970-01-01
      相关资源
      最近更新 更多