python - 如何读取tfrecord文件

标签 python tensorflow

我有一些代码可以编写这样的 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/

相关文章:

作为字符串给出的 Python 类型提示?

android - TensorFlow 重新训练的 inception v3 模型在 Android 上崩溃

python - 在 Keras 中加载模型权重时出现问题

python - 在 Windows 上将 Word2vec 与 Tensorflow 结合使用

python - 我可以在 View 函数内的函数中返回响应吗?

python - 使用 setuptools 构建 .egg 时如何包含 .so 文件

python - 使用真实账户连接 XTB API 时出错

python - numpy ndarray 的解释

python - ModuleNotFoundError : No module named 'tf_slim' despite installing

python - Tensorflow 替换张量中接近于零的值