python - 如何将 CNN 应用于短时傅里叶变换?
问题描述
所以我有一个代码,它返回一个 .wav 文件的短时傅里叶变换频谱。我希望能够采取,比如说一毫秒的频谱,并在其上训练一个 CNN。
我不太确定我将如何实现它。我知道如何格式化图像数据以输入 CNN,以及如何训练网络,但我不知道如何获取 FFT 数据并将其划分为小的时间范围。
FFT码(对不起超长码):
rate, audio = wavfile.read('scale_a_lydian.wav')
audio = np.mean(audio, axis=1)
N = audio.shape[0]
L = N / rate
M = 1024
# Audio is 44.1 Khz, or ~44100 samples / second
# window function takes 1024 samples or 0.02 seconds of audio (1024 / 44100 = ~0.02 seconds)
# and shifts the window 100 over each time
# so there would end up being (total_samplesize - 1024)/(100) total steps done (or slices)
slices = util.view_as_windows(audio, window_shape=(M,), step=100) #slices overlap
win = np.hanning(M + 1)[:-1]
slices = slices * win #each slice is 1024 samples (0.02 seconds of audio)
slices = slices.T #transpose matrix -> make each column 1024 samples (ie. make each column one slice)
spectrum = np.fft.fft(slices, axis=0)[:M // 2 + 1:-1] #perform fft on each slice and then take the first half of each slice, and reverse
spectrum = np.abs(spectrum) #take absolute value of slices
# take SampleSize * Slices
# transpose into slices * samplesize
# Take the first row -> slice * samplesize
# transpose back to samplesize * slice (essentially get 0.01s of spectrum)
spectrum2 = spectrum.T
spectrum2 = spectrum2[:1]
spectrum2 = spectrum2.T
以下输出 FFT 频谱:
N = spectrum2.shape[0]
L = N / rate
f, ax = plt.subplots(figsize=(4.8, 2.4))
S = np.abs(spectrum2)
S = 20 * np.log10(S / np.max(S))
ax.imshow(S, origin='lower', cmap='viridis',
extent=(0, L, 0, rate / 2 / 1000))
ax.axis('tight')
ax.set_ylabel('Frequency [kHz]')
ax.set_xlabel('Time [s]');
plt.show()
(请随时纠正我在评论中提出的任何理论错误)
所以据我了解,我有一个 numpy 数组(频谱),每列是一个包含 510 个样本的切片(减半,因为每个 FFT 切片的一半是多余的(没用?)),每个样本都有频率列表?
上面的代码理论上输出0.01s的音频作为频谱,这正是我所需要的。这是真的,还是我想的不对?
解决方案
我建议您使用Librosa加载音频并在 1 行代码中进行一些预处理。您会希望所有音频文件都具有相同的采样率。此外,您还想在特定部分剪切音频以获得特定间隔。您可以像这样加载音频:
import librosa
y, sr = librosa.load(audiofile, offset=10.0, duration=30.0, sr=16000)
因此,您将时间序列设为 y。从这里我会在音频上使用 CNN 的这个很好的实现。在这里,这个家伙正在使用他自己的库来执行 GPU 梅尔谱图计算。您只需要将y
参数提供给网络。在这里查看它是如何完成的。或者,您可以删除该网络的第一层并预先计算您的梅尔谱图并将它们保存在某处。这些将是您对网络的输入。看这里
其他资源: 音频分类:卷积神经网络方法
推荐阅读
- c# - 使用自定义 ItemTemplate 时未设置 ComboBox SelectedItem
- php - Spatie laravel/permission - 修改表和方法
- javascript - Javascript:循环仅打印最后一个值
- java - 正则表达式匹配非匹配组
- python-3.x - 在 Python3 中压缩写入 StringIO 缓冲区的 CSV 文件
- docker - 在 Docker 18.06 和 Docker Compose 1.20.0 中配置桥接网络和容器 CIDR 的问题
- r - brew install 后无法将软件包安装到 R
- c# - 将分钟转换为小时 - 分钟包括天
- vba - VBA - 在if语句中检查字符串是否是不同工作表的列中的1
- ios - 如果 CoreData NSPersistentContainer 内容被修改,则使用 KVO 触发操作