Audio Data: Music Genre Classification

Audio Data: Music Genre Classification


Audio Data: Music Genre Classification

Generated with DALL•E 3 by OpenAI

Note: This article is an excerpt of my Notebook, Audio Data: Music Genre Classification | Kaggle.

Introduction

In the previous couple of years, we have now seen how Deep Learning has been in a position to convey revolutionary options throughout many industries on duties associated to picture and textual content information. But apart from the deeply explored fields of Natural Language Processing and Computer Vision, deep studying additionally allowed us to discover audio information in a number of methods.

Audio classification is just one amongst a number of functions of Hugging Face’s 🤗Transformers in audio processing. It is especially no that a lot totally different from different classification duties in typical machine studying tasks, the place a number of labels should be assigned to a selected pattern within the dataset.

In audio processing, classification duties is likely to be based mostly on figuring out what’s the language spoken in an audio recording, or detecting key phrases like ❝Hey Siri❞ to begin a dialog together with your private assistant in your cellphone.

Other than that, we even have a number of different examples the place audio processing with Machine Learning might help us on a day-to-day foundation.

• Healthcare: You can analyze cough sounds to detect potential respiratory situations, and even detect stress by vocal patterns.

• Automotive: In-car voice command assists in performing consumer instructions for hands-free operation.

• Smart Homes: Recognizing noises like glass breaking or alarms to detect emergencies. It may also be used for deciphering consumer instructions for a lot of dwelling home equipment.

• Industrial: The evaluation of sounds emitted by machines might help in monitoring potential upkeep requirements earlier than failures occur.

• Communication: Speech-to-Text functions, in addition to Text-to-Speech functions. Noise cancellation may also be used to filter out background noise to enhance communication high quality.

In this pocket book, we’ll stroll by the method of utilizing a pre-trained audio transformers for audio classification duties. We will fine-tune a transformer mannequin to carry out music style classification, the place our mannequin receives a music recording as enter and labels it as genres like pop or rock.

This type of activity may be very current in streaming platforms like Spotify to advocate songs which are much like those the consumer is at present listening to.

The course of you will notice on this pocket book relies on the Hugging Face Audio Course, which is accessible without spending a dime. I extremely counsel you are taking the course for a extra in-depth view into easy methods to work with audio information for deep studying taks.

Audio Data

Before delving into the duty we have now at hand, let’s first discover what precisely we check with when speaking about audio information.

You may already be conversant in the idea of sound waves. These are vibrations that journey by air and are detected by our ears, which in flip assist them to journey to our mind to interpret them as sounds.

The downside with sound waves is that they’re steady indicators consisting of an infinite variety of values over time, which makes it troublesome for digital gadgets to course of and retailer them. To make it simpler to work with them, we use digital illustration of sound waves, that converts these infinite sign values right into a collection of discreet values.

To get to this digital illustration we carry out one thing known as sampling, which is the method of measuring the worth of a steady sign at fastened time samples. The sampling charge/frequency is a measure in hertz (Hz) that describes the variety of samples taken from an audio file in a one-second time-frame . A CD-quality audio, for instance, has a sampling charge of 44,100Hz, which means that 44,100 pattern are taken for each second of the recording.

It is vital to say that each audio instance in a dataset should have the very same sampling charge when engaged on any audio activity. If you intent to make use of customized audio information to fine-tune a pre-trained mannequin, the sampling charge of your information should match the sampling charge of the information the mannequin was pre-trained on. One elementary step of audio information preprocessing known as Resampling, which is precisely the method of constructing the sampling charges throughout the dataset match.

Another vital side of audio information is the amplitude. In digital audio, every audio pattern records the amplitute of the audio wave at a sure cut-off date. The amplitude could be understood because the notion of loudness. It is measured in decilbels (dB) and what it describes is the sound stress ranges at any given instantaneous.

The larger the amplitude, the louder the sound. While a traditional talking voice tends to be beneath 60 dB, a rock live performance could be at round 125 dB.

The Model

