到目前为止,我使用以下代码将uint8 numpy数组存储为TFRecord格式;
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _floats_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def convert_to_record(name, image, label, map):
filename = os.path.join(params.TRAINING_RECORDS_DATA_DIR, name + '.' + params.DATA_EXT)
writer = tf.python_io.TFRecordWriter(filename)
image_raw = image.tostring()
map_raw = map.tostring()
label_raw = label.tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'image_raw': _bytes_feature(image_raw),
'map_raw': _bytes_feature(map_raw),
'label_raw': _bytes_feature(label_raw)
}))
writer.write(example.SerializeToString())
writer.close()我在下面的示例代码中阅读了
features = tf.parse_single_example(example, features={
'image_raw': tf.FixedLenFeature([], tf.string),
'map_raw': tf.FixedLenFeature([], tf.string),
'label_raw': tf.FixedLenFeature([], tf.string),
})
image = tf.decode_raw(features['image_raw'], tf.uint8)
image.set_shape(params.IMAGE_HEIGHT*params.IMAGE_WIDTH*3)
image = tf.reshape(image_, (params.IMAGE_HEIGHT,params.IMAGE_WIDTH,3))
map = tf.decode_raw(features['map_raw'], tf.uint8)
map.set_shape(params.MAP_HEIGHT*params.MAP_WIDTH*params.MAP_DEPTH)
map = tf.reshape(map, (params.MAP_HEIGHT,params.MAP_WIDTH,params.MAP_DEPTH))
label = tf.decode_raw(features['label_raw'], tf.uint8)
label.set_shape(params.NUM_CLASSES)而且它运行得很好。现在我想用我的数组"map“做同样的事情,而不是uint8,我找不到如何做到这一点的例子;我尝试了_floats_feature函数,如果我向它传递一个标量,它就有效,但不能用数组;用uint8,序列化可以通过方法tostring()来完成;
如何序列化一个浮点型numpy数组,以及如何读回该数组?
发布于 2016-12-21 05:13:43
FloatList和BytesList需要一个可迭代的。所以你需要向它传递一个浮点数的列表。去掉_float_feature中多余的括号,即
def _floats_feature(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
numpy_arr = np.ones((3,)).astype(np.float)
example = tf.train.Example(features=tf.train.Features(feature={"bytes": _floats_feature(numpy_arr)}))
print(example)
features {
feature {
key: "bytes"
value {
float_list {
value: 1.0
value: 1.0
value: 1.0
}
}
}
}发布于 2017-07-02 19:48:45
我将详述雅罗斯拉夫的答案。
Int64List、BytesList和FloatList需要iterator of the underlying elements (重复字段)。在您的例子中,您可以使用列表作为迭代器。
你提到过:如果我向它传递一个标量,而不是数组,它就会起作用。这是意料之中的,因为当您传递一个标量时,您的_floats_feature会在其中创建一个包含一个浮点元素的数组(与预期完全相同)。但是当你传递一个数组时,你会创建一个数组列表,并将其传递给一个函数,该函数需要一个浮点数列表。
因此,只需从您的函数中删除数组的构造:float_list=tf.train.FloatList(value=value)
发布于 2019-02-14 09:41:26
我在处理类似的问题时偶然发现了这一点。由于原始问题的一部分是如何从tfrecords中读回float32功能,我将把这个留在这里,以防它对任何人有帮助:
如果使用map.ravel()将维度[x, y, z]的map输入到_floats_feature中
features = {
...
'map': tf.FixedLenFeature([x, y, z], dtype=tf.float32)
...
}
parsed_example = tf.parse_single_example(serialized=serialized, features=features)
map = parsed_example['map']https://stackoverflow.com/questions/41246438
复制相似问题