我有一些代码可以编写这样的 tfrecord 文件
filename = "D:\\nvdata_.wav"
recname = 'list.tfrecord'
f_wav = wave.open(filename, 'rb')
num_frames = f_wav.getnframes()
print(num_frames)
data = np.fromstring(f_wav.readframes(num_frames), dtype=np.int16)
f_wav.close()
sub_data1 = data[10000:10200]
sub_data2 = data[20000:20200]
input_feature = [tf.train.Feature(int64_list=tf.train.Int64List(value=[input_])) for input_ in sub_data1]
label_feature = [tf.train.Feature(int64_list=tf.train.Int64List(value=[label_])) for label_ in sub_data2]
feature_list = {'input': tf.train.FeatureList(feature=input_feature),
'label': tf.train.FeatureList(feature=label_feature)}
featurelists = tf.train.FeatureLists(feature_list=feature_list)
example = tf.train.SequenceExample(feature_lists=featurelists)
with tf.python_io.TFRecordWriter(recname) as writer:
writer.write(example.SerializeToString())
现在我想解析文件内的数据。我怎么能那样做呢? 非常感谢您的帮助!
最佳答案
您必须使用 tf.data.TFRecordDataset
读取您的 tfrecord 文件。通过 tf.io.parse_single_example 传递您在 tfrecord 文件中创建的功能,如图所示。在 tf.io.FixedLenFeature 内部,您必须传递输入和标签的形状。我假设它们是 0 维条目。
这里是帮助您入门的代码示例。
def parse_function(record):
features = {
'input': tf.io.FixedLenFeature((), dtype=tf.int64),
'label': tf.io.FixedLenFeature((), dtype=tf.int64)
}
example = tf.io.parse_single_example(record, features)
return example['input'], example['label']
dataset = tf.data.TFRecordDataset('data.tfrecord')
dataset = dataset.map(parse_function)
for data in dataset.take(10):
print(data)
关于python - 如何读取tfrecord文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58470530/