For this activity, we’re going to leverage the Transformer structure to work with audio processing. Let’s take a fast recap on what’s the transformer structure.

Transformer structure.
Source: Hugging Face

The authentic Transformer structure consists of an encoder and a decoder. The encoder’s function is to extract and course of understanding from the enter information. In distinction, the decoder generates outputs based mostly on each the information obtained from the encoder and its personal beforehand generated sequences.

The essential component behind the facility of transformer fashions are the consideration layers, which aids the mannequin in being attentive to sure parts within the enter information whereas ignoring what is probably not related sufficient for the duty at hand.

Some transformer-based fashions have a tendency to make use of each the encoder and the decoder, whereas others use solely one of many two. Encoder-only fashions is likely to be good for duties that require a deeper understanding of the enter information, comparable to classification duties. Decoder-only fashions are usually superb on the activity of producing texts, comparable to summarization or translation.

Even although the unique Transformer structure was designed to work with textual content information, we have already got many architectures designed to work with audio information. These fashions might differ on the kind of audio information they take as enter and the nuances inside their functioning. Overall, nonetheless, they have an inclination to comply with a really related method to that of the unique Transformer.

Transformer structure for audio enter.
Source: Hugging Face

For our particular activity, which is concentrated on labeling the genres of the music performed in an audio file, we’ll want a mannequin that takes audio as enter and provides us as output what’s the most possible style/label to that music.

The HuBERT mannequin, proposed within the 2021 analysis paper HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units by Hsu et al., is an encoder-only mannequin that’s perfect for the duty of audio classification.

As the identify suggests, HuBERT works very carefully with how the BERT mannequin works. The essential thought is to masks sure elements of the enter audio, and the mannequin is skilled to discover ways to predict these masked segments. It additionally makes use of cluster ensembles to generate pseudo labels that assist in guiding the educational course of in predicting the masked elements.

The Dataset

In this pocket book, we’re going to use the GTZAN dataset to fine-tune the mannequin.

Briefly introducing, this dataset comprises over 500 samples of 30-seconds lengthy audio information consisting of music from a number of genres.

Exploratory Data Analysis

The exploratory evaluation of audio information is sort of totally different from what you normally carry out on different varieties of information. If I migh say so, this can be very attention-grabbing and fairly enjoyable to do it. Did you recognize that you would see sound? Well, that is exactly what we’re going to do right here.

Let’s begin through the use of the 🤗 Datasets library to load our information.

# Loading information with the Datasets lib
df = load_dataset("marsyas/gtzan")
DatasetDict({
practice: Dataset({
options: ['file', 'audio', 'genre'],
num_rows: 999
})
})

ou can see that this dataset is just not divided into coaching and validation units, which means we should break up it afterward. Overall, we have now three diferent options, and num_rows tells us that we have now 999 audio information.

Let’s begin by making a validation set, so we will discover the coaching set.

# Splitting information into coaching and validation
df = df['train'].train_test_split(seed = seed, shuffle = True,
test_size = .2)

With shuffle = True we be certain that samples are break up into coaching and take a look at randomly. With test_size = .2 we guarantee to make use of 80% of the information for coaching and 20% of it for validation.

Let’s see the dataset once more.

DatasetDict({
practice: Dataset({
options: ['file', 'audio', 'genre'],
num_rows: 799
})
take a look at: Dataset({
options: ['file', 'audio', 'genre'],
num_rows: 200
})
})

Now we have now a practice dataset with 799 samples and a take a look at dataset with 200 samples. Let’s check out one of many audio information.

# Picking the third file within the coaching dataset
print("file:", df['train'][2]['file'])
print('n')
print("audio: ", df['train'][2]['audio'])
print('n')
print("style:", df['train'][2]['genre'])
print('n')
file: /root/.cache/huggingface/datasets/downloads/extracted/5022b0984afa7334ff9a3c60566280b08b5179d4ac96a628052bada7d8940244/genres/disco/disco.00088.wav


