python - 如何读写二维数组的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
是错误的。有人可以帮我吗?
解决方案
我认为您应该在解析 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
推荐阅读
- java - NoSuchMethodError 与 FirebaseDatabase.getInstance()
- javascript - A-frame AR的屏幕按钮
- java - 如何在没有 maven 依赖的情况下使用 Mockito
- python - 我正在尝试将前三个高分保存到单独的 txt 文件中
- azure - 使用 Arm 模板重新生成存储帐户密钥
- hadoop - 哪个大数据搜索引擎
- multithreading - TypeError:字符串格式化期间并非所有参数都转换 - opc ua客户端到数据库连接
- java - 如何通过参数从 Android 中的 Firebase 数据库中获取数据?
- python - 为什么scipy的熵函数返回的值大于1?
- c# - 方法名称与类相同,是什么意思?