Spaces:
Running
Running
File size: 11,327 Bytes
9ce984a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
"""
Title: Audio Classification with the STFTSpectrogram layer
Author: [Mostafa M. Amin](https://mostafa-amin.com)
Date created: 2024/10/04
Last modified: 2024/10/04
Description: Introducing the `STFTSpectrogram` layer to extract spectrograms for audio classification.
Accelerator: GPU
"""
"""
## Introduction
Preprocessing audio as spectrograms is an essential step in the vast majority
of audio-based applications. Spectrograms represent the frequency content of a
signal over time, are widely used for this purpose. In this tutorial, we'll
demonstrate how to use the `STFTSpectrogram` layer in Keras to convert raw
audio waveforms into spectrograms **within the model**. We'll then feed
these spectrograms into an LSTM network followed by Dense layers to perform
audio classification on the Speech Commands dataset.
We will:
- Load the ESC-10 dataset.
- Preprocess the raw audio waveforms and generate spectrograms using
`STFTSpectrogram`.
- Build two models, one using spectrograms as 1D signals and the other is using
as images (2D signals) with a pretrained image model.
- Train and evaluate the models.
## Setup
### Importing the necessary libraries
"""
import os
os.environ["KERAS_BACKEND"] = "jax"
import keras
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.io.wavfile
from keras import layers
from scipy.signal import resample
keras.utils.set_random_seed(41)
"""
### Define some variables
"""
BASE_DATA_DIR = "./datasets/esc-50_extracted/ESC-50-master/"
BATCH_SIZE = 16
NUM_CLASSES = 10
EPOCHS = 200
SAMPLE_RATE = 16000
"""
## Download and Preprocess the ESC-10 Dataset
We'll use the Dataset for Environmental Sound Classification dataset (ESC-10).
This dataset consists of five-second .wav files of environmental sounds.
### Download and Extract the dataset
"""
keras.utils.get_file(
"esc-50.zip",
"https://github.com/karoldvl/ESC-50/archive/master.zip",
cache_dir="./",
cache_subdir="datasets",
extract=True,
)
"""
### Read the CSV file
"""
pd_data = pd.read_csv(os.path.join(BASE_DATA_DIR, "meta", "esc50.csv"))
# filter ESC-50 to ESC-10 and reassign the targets
pd_data = pd_data[pd_data["esc10"]]
targets = sorted(pd_data["target"].unique().tolist())
assert len(targets) == NUM_CLASSES
old_target_to_new_target = {old: new for new, old in enumerate(targets)}
pd_data["target"] = pd_data["target"].map(lambda t: old_target_to_new_target[t])
pd_data
"""
### Define functions to read and preprocess the WAV files
"""
def read_wav_file(path, target_sr=SAMPLE_RATE):
sr, wav = scipy.io.wavfile.read(os.path.join(BASE_DATA_DIR, "audio", path))
wav = wav.astype(np.float32) / 32768.0 # normalize to [-1, 1]
num_samples = int(len(wav) * target_sr / sr) # resample to 16 kHz
wav = resample(wav, num_samples)
return wav[:, None] # Add a channel dimension (of size 1)
"""
Create a function that uses the `STFTSpectrogram` to compute a spectrogram,
then plots it.
"""
def plot_single_spectrogram(sample_wav_data):
spectrogram = layers.STFTSpectrogram(
mode="log",
frame_length=SAMPLE_RATE * 20 // 1000,
frame_step=SAMPLE_RATE * 5 // 1000,
fft_length=1024,
trainable=False,
)(sample_wav_data[None, ...])[0, ...]
# Plot the spectrogram
plt.imshow(spectrogram.T, origin="lower")
plt.title("Single Channel Spectrogram")
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.show()
"""
Create a function that uses the `STFTSpectrogram` to compute three
spectrograms with multiple bandwidths, then aligns them as an image
with different channels, to get a multi-bandwith spectrogram,
then plots the spectrogram.
"""
def plot_multi_bandwidth_spectrogram(sample_wav_data):
# All spectrograms must use the same `fft_length`, `frame_step`, and
# `padding="same"` in order to produce spectrograms with identical shapes,
# hence aligning them together. `expand_dims` ensures that the shapes are
# compatible with image models.
spectrograms = np.concatenate(
[
layers.STFTSpectrogram(
mode="log",
frame_length=SAMPLE_RATE * x // 1000,
frame_step=SAMPLE_RATE * 5 // 1000,
fft_length=1024,
padding="same",
expand_dims=True,
)(sample_wav_data[None, ...])[0, ...]
for x in [5, 10, 20]
],
axis=-1,
).transpose([1, 0, 2])
# normalize each color channel for better viewing
mn = spectrograms.min(axis=(0, 1), keepdims=True)
mx = spectrograms.max(axis=(0, 1), keepdims=True)
spectrograms = (spectrograms - mn) / (mx - mn)
plt.imshow(spectrograms, origin="lower")
plt.title("Multi-bandwidth Spectrogram")
plt.xlabel("Time")
plt.ylabel("Frequency")
plt.show()
"""
Demonstrate a sample wav file.
"""
sample_wav_data = read_wav_file(pd_data["filename"].tolist()[52])
plt.plot(sample_wav_data[:, 0])
plt.show()
"""
Plot a Spectrogram
"""
plot_single_spectrogram(sample_wav_data)
"""
Plot a multi-bandwidth spectrogram
"""
plot_multi_bandwidth_spectrogram(sample_wav_data)
"""
### Define functions to construct a TF Dataset
"""
def read_dataset(df, folds):
msk = df["fold"].isin(folds)
filenames = df["filename"][msk]
targets = df["target"][msk].values
waves = np.array([read_wav_file(fil) for fil in filenames], dtype=np.float32)
return waves, targets
"""
### Create the datasets
"""
train_x, train_y = read_dataset(pd_data, [1, 2, 3])
valid_x, valid_y = read_dataset(pd_data, [4])
test_x, test_y = read_dataset(pd_data, [5])
"""
## Training the Models
In this tutorial we demonstrate the different usecases of the `STFTSpectrogram`
layer.
The first model will use a non-trainable `STFTSpectrogram` layer, so it is
intended purely for preprocessing. Additionally, the model will use 1D signals,
hence it make use of Conv1D layers.
The second model will use a trainable `STFTSpectrogram` layer with the
`expand_dims` option, which expands the shapes to be compatible with image
models.
### Create the 1D model
1. Create a non-trainable spectrograms, extracting a 1D time signal.
2. Apply `Conv1D` layers with `LayerNormalization` simialar to the
classic VGG design.
4. Apply global maximum pooling to have fixed set of features.
5. Add `Dense` layers to make the final predictions based on the features.
"""
model1d = keras.Sequential(
[
layers.InputLayer((None, 1)),
layers.STFTSpectrogram(
mode="log",
frame_length=SAMPLE_RATE * 40 // 1000,
frame_step=SAMPLE_RATE * 15 // 1000,
trainable=False,
),
layers.Conv1D(64, 64, activation="relu"),
layers.Conv1D(128, 16, activation="relu"),
layers.LayerNormalization(),
layers.MaxPooling1D(4),
layers.Conv1D(128, 8, activation="relu"),
layers.Conv1D(256, 8, activation="relu"),
layers.Conv1D(512, 4, activation="relu"),
layers.LayerNormalization(),
layers.Dropout(0.5),
layers.GlobalMaxPooling1D(),
layers.Dense(256, activation="relu"),
layers.Dense(256, activation="relu"),
layers.Dropout(0.5),
layers.Dense(NUM_CLASSES, activation="softmax"),
],
name="model_1d_non_trainble_stft",
)
model1d.compile(
optimizer=keras.optimizers.Adam(1e-5),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
model1d.summary()
"""
Train the model and restore the best weights.
"""
history_model1d = model1d.fit(
train_x,
train_y,
batch_size=BATCH_SIZE,
validation_data=(valid_x, valid_y),
epochs=EPOCHS,
callbacks=[
keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=EPOCHS,
restore_best_weights=True,
)
],
)
"""
### Create the 2D model
1. Create three spectrograms with multiple band-widths from the raw input.
2. Concatenate the three spectrograms to have three channels.
3. Load `MobileNet` and set the weights from the weights trained on `ImageNet`.
4. Apply global maximum pooling to have fixed set of features.
5. Add `Dense` layers to make the final predictions based on the features.
"""
input = layers.Input((None, 1))
spectrograms = [
layers.STFTSpectrogram(
mode="log",
frame_length=SAMPLE_RATE * frame_size // 1000,
frame_step=SAMPLE_RATE * 15 // 1000,
fft_length=2048,
padding="same",
expand_dims=True,
# trainable=True, # trainable by default
)(input)
for frame_size in [30, 40, 50] # frame size in milliseconds
]
multi_spectrograms = layers.Concatenate(axis=-1)(spectrograms)
img_model = keras.applications.MobileNet(include_top=False, pooling="max")
output = img_model(multi_spectrograms)
output = layers.Dropout(0.5)(output)
output = layers.Dense(256, activation="relu")(output)
output = layers.Dense(256, activation="relu")(output)
output = layers.Dense(NUM_CLASSES, activation="softmax")(output)
model2d = keras.Model(input, output, name="model_2d_trainble_stft")
model2d.compile(
optimizer=keras.optimizers.Adam(1e-4),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
model2d.summary()
"""
Train the model and restore the best weights.
"""
history_model2d = model2d.fit(
train_x,
train_y,
batch_size=BATCH_SIZE,
validation_data=(valid_x, valid_y),
epochs=EPOCHS,
callbacks=[
keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=EPOCHS,
restore_best_weights=True,
)
],
)
"""
### Plot Training History
"""
epochs_range = range(EPOCHS)
plt.figure(figsize=(14, 5))
plt.subplot(1, 2, 1)
plt.plot(
epochs_range,
history_model1d.history["accuracy"],
label="Training Accuracy,1D model with non-trainable STFT",
)
plt.plot(
epochs_range,
history_model1d.history["val_accuracy"],
label="Validation Accuracy, 1D model with non-trainable STFT",
)
plt.plot(
epochs_range,
history_model2d.history["accuracy"],
label="Training Accuracy, 2D model with trainable STFT",
)
plt.plot(
epochs_range,
history_model2d.history["val_accuracy"],
label="Validation Accuracy, 2D model with trainable STFT",
)
plt.legend(loc="lower right")
plt.title("Training and Validation Accuracy")
plt.subplot(1, 2, 2)
plt.plot(
epochs_range,
history_model1d.history["loss"],
label="Training Loss,1D model with non-trainable STFT",
)
plt.plot(
epochs_range,
history_model1d.history["val_loss"],
label="Validation Loss, 1D model with non-trainable STFT",
)
plt.plot(
epochs_range,
history_model2d.history["loss"],
label="Training Loss, 2D model with trainable STFT",
)
plt.plot(
epochs_range,
history_model2d.history["val_loss"],
label="Validation Loss, 2D model with trainable STFT",
)
plt.legend(loc="upper right")
plt.title("Training and Validation Loss")
plt.show()
"""
### Evaluate on Test Data
Running the models on the test set.
"""
_, test_acc = model1d.evaluate(test_x, test_y)
print(f"1D model wit non-trainable STFT -> Test Accuracy: {test_acc * 100:.2f}%")
_, test_acc = model2d.evaluate(test_x, test_y)
print(f"2D model with trainable STFT -> Test Accuracy: {test_acc * 100:.2f}%")
|