audio: {'path': '/root/.cache/huggingface/datasets/downloads/extracted/5022b0984afa7334ff9a3c60566280b08b5179d4ac96a628052bada7d8940244/genres/disco/disco.00088.wav', 'array': array([ 0.03372192, 0.05703735, 0.06817627, ..., -0.00717163,
0.00860596, 0.02481079], dtype=float32), 'sampling_rate': 22050}


style: 3

We can se that file describes the audio path, whereas audio comprises some extra data.

Besides the trail, we will additionally see that the audio information are represented as 1-dimensional arrays, the place the worth of the array represents the amplitude at that specific timestep.

This explicit music has a sampling charge of twenty-two,050 Hz. We will verify afterward if all information are inside that very same sampling charge or not.

The music style is at present represented as an integer. Let’s repair that and procure their labels in a format that’s human-readable.

# Obtaining human-readable label
id2label_function = df['train'].options['genre'].int2str

print("style: ", id2label_function(df['train'][2]['genre']))
style:  disco

We can see that the id 3 refers back to the disco style.

Let’s examine if all sampling charges is identical throughout the dataset.

# Initializing variables
sampling_rate_check = None
all_same = True

# Iterating by every pattern
for set_name in ['train', 'test']: # Iterating by each units
for pattern in df[set_name]:
sampling_rate = pattern['audio']['sampling_rate']

if sampling_rate_check is None:
sampling_rate_check = sampling_rate
else:
if sampling_rate != sampling_rate_check:
all_same = False
break

# Printing outcome
if all_same:
print(f"All samples have the identical sampling charge: {sampling_rate_check} Hz")
else:
print("The samples within the dataframe have totally different sampling charges.")
All samples have the identical sampling charge: 22050 Hz

We have a affirmation that each one audio information in each units share the identical 22,050 Hz sampling charge.

Let’s now depend the labels.

labels = {} # Initializing empty checklist

# Defining a operate to depend labels
def count_genres(df):
for pattern in df:
genre_label = id2label_function(pattern['genre'])

if genre_label in labels:
labels[genre_label] += 1

else:
labels[genre_label] = 1

# Counting labels in each units
count_genres(df['train'])
count_genres(df['test'])

# Obtaining genres and depend values
genres = checklist(labels.keys())
counts = checklist(labels.values())

# Plotting bar plot
fig = px.bar(x = genres, y = counts, textual content = counts)
fig.update_traces(marker=dict(shade="#4682B4"))
fig.update_layout(title = '<b>Genre Counts</b>', showlegend = True, top = 500, width = 750,
plot_bgcolor=bg_color,paper_bgcolor=paper_color)
fig.update_yaxes(title_text = '<b>Count</b>')
fig.update_xaxes(title = '<b>Genres</b>')

fig.present()
Genre Counts Barplot

Overall we have now 100 samples for Rock, Disco, Country, Classical Music, Blues, Reggae, HipHop, Pop, and Metal. Jazz is the one style with solely 99 samples, this is because of a corrupted file that was faraway from the dataset.

After acquiring a bit extra of perception in regards to the information, we will now begin the method of “seeing” our information, as I’ve talked about earlier than. The extra environment friendly method of doing that is by waveforms, which could be plotted utilizing the librosa library.

A waveform illustrates adjustments within the amplitude of sound over time. In the x-axis we have now the time characteristic, whereas within the y-axis we have now amplitude values in a [−1.00,1.00][−1.00,1.00] vary. Let’s check out some examples, take heed to the information, and verify their genres to see how they differ from each other.

Note: You can take heed to the audio information on Kaggle!

style: disco
style: reggae
style: rock
style: metallic

Right above, we have now 4 audio information from totally different genres: disco, reggae, rock, and metallic. By wanting on the waveforms, you possibly can observe that the reggae instance appears to be the quieter, with an amplitude starting from -0.75 to 0.75 and lesser peaks to the acute values of the vary all through the excerpt.

The disco excerpt appears to be the one with the best peaks of amplitude, reaching the utmost of -1.00 and 1.00. This could possibly be an indication of clipping—a distortion that happens every time a sign exceeds the utmost stage that may be precisely recorded.

