首页 > 解决方案 > 如何将 wav 写入 tfrecord 然后读回

问题描述

我正在尝试将编码的 wav 写入 tfrecord,然后将其读回。我知道我可以将 wav 写为普通张量,但我正在努力节省空间。

我想做类似以下的事情,但不确定如何填写省略号。特别是,我不知道是否应该保存为 int64 功能或字节功能。

def wav_feature(wav):
    value = tf.audio.encode_wav(wav, 44100)
    return tf.train.Feature(...)

example = tf.train.Example(features=tf.train.Features(feature={
    'foo': wav_feature(wav),
}))

with tf.io.TFRecordWriter(outpath) as writer:
    writer.write(example.SerializeToString())

# In parser

features = tf.io.parse_single_example(
            serialized=proto,
            features={'foo': tf.io.FixedLenFeature([], ...)})

decoded, sr = tf.audio.decode_wav(features['foo'])

标签: pythontensorflowtensorflow2.0tfrecord

解决方案


它看起来像encode_wav 返回一个字符串 tensor,所以最好使用字节功能:

def _bytes_feature(value):                                                      
  """Returns a bytes_list from a string / byte."""                              
  if isinstance(value, type(tf.constant(0))):                                   
    value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))         

# Convert to a string tensor.
wav_encoded = tf.audio.encode_wav(wav, 44100)

feature = {'foo': _bytes_feature(wav_encoded)}         
example = tf.train.Example(features=tf.train.Features(feature=feature))      

然后,在解析器中:

features = tf.io.parse_single_example(
        example.SerializeToString(),                 
        features={'foo': tf.io.FixedLenFeature([], tf.string)})               
# wav_encoded will be a string tensor. 
wav_encoded = features['foo']

的定义_bytes_feature这里


推荐阅读