我想将大小为(n,3)的二维数组制作为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
的方式是错误的。
有人可以帮我吗?
答案 0 :(得分:0)
我认为您在解析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
答案 1 :(得分:0)
感谢donglinjy的建议,我在这里固定了代码
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)
}
和这里。
with tf.compat.v1.Session() as sess:
coord=tf.train.Coordinator()
threads=tf.train.start_queue_runners(coord=coord)
print(sess.run(x))
现在可以使用。