If you take heed to the metallic excerpt whereas listening to the audio, you’ll discover the music will get considerably quieter across the 13-second time-frame, which is precisely captured within the waveform when there is a sudden discount within the vary of the peaks.

Audio Preprocessing

After analysing the information, we should put together it for use as enter for fine-tuning our mannequin. Similar to the tokenization course of in Natural Language Processing, audio fashions require the enter to be encoded in a format that the mannequin can perceive.

Luckily, the 🤗 Transformers library has a category known as AutoFeatureExtractor that’s environment friendly in deciding on the proper characteristic extractor for any given mannequin.

As I’ve talked about within the introduction, we’re going to use the HuBERT mannequin for this activity. However, I’ll use the DistilHuBERT mannequin, which is a a lot smaller — thus distilled — model of the unique mannequin.

# Loading mannequin
mannequin = "ntu-spml/distilhubert"

# Instantiating characteristic extractor
feature_extractor = AutoFeatureExtractor.from_pretrained(mannequin, do_normalize = True, return_attention_mask = True)

We want to make sure that the sampling charge of the mannequin matches the 22,050 Hz sampling charge of the dataset. We can use feature_extractor to verify the sampling charge of the mannequin.

# Checking sampling charge
sampling_rate = feature_extractor.sampling_rate
print(f'DistilHuBERT Sampling Rate: {sampling_rate} Hz')
DistilHuBERT Sampling Rate: 16000 Hz

We have totally different sampling charges. This is just not an enormous problem. Let’s simply use the cast_column() methodology from the 🤗 Datasets library to resample our information.

from datasets import Audio

# Resampling information
df = df.cast_column("audio", Audio(sampling_rate = 16000))
* * * Dataset After Resampling* * *




file: /root/.cache/huggingface/datasets/downloads/extracted/5022b0984afa7334ff9a3c60566280b08b5179d4ac96a628052bada7d8940244/genres/disco/disco.00088.wav


audio: {'path': '/root/.cache/huggingface/datasets/downloads/extracted/5022b0984afa7334ff9a3c60566280b08b5179d4ac96a628052bada7d8940244/genres/disco/disco.00088.wav', 'array': array([ 0.03352892, 0.05795968, 0.09609947, ..., -0.03805662,
0.00101842, 0.01898582], dtype=float32), 'sampling_rate': 16000}


style: 3

You can now see that sampling_rate: 16000. Our resampling methodology was profitable.

As you possibly can see within the output above, the audio information is represented as a one-dimensional array ([ 0.03352892, 0.05795968, 0.09609947, ..., -0.03805662,0.00101842, 0.01898582], dtype=float32). For our mannequin to converge throughout coaching, we should be certain that all inputs are throughout the identical vary. We might want to normalize our information by rescaling every pattern to have imply 0 and variance 1.

Let’s check out one instance within the dataset.

# Computing imply and variance 
pattern = df['train'][9]['audio']

print('nExample Data:n')
print(f" Mean: {np.imply(pattern['array']):.3}n")
print(f" Variance: {np.var(pattern['array']):.3}n")
Example Data:

Mean: -2.12e-05

Variance: 0.0301

Our imply is extraordinarily near 0.0, however the variance is just not even near 1.0. We can apply feature_extractor to normalize the information.

# Normalizing audio information
inputs = feature_extractor(pattern['array'], sampling_rate = pattern['sampling_rate'])

print(f"nInputs Keys: {checklist(inputs.keys())}n")

print(
f" Mean: {np.imply(inputs['input_values']):.3}, Variance: {np.var(inputs['input_values']):.3}"
)
Inputs Keys: ['input_values', 'attention_mask']

Mean: 1.15e-09, Variance: 1.0

Success! We now have variance 1.0.

By appling feature_extractor, we get hold of a dictionary of two arrays: input_values and attention_mask. The input_values array comprises the preprocessed audio inputs that we’ll move to our HuBERT mannequin.

linkcode

By now, we have now solely utilized the normalization to 1 single pattern. Let’s construct a preprocessing operate, so we will carry out the steps above to the whole dataset without delay.

