我正在尝试在此之后将压缩的数据集写入TFRecord文件 tutorial,但我的处境不同,因为ZipDataSet中每个数据集的每个元素都是张量而不是标量。
本教程通过注释解决了这种情况
注意:为简单起见,本示例仅使用标量输入。处理非标量特征的最简单方法是使用tf.serialize_tensor将张量转换为二进制字符串。字符串是张量流中的标量。使用tf.parse_tensor将二进制字符串转换回张量。
但是我收到的错误似乎表明_bytes_feature函数正在获取张量而不是字节。
import tensorflow as tf
import numpy as np
sess = tf.Session()
def _bytes_feature(value):
"""Returns a bytes_list from a string / byte."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def serialize_with_labels(a, b, c, d):
"""
Creates a tf.Example message ready to be written to a file.
"""
# Create a dictionary mapping the feature name to the tf.Example-compatible
# data type.
feature = {'a': _bytes_feature(a),
'b': _bytes_feature(b),
'c': _bytes_feature(c),
'd': _bytes_feature(d),
}
# Create a Features message using tf.train.Example.
example_proto = tf.train.Example(features=tf.train
.Features(feature=feature))
return example_proto.SerializeToString()
def tf_serialize_w_labels(a, b, c, d):
"""Map serialize_with_labels to tf.data.Dataset."""
tf_string = tf.py_func(serialize_with_labels,
(a, b, c, d),
tf.string)
return tf.reshape(tf_string, ())
# a is a [n,m,p] tensor
# b is a [n,m,p] tensor
# c is a [n,m,p] tensor
# d is a [n,1,1] tensor
zipped = tf.data.Dataset().from_tensor_slices((a,b,c,d))
# I have confirmed that each item of serial_tensors is a tuple
# of four bytestrings.
serial_tensors = zipped.map(tf.serialize_tensor)
# Each item of serialized_features_dataset is a single bytestring
serialized_features_dataset = serial_tensors.map(tf_serialize_w_labels)
writer = tf.contrib.data.TFRecordWriter('test_output')
writeop = writer.write(serialized_features_dataset)
sess.run(writeop)
是我要运行的代码的基本格式。它写了,但是当我读TFRecord时,
def _parse_function(example_proto):
# Parse the input tf.Example proto using the dictionary below.
feature_description = {
'a': tf.FixedLenFeature([], tf.string, default_value=''),
'b': tf.FixedLenFeature([], tf.string, default_value=''),
'c': tf.FixedLenFeature([], tf.string, default_value=''),
'd': tf.FixedLenFeature([], tf.string, default_value='')
}
return tf.parse_single_example(example_proto, feature_description)
filenames = ['zipped_TFR']
raw_dataset = tf.data.TFRecordDataset(filenames)
parsed = raw_dataset.map(_parse_function)
parsed_it = parsed.make_one_shot_iterator()
# prints the first element of a
print(sess.run(tf.parse_tensor(parsed_it.get_next()['a'], out_type=tf.int32)))
#prints the first element of b
print(sess.run(tf.parse_tensor(parsed_it.get_next()['b'], out_type=tf.int32)))
#prints the first element of c
print(sess.run(tf.parse_tensor(parsed_it.get_next()['c'], out_type=tf.int32)))
#prints nothing
print(sess.run(tf.parse_tensor(parsed_it.get_next()['d'], out_type=tf.int32)))
这不是迭代器用尽的问题,例如,在打印a,b或c之前,我尝试打印d,但是什么都没得到,然后在同一会话中成功打印了a。 >
我正在使用tensorflow-gpu版本1.10,并且我暂时坚持使用它,这就是为什么我使用
writer = tf.contrib.data.TFRecordWriter('test_output')
代替
writer = tf.data.experimental.TFRecordWriter('test_output')
首先,我将a,b,c和d展平为[n,-1]。然后,我将serialize_w_labels更改为以下代码(不考虑tf_serialize_w_examples)。
def serialize_w_labels(a, b, c, d, n, m, p):
# The object we return
ex = tf.train.SequenceExample()
# A non-sequential feature of our example
ex.context.feature["d"].int64_list.value.append(d)
ex.context.feature["n"].int64_list.value.append(n)
ex.context.feature["m"].int64_list.value.append(m)
ex.context.feature["p"].int64_list.value.append(p)
# Feature lists for the two sequential features of our example
fl_a = ex.feature_lists.feature_list["a"]
fl_b = ex.feature_lists.feature_list["b"]
fl_c = ex.feature_lists.feature_list["c"]
for _a, _b, _c in zip(a, b, c):
fl_a.feature.add().int64_list.value.append(_a)
fl_b.feature.add().int64_list.value.append(_b)
fl_c.feature.add().float_list.value.append(_c)
return ex.SerializeToString()
以下代码正确解析了结果数据集的元素:
context_features = {
"d": tf.FixedLenFeature([], dtype=tf.int64),
"m": tf.FixedLenFeature([], dtype=tf.int64),
"n": tf.FixedLenFeature([], dtype=tf.int64),
"p": tf.FixedLenFeature([], dtype=tf.int64)
}
sequence_features = {
"a": tf.FixedLenSequenceFeature([], dtype=tf.int64),
"b": tf.FixedLenSequenceFeature([], dtype=tf.int64),
"c": tf.FixedLenSequenceFeature([], dtype=tf.float32)
}
context_parsed, sequence_parsed = tf.parse_single_sequence_example(
serialized=ex,
context_features=context_features,
sequence_features=sequence_features
)
显然,您的dtype可能会有所不同。然后可以使用上下文特征重塑展平的a,b和c。
答案 0 :(得分:1)
我认为您应该研究tf.io.FixedLenSequenceFeature
,这应该允许您将一系列功能作为功能写入TFRecord
文件。例如,它在YouTube8M数据集中用于存储一项功能,该功能对于每个视频都是一组帧,对于每个具有Tensor
的帧。
示例阅读方法: https://www.tensorflow.org/api_docs/python/tf/io/FixedLenSequenceFeature
答案 1 :(得分:0)
如果您想使用tf.serialize_tensor
进行记录,则需要创建一个会话并评估张量。
_bytes_feature(sess.run(tf.serialize_tensor(features[key])))