首页 > 解决方案 > 如何读写二维数组的tfrecord文件

问题描述

我想将一个大小为 (n, 3) 的二维数组设置为 a tfrecord file,然后读取它。

我写的代码tfrecord file

def _float_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))
example = tf.train.Example(
      features=tf.train.Features(
          feature={
              'arry_x':_float_feature(array[:,0]),
              'arry_y':_float_feature(array[:,1]),
              'arry_z':_float_feature(array[:,2])}
         )
      )

with tf.compat.v1.python_io.TFRecordWriter(file_name) as writer:
    writer.write(example.SerializeToString())

我试图用TFRecordReader

def get_tfrecord_feature():
    return{
        'arry_x': tf.compat.v1.io.FixedLenFeature([], tf.float32),
        'arry_y': tf.compat.v1.io.FixedLenFeature([], tf.float32),
        'arry_z': tf.compat.v1.io.FixedLenFeature([], tf.float32)
    }
filenames = [file_name, file_name2, ...]
file_name_queue = tf.train.string_input_producer(filenames)

reader = tf.TFRecordReader()
_, serialized_example = reader.read(file_name_queue)

data = tf.compat.v1.io.parse_single_example(serialized_example, features=get_tfrecord_feature())

x = data['arry_x']
y = data['arry_y']
z = data['arry_z']

x, y, z = tf.train.batch([x, y, z], batch_size=1)

我使用 tf.Session 来检查代码

with tf.compat.v1.Session() as sess:
    print(sess.run(x))

代码运行没有错误,但会话不打印任何值。我认为阅读的方式tfrecord file是错误的。有人可以帮我吗?

标签: pythontensorflowtfrecord

解决方案


我认为您应该在解析 tf 记录时将列表长度(在您的情况下为array.shape[0]如下)添加到特征定义中。

def get_tfrecord_feature():
    return{
        'arry_x': tf.compat.v1.io.FixedLenFeature([array.shape[0]], tf.float32),
        'arry_y': tf.compat.v1.io.FixedLenFeature([array.shape[0]], tf.float32),
        'arry_z': tf.compat.v1.io.FixedLenFeature([array.shape[0]], tf.float32)
    }

如果 FixedLenFeature 只有一个元素,您可以将形状保留为 []。 https://tensorflow.org/versions/r1.15/api_docs/python/tf/io/FixedLenFeature


推荐阅读