# Defining audio most length
max_duration = 30.0 # 30 seconds

def preprocess_function(examples):
# Extracting and saving arrays
audio_arrays = [x['array'] for x in examples['audio']]

# Preprocessing audio inputs
inputs = feature_extractor(audio_arrays,
sampling_rate = feature_extractor.sampling_rate,
max_length = int(feature_extractor.sampling_rate * max_duration),
truncation = True,
return_attention_mask = True)

return inputs

Let’s use the map( ) methodology to use the operate above to the dataset. We will take away some columns that won’t be used throughout coaching and validation, in addition to outline a batch dimension.

# Preprocessing information
df = df.map(preprocess_function,
remove_columns = ['audio', 'file'],
batched = True,
batch_size = 100,
num_proc = 1)

📝 The `batch_size` parameter is vital to outline the height RAM utilization. If the code above exhaust your system’s RAM, you possibly can iteratively cut back it by an element of two till it really works tremendous for you.

After preprocessing the dataset, we’re left with three options:

• style: This is the goal variable. This comprises all of the style labels we’ll fine-tune our mannequin to categorise audio information.

• input_values: This comprises the encoded audio information, so the HuBERT mannequin can precisely perceive the information it receives.

• attention_mask: This characteristic consists of binary 0 and 1 values that indicade the place we have now padded the audio enter.

To allow the Trainer class to course of labels, we should rename this column to label.

# Renaming style column
df = df.rename_column('style', 'label')

The final step in our preprocessing journey is mapping our style labels from integer IDs to human-readable descriptions(e.g., 7 -> pop) and vice-versa. This could be simply executed through the use of the int2str( ) methodology

# Id to label
id2label = {str(i): id2label_function(i)
for i in vary(len(df['train'].options['label'].names))}

# Label to id
label2id = {v: ok for ok, v in id2label.gadgets()}

Let’s take a look at it.

integer = 7 # Defining a random int
label = id2label[str(integer)] # Obtaining label

print(f'nId: {integer}')
print(f'nLabel: {label}')
Id: 7

Label: pop

It is working as supposed.

Fine-tuning HuBERT

The information is preprocessed and prepared for use for fine-tuning the HuBERT mannequin for the duty of music style classification.

For this activity, we’re going to use 🤗 Transformers’ Trainer and TrainingArguments.

Let’s go forward and use AutoModelForAudioClassification to load our mannequin with the suitable classification head for this activity and visualize its structure.

num_labels = len(id2label) # Obtaining the entire variety of labels

# Loading mannequin
hubert_model = AutoModelForAudioClassification.from_pretrained(mannequin,
num_labels = num_labels,
label2id=label2id,
id2label=id2label)

