Tensorflow TFRecord:无法分析序列化的examp

2024-05-23 18:02:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图遵循this guide以便将输入数据序列化为TFRecord格式,但在尝试读取时仍遇到此错误:

InvalidArgumentError: Key: my_key. Can't parse serialized Example.

我不知道我错在哪里。这是我无法忘记的问题的一个最小的复制品。

序列化一些示例数据:

with tf.python_io.TFRecordWriter('train.tfrecords') as writer:
  for idx in range(10):
        example = tf.train.Example(
            features=tf.train.Features(
                feature={
                    'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[1,2,3])),
                    'test': tf.train.Feature(float_list=tf.train.FloatList(value=[0.1,0.2,0.3])) 
                }
            )
        )

        writer.write(example.SerializeToString())
  writer.close()

分析函数和反序列化:

def parse(tfrecord):
  features = {
      'label': tf.FixedLenFeature([], tf.int64, default_value=0),
      'test': tf.FixedLenFeature([], tf.float32, default_value=0.0),
  }
  return tf.parse_single_example(tfrecord, features)

dataset = tf.data.TFRecordDataset('train.tfrecords').map(parse)
getnext = dataset.make_one_shot_iterator().get_next()

尝试运行此操作时:

with tf.Session() as sess:
  v = sess.run(getnext)
  print (v)

我触发上述错误信息。

是否可以跳过此错误并反序列化我的数据?


Tags: 数据序列化parsevalueexampletfas错误
2条回答

tf.FixedLenFeature()用于读取固定大小的数据数组。数据的形状应该预先定义。将解析函数更新为

def parse(tfrecord):
   return tf.parse_single_example(tfrecord, features={
       'label': tf.FixedLenFeature([3], tf.int64, default_value=[0,0,0]),
       'test': tf.FixedLenFeature([3], tf.float32, default_value=[0.0, 0.0, 0.0]),
   })

应该做这项工作。

另一种方法是,如果输入特性的长度不是固定的,并且是任意大小的,那么您还可以将tf.io.FixedLenSequenceFeature()与参数allow_missing = Truedefault_value=0(对于int类型和0.0 for float类型)一起使用,这不需要输入特性具有与tf.io.FixedLenFeature()不同的固定大小。您可以找到更多信息here

相关问题 更多 >