如何对音频进行预处理以进行分类?

时间:2017-02-19 18:02:08

标签: python machine-learning tensorflow classification

我目前正在使用TensorFlow的Python API开发一个音频分类器,使用UrbanSound8K数据集并尝试区分10个互斥类。

音频文件长4秒,包含176400个数据点,导致严重的内存问题。如何预处理音频以减少内存使用量?

如何从音频中提取更多有用的功能(使用卷积和合并)?

1 个答案:

答案 0 :(得分:1)

在声音分类方面,我个人更喜欢光谱图作为神经网络的输入。这样,原始音频数据将转换为图像表示,您可以将其视为基本图像分类任务。

有多种方法可供选择,以下是我通常使用scipy做的事情,python_speech_featurespydub

import numpy as np
import scipy.io.wavfile as wave
import python_speech_features as psf
from pydub import AudioSegment

#your sound file
filepath = 'my-sound.wav'

def convert(path):

    #open file (supports all ffmpeg supported filetypes) 
    audio = AudioSegment.from_file(path, path.split('.')[-1].lower())

    #set to mono
    audio = audio.set_channels(1)

    #set to 44.1 KHz
    audio = audio.set_frame_rate(44100)

    #save as wav
    audio.export(path, format="wav")

def getSpectrogram(path, winlen=0.025, winstep=0.01, NFFT=512):

    #open wav file
    (rate,sig) = wave.read(path)

    #get frames
    winfunc=lambda x:np.ones((x,))
    frames = psf.sigproc.framesig(sig, winlen*rate, winstep*rate, winfunc)

    #Magnitude Spectrogram
    magspec = np.rot90(psf.sigproc.magspec(frames, NFFT))

    #noise reduction (mean substract)
    magspec -= magspec.mean(axis=0)

    #normalize values between 0 and 1
    magspec -= magspec.min(axis=0)
    magspec /= magspec.max(axis=0)

    #show spec dimensions
    print magspec.shape    

    return magspec

#convert file if you need to
convert(filepath)

#get spectrogram
spec = getSpectrogram(filepath)

首先,您需要根据采样率和频道标准化音频文件。你可以用优秀的 pydub 包来做到这一点(以及更多)。

之后,您需要使用FFT将音频信号转换为图像。您可以使用 scipy.io.wavefile python_speech_features 的sigproc模块来实现。我喜欢幅度谱图,将其旋转90度,将其标准化并使用生成的NumPy阵列作为我的网络的输入。您可以通过调整 winstep NFFT 的值来更改频谱图的空间维度,以适合您的输入大小

可能有更简单的方法来做到这一切;我使用上面的代码获得了良好的整体分类结果。