# Visualizing mannequin's structure
print('nHuBERT Architecture')
print(hubert_model)
HuBERT Architecture
HubertForSequenceClassification(
(hubert): HubertModel(
(feature_extractor): HubertFeatureEncoder(
(conv_layers): ModuleList(
(0): HubertGroupNormConvLayer(
(conv): Conv1d(1, 512, kernel_size=(10,), stride=(5,), bias=False)
(activation): GELUActivation()
(layer_norm): GroupNorm(512, 512, eps=1e-05, affine=True)
)
(1-4): 4 x HubertNoLayerNormConvLayer(
(conv): Conv1d(512, 512, kernel_size=(3,), stride=(2,), bias=False)
(activation): GELUActivation()
)
(5-6): 2 x HubertNoLayerNormConvLayer(
(conv): Conv1d(512, 512, kernel_size=(2,), stride=(2,), bias=False)
(activation): GELUActivation()
)
)
)
(feature_projection): HubertFeatureProjection(
(projection): Linear(in_features=512, out_features=768, bias=True)
(dropout): Dropout(p=0.0, inplace=False)
)
(encoder): HubertEncoder(
(pos_conv_embed): HubertPositionalConvEmbedding(
(conv): Conv1d(768, 768, kernel_size=(128,), stride=(1,), padding=(64,), teams=16)
(padding): HubertSamePadLayer()
(activation): GELUActivation()
)
(layer_norm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(dropout): Dropout(p=0.1, inplace=False)
(layers): ModuleList(
(0-1): 2 x HubertEncoderLayer(
(consideration): HubertAttention(
(k_proj): Linear(in_features=768, out_features=768, bias=True)
(v_proj): Linear(in_features=768, out_features=768, bias=True)
(q_proj): Linear(in_features=768, out_features=768, bias=True)
(out_proj): Linear(in_features=768, out_features=768, bias=True)
)
(dropout): Dropout(p=0.1, inplace=False)
(layer_norm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
(feed_forward): HubertFeedForward(
(intermediate_dropout): Dropout(p=0.1, inplace=False)
(intermediate_dense): Linear(in_features=768, out_features=3072, bias=True)
(intermediate_act_fn): GELUActivation()
(output_dense): Linear(in_features=3072, out_features=768, bias=True)
(output_dropout): Dropout(p=0.1, inplace=False)
)
(final_layer_norm): LayerNorm((768,), eps=1e-05, elementwise_affine=True)
)
)
)
)
(projector): Linear(in_features=768, out_features=256, bias=True)
(classifier): Linear(in_features=256, out_features=10, bias=True)
)

I’ll now set the coaching arguments and outline a operate for accuracy computing. We can then begin the fine-tuning course of.

# Setting coaching arguments
training_args = TrainingArguments(
output_dir = 'hubert_gtzan',
evaluation_strategy = 'epoch',
save_strategy = 'epoch',
load_best_model_at_end = True,
metric_for_best_model = 'accuracy',
learning_rate = 5e-5,
seed = seed,
per_device_train_batch_size = 8,
per_device_eval_batch_size = 8,
gradient_accumulation_steps = 1,
num_train_epochs = 15,
warmup_ratio = 0.1,
fp16 = True,
save_total_limit = 2,
report_to = 'none'
)

📝 If you encounter a CUDA out-of-memory error throughout coaching, you possibly can cut back `batch_size` and improve `gradient_acumulation_steps` to resolve the issue.

# Loading `accuracy` metric from the consider library
metric = consider.load('accuracy')
# Creating operate to compute accuracy
def compute_metrics(eval_pred):
predictions = np.argmax(eval_pred.predictions, axis = 1)
return metric.compute(predictions = predictions, references = eval_pred.label_ids)
# Setting coach
coach = Trainer(
mannequin=hubert_model,
args = training_args,
train_dataset = df['train'],
eval_dataset = df['test'],
tokenizer = feature_extractor,
compute_metrics = compute_metrics)

coach.practice()

Our finest analysis accuracy is 78.5%. We can now save our mannequin and the characteristic extractor for additional use, mannequin deploy, and even add on Hugging Face Models so others can fine-tune it even additional on their very own duties and information.

# Saving mannequin & characteristic extractor
listing = 'fine_tuned_hubert'
coach.save_model(listing)
feature_extractor.save_pretrained(listing)

The mannequin skilled on this pocket book has been uploaded to Hugging Face and you should use it in your personal functions. Just click on on luisotorres/hubert_gtzan to verify it.

You may also load it on an audio-classification pipeline to check it utilizing your personal customized audios.

Conclusion

In this pocket book, we have now explored the small print behind audio processing and the way Transformer architectures could be effectively utilized in a number of audio duties.

More particularly, we have now employed the comfort of the 🤗 Transformers library to fine-tune a distilled model of the HuBERT mannequin on the GTZAN dataset for the duty of audio classification.

I actually hope this pocket book serves as introduction for these considering leveraging deep studying frameworks for working with audio information, in addition to supply for individuals who are veterans looking for refining their data on the topic.

Feel free to go away your feedback, options, and concepts. Your suggestions is extremely appreciated!

If you just like the content material introduced on this pocket book, your upvote can be extraordinarily appreciated.

Thank you!

HI-FI News

through Machine Learning on Medium https://ift.tt/k3aoCpG

November 28, 2023 at 10:22PM