使用tf.data.map将音频文件拆分为1秒的音频张量块



我正在尝试使用可变长度的音频文件创建TensorFlow数据集。这些文件属于一个"noise"类,我已经有了其他类的1秒长度的文件。以下是我所做的:

import tensorflow as tf
from glob import glob
NUM_SAMPLES = 16000
#
# Other preprocessing functions here
#
def split_wav(file):
wav = decode_audio(file=file, desired_samples=-1) # Returns tf.float32 tensor 
# Slice 16000 length splits and drop remaining
n = int(tf.size(wav) / NUM_SAMPLES)
audio = wav[:(n * NUM_SAMPLES)] 
x = tf.split(audio, num_or_size_splits=n)
label = path_to_label(file)
y = [label for _ in x]
return x, y

@tf.function
def transform_fn(dataset: Dataset) -> Dataset:
dataset = dataset.map(split_wav)
# Dataset got kinda batched (on purpose) after split_wav i.e. splitting variable
# length input tensors into multiples of 16000
dataset = dataset.unbatch()
dataset = dataset.map(to_mfccs)
dataset = dataset.map(add_batch_dims)
return dataset
# Load all classes starting with _ (noise class)
files = glob('data/v1/[_]*/**/*.wav', recursive=True)
ds = tf.data.Dataset.from_tensor_slices(files)
ds.apply(transform_fn)

然而,这引发了以下问题:

ValueError: Rank-0 tensors are not supported as the num_or_size_splits argument to split. Argument provided: Tensor("Cast:0", shape=(), dtype=int32)

所以我的问题变成了:如何在tf.split(tensor_to_split, split_size_here)函数中传递一个0秩张量作为split_size

如果我加载所有音频文件,手动拆分它们并创建一个数据集,那么这意味着内存不足并冻结我的系统(我的数据集很大(。有什么比我在这里做的更好的方法吗?

事实证明,你无法计算图中的张量。以下是使用tf.reshape而不是tf.split解决问题的方法:

NUM_SMAPLES = 16000
def split_wav(file):
wav = decode_audio(file=file, desired_samples=-1) # Returns tf.float32 tensor 
# Slice 16000 length splits and drop remaining
n = int(tf.size(wav) / NUM_SAMPLES)
audio = wav[:(n * NUM_SAMPLES)] 
x = tf.reshape(tensor=audio, shape=(n, NUM_SAMPLES)) # Reshape along batch dim
return x

来源:r/tensorflow 上的Redditor同事

最新更新