python - 如何将 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'])
解决方案
它看起来像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
在这里。
推荐阅读
- postcss - PurgeCSS 忽略使用的类
- python - 如果给定范围,如何为数据框列创建 bin
- node.js - 从与 nodejs 的电报聊天中踢出用户
- airflow - 气流 dag 中特定任务的执行时间和状态
- ssl - Spring Security (for Webflux) - 仅对一个端点禁用 mTLS over HTTPS(保留其余 mTLS/SSL)
- python - 构建带有时区感知列的 pandas DataFrame 时发出警告
- javascript - 使用二维数组的列从 JSON 对象中获取数据
- javascript - Emscripten,如何在 Typescript 中传递指向浮点数组的指针
- css - 从默认 CSS 样式继承样式,同时覆盖一个属性
- python - 将 2020-09-01T00:00:00-05:00 时间戳转换为 dd-mm-yyyy