vector listlengths 1.02k 1.02k | text stringlengths 2 11.8k |
|---|---|
[
0.015501777,
0.006493011,
0.00865078,
0.041644603,
0.003335181,
-0.050393913,
-0.03912228,
0.016198043,
0.011652607,
0.040015604,
0.0036291236,
0.0031693252,
0.070625044,
-0.039201103,
-0.011054869,
0.0029903322,
0.023016198,
-0.059747525,
-0.058013428,
-0.02821849,
-0.024737... | print(train_dataset.num_videos, val_dataset.num_videos, test_dataset.num_videos)
(300, 30, 75)
Visualize the preprocessed video for better debugging |
[
0.020610109,
0.03080819,
0.0114888875,
-0.0076378635,
-0.03754035,
-0.04712512,
-0.03380343,
0.017515026,
-0.02183673,
0.07171462,
0.015575252,
-0.0151758855,
0.047039542,
-0.031578396,
-0.0022517792,
0.025873173,
-0.029610094,
-0.0658953,
-0.031721026,
-0.0028133867,
0.03246... |
import imageio
import numpy as np
from IPython.display import Image
def unnormalize_img(img):
"""Un-normalizes the image pixels."""
img = (img * std) + mean
img = (img * 255).astype("uint8")
return img.clip(0, 255)
def create_gif(video_tensor, filename="sample.gif"):
"""Prepares a GIF from a ... |
[
0.04314803,
0.038616765,
0.010101546,
0.030304637,
-0.0521817,
-0.015974874,
-0.020015491,
0.031141622,
0.0040622647,
0.03293104,
0.033768024,
0.01852912,
0.03627898,
-0.046928894,
-0.008456437,
0.044187047,
0.003488641,
-0.047506128,
-0.07492461,
0.0073164054,
0.026942266,
... |
from transformers import TrainingArguments, Trainer
model_name = model_ckpt.split("/")[-1]
new_model_name = f"{model_name}-finetuned-ucf101-subset"
num_epochs = 4
args = TrainingArguments(
new_model_name,
remove_unused_columns=False,
evaluation_strategy="epoch",
save_strategy="epoch",
learnin... |
[
0.036855955,
0.042950016,
-0.019433934,
-0.004381018,
-0.039859246,
-0.0019135063,
-0.009753414,
0.010854136,
0.0051682894,
0.031520005,
0.030528625,
0.01643064,
0.03224896,
-0.03790565,
0.025338467,
0.049743872,
0.0018633907,
-0.015191417,
-0.059890926,
0.004257096,
0.016561... |
Train the model
Leverage Trainer from 🤗 Transformers for training the model. To instantiate a Trainer, you need to define the training configuration and an evaluation metric. The most important is the TrainingArguments, which is a class that contains all the attributes to configure the training. It requires an outp... |
[
-0.004773214,
0.01787773,
-0.022780139,
0.0021997988,
-0.044359118,
-0.0050560455,
-0.005209682,
-0.0061873705,
0.0018191987,
0.033828016,
0.02997313,
0.0041272417,
-0.008079896,
-0.030420074,
0.006281648,
0.03354868,
-0.016131857,
-0.03575546,
-0.064471565,
-0.022933776,
0.0... | import evaluate
metric = evaluate.load("accuracy")
def compute_metrics(eval_pred):
predictions = np.argmax(eval_pred.predictions, axis=1)
return metric.compute(predictions=predictions, references=eval_pred.label_ids) |
[
0.027491733,
0.0021539575,
0.0020096295,
0.006017927,
-0.023794014,
-0.019248597,
-0.02993252,
-0.0046038786,
0.019277828,
0.046769563,
0.011553544,
0.0105816135,
0.03148176,
-0.02889482,
0.0038950276,
0.026731728,
-0.026220186,
-0.08950525,
-0.049078807,
0.006076389,
0.03449... | A note on evaluation:
In the VideoMAE paper, the authors use the following evaluation strategy. They evaluate the model on several clips from test videos and apply different crops to those clips and report the aggregate score. However, in the interest of simplicity and brevity, we don't consider that in this tutorial.
... |
[
0.048081357,
0.013898967,
-0.010328854,
0.05119081,
-0.032908376,
-0.014237264,
-0.021204742,
0.04839806,
0.015086605,
0.047131248,
0.05237125,
-0.00015733959,
0.021881336,
-0.0584462,
-0.025796944,
0.034060027,
-0.0006855912,
-0.024328591,
-0.023738371,
0.022802655,
0.036334... | The dataset returned by pytorchvideo.data.Ucf101() doesn't implement the __len__ method. As such, we must define max_steps when instantiating TrainingArguments.
Next, you need to define a function to compute the metrics from the predictions, which will use the metric you'll load now. The only preprocessing you have to... |
[
0.018045466,
0.028331522,
0.00087759376,
-0.0019484825,
-0.035400596,
-0.035787184,
0.029518904,
0.030982424,
0.00048108015,
0.0339923,
-0.0020209681,
0.0201441,
0.02494886,
-0.04161365,
0.003589764,
0.043629438,
-0.010934973,
-0.060308035,
-0.083116844,
-0.022781195,
-0.0064... | Then you just pass all of this along with the datasets to Trainer:
trainer = Trainer(
model,
args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
tokenizer=image_processor,
compute_metrics=compute_metrics,
data_collator=collate_fn,
) |
[
0.045295488,
0.013045838,
-0.030669412,
-0.011947464,
-0.022137532,
-0.036338434,
-0.0064414265,
-0.0012436418,
0.0050206278,
0.029025394,
-0.0051162927,
0.010572727,
0.016851168,
-0.041780695,
-0.008390153,
0.016397648,
0.0042446805,
-0.045493905,
-0.0707494,
0.006646929,
0.... | You might wonder why you passed along the image_processor as a tokenizer when you preprocessed the data already. This is only to make sure the image processor configuration file (stored as JSON) will also be uploaded to the repo on the Hub.
Now fine-tune our model by calling the train method:
train_results = trainer... |
[
0.014582506,
-0.010402669,
0.018336419,
0.017513445,
-0.03840541,
-0.050764445,
-0.00040246273,
0.01579531,
0.0077677113,
0.03918507,
0.034478243,
0.014149362,
0.031128597,
-0.027389122,
0.002008704,
0.03257241,
-0.02055989,
-0.0647983,
-0.05189062,
-0.019144954,
0.005147191,... | def collate_fn(examples):
# permute to (num_frames, num_channels, height, width)
pixel_values = torch.stack(
[example["video"].permute(1, 0, 2, 3) for example in examples]
)
labels = torch.tensor([example["label"] for example in examples])
return {"pixel_values": pixel_values, "labels"... |
[
-0.009965809,
0.006834635,
-0.001789763,
0.027571829,
-0.0032788021,
-0.022541538,
-0.0108989645,
0.016753057,
0.02391211,
0.06415444,
-0.009958519,
-0.014638877,
0.06129665,
-0.057972282,
-0.030094264,
0.027644731,
-0.019537942,
-0.06450437,
-0.080776274,
0.0031275288,
0.037... | from transformers import pipeline
video_cls = pipeline(model="my_awesome_video_cls_model")
video_cls("https://huggingface.co/datasets/sayakpaul/ucf101-subset/resolve/main/v_BasketballDunk_g14_c06.avi")
[{'score': 0.9272987842559814, 'label': 'BasketballDunk'},
{'score': 0.017777055501937866, 'label': 'BabyCrawling'},
... |
[
0.016245414,
-0.015929034,
-0.027414996,
-0.0024192736,
-0.012675825,
0.008335919,
-0.037828017,
0.026906038,
0.030647572,
0.06377116,
0.031527933,
-0.022504231,
0.03147291,
-0.05350945,
-0.009855918,
0.035847206,
-0.0046081403,
-0.05590293,
-0.030427482,
-0.026300788,
0.0021... | You can also manually replicate the results of the pipeline if you'd like.
def run_inference(model, video):
# (num_frames, num_channels, height, width)
perumuted_sample_test_video = video.permute(1, 0, 2, 3)
inputs = {
"pixel_values": perumuted_sample_test_video.unsqueeze(0),
"labels":... |
[
0.029039612,
0.021807471,
-0.044531107,
-0.007877619,
-0.043975856,
-0.0070933276,
-0.035536043,
0.021515965,
0.028262261,
0.034536593,
0.006704652,
0.01686574,
0.009161636,
-0.030399976,
0.0115006305,
0.023598155,
0.013659167,
-0.030150114,
-0.04247668,
0.008675792,
-0.00538... | train_results = trainer.train()
Once training is completed, share your model to the Hub with the [~transformers.Trainer.push_to_hub] method so everyone can use your model:
trainer.push_to_hub()
Inference
Great, now that you have fine-tuned a model, you can use it for inference!
Load a video for inference:
sample_... |
[
0.032536954,
0.015683895,
-0.028544689,
0.018621061,
-0.013202989,
-0.020160934,
-0.006744075,
0.05215608,
0.0021101967,
0.056205377,
0.012611277,
0.022784423,
0.017950932,
-0.04545478,
-0.019276934,
0.03330689,
0.00093925145,
-0.05192795,
-0.045483295,
-0.0051685562,
0.04437... | Now, pass your input to the model and return the logits:
logits = run_inference(trained_model, sample_test_video["video"])
Decoding the logits, we get:
predicted_class_idx = logits.argmax(-1).item()
print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: BasketballDunk
``` |
[
0.018777031,
0.019730607,
-0.030626614,
-0.011702339,
-0.051661376,
0.0042700567,
-0.05317588,
0.021511551,
0.020866485,
0.055784192,
0.017430807,
-0.015804118,
0.033178832,
-0.027793933,
0.015299284,
0.023180308,
0.004827478,
-0.045014393,
-0.048520185,
0.0061421506,
0.01319... | trainer.push_to_hub()
Inference
Great, now that you have fine-tuned a model, you can use it for inference!
Load a video for inference:
sample_test_video = next(iter(test_dataset))
The simplest way to try out your fine-tuned model for inference is to use it in a pipeline. Instantiate a pipeline for video classifica... |
[
0.036603402,
0.00075220986,
-0.035836093,
0.013292889,
-0.029470285,
0.026429474,
-0.0129944915,
0.025576912,
0.0025186152,
0.071672186,
0.014486479,
0.035978187,
0.01619871,
-0.06712518,
-0.0050905156,
0.03759806,
0.0031225146,
-0.035978187,
-0.040667288,
-0.0029200306,
0.03... | device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
inputs = {k: v.to(device) for k, v in inputs.items()}
model = model.to(device)
# forward pass
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
return logits
Now, pass your input to th... |
[
0.018758876,
-0.00053868396,
-0.031955276,
-0.024640039,
0.005356058,
-0.032418817,
-0.040936362,
-0.016296322,
0.00028043255,
0.027783418,
0.0152099,
0.0073550735,
0.021612544,
-0.030593628,
0.010118205,
0.019961184,
-0.015789324,
-0.0027414034,
-0.0502651,
0.009517052,
-0.0... |
For more examples on what Bark and other pretrained TTS models can do, refer to our
Audio course.
If you are looking to fine-tune a TTS model, the only text-to-speech models currently available in 🤗 Transformers
are SpeechT5 and FastSpeech2Conformer, though more will be added in the future. SpeechT5 is pre-traine... |
[
0.028356485,
0.04453973,
-0.042019155,
-0.00015675282,
-0.000963118,
-0.037207145,
0.029845918,
-0.030017775,
-0.009359073,
0.017285999,
-0.021066863,
-0.0278982,
0.032395136,
-0.06456113,
0.018947288,
0.04422466,
-0.035058927,
-0.058116473,
-0.04030058,
-0.029559487,
0.01195... | pip install datasets soundfile speechbrain accelerate
Install 🤗Transformers from source as not all the SpeechT5 features have been merged into an official release yet:
pip install git+https://github.com/huggingface/transformers.git
To follow this guide you will need a GPU. If you're working in a notebook, run the fo... |
[
-0.001397087,
0.0012988611,
-0.04052517,
-0.0049744365,
0.020739682,
-0.05618517,
-0.04139517,
-0.012846535,
0.0007463409,
0.02694194,
-0.038308073,
0.007166977,
-0.006195243,
-0.03477194,
-0.012488713,
-0.01278339,
-0.03791517,
-0.026464844,
-0.030421942,
-0.006121574,
-0.03... |
Text to speech
[[open-in-colab]]
Text-to-speech (TTS) is the task of creating natural-sounding speech from text, where the speech can be generated in multiple
languages and for multiple speakers. Several text-to-speech models are currently available in 🤗 Transformers, such as
Bark, MMS, VITS and SpeechT5.
You can ... |
[
0.03411154,
0.022866936,
-0.014978279,
0.020455303,
0.0046634604,
-0.025874214,
0.077346615,
-0.00537896,
0.014825736,
0.052823495,
-0.012893523,
-0.0042421506,
0.008375342,
-0.057065643,
0.0009815422,
0.027196255,
0.012232503,
-0.06462016,
-0.04323507,
-0.0068099597,
-0.0008... | To follow this guide you will need a GPU. If you're working in a notebook, run the following line to check if a GPU is available:
!nvidia-smi
or alternatively for AMD GPUs:
!rocm-smi
We encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your ... |
[
0.004104012,
0.01835665,
-0.008933952,
-0.00855302,
-0.010881741,
-0.050886873,
-0.036742046,
-0.006044613,
0.027858406,
0.05752804,
-0.006752573,
-0.017982904,
0.031480864,
-0.025659058,
-0.008208024,
0.020311626,
-0.02932464,
-0.052123107,
-0.0487594,
0.006996945,
-0.015769... | from transformers import pipeline
pipe = pipeline("text-to-speech", model="suno/bark-small")
text = "[clears throat] This is a test and I just took a long pause."
output = pipe(text)
Here's a code snippet you can use to listen to the resulting audio in a notebook:
thon
from IPython.display import Audio
Audio(output... |
[
0.04380511,
-0.0052071186,
-0.05022057,
0.0073153665,
-0.008476536,
-0.0051817177,
-0.02984205,
-0.040205486,
-0.020480122,
0.016778896,
0.004143923,
-0.022004157,
0.013469564,
-0.047666,
0.013578423,
0.0083604185,
-0.027243935,
-0.0469693,
-0.061716147,
-0.013026868,
-0.0142... | Fine-tune SpeechT5 that was originally trained on English speech on the Dutch (nl) language subset of the VoxPopuli dataset.
Use your refined model for inference in one of two ways: using a pipeline or directly.
Before you begin, make sure you have all the necessary libraries installed:
pip install datasets soundfile... |
[
-0.0018901398,
-0.0044461037,
0.011366308,
0.04546523,
-0.010660461,
-0.022776276,
-0.022004938,
-0.029252596,
-0.01500469,
0.014480763,
-0.045028623,
0.011882958,
-0.0005225627,
-0.01579058,
-0.036383826,
0.0033363968,
-0.055623595,
-0.06613124,
-0.062871255,
-0.012472375,
-... | from transformers import SpeechT5Processor
checkpoint = "microsoft/speecht5_tts"
processor = SpeechT5Processor.from_pretrained(checkpoint)
Text cleanup for SpeechT5 tokenization
Start by cleaning up the text data. You'll need the tokenizer part of the processor to process the text:
tokenizer = processor.tokenizer |
[
0.030569151,
0.012368814,
0.009923567,
0.04819204,
-0.008176963,
-0.035644997,
0.03960872,
0.008397962,
-0.01689573,
0.06581493,
0.008012996,
0.010843208,
0.011320852,
-0.055264004,
-0.07243063,
-0.0019586927,
-0.020816678,
-0.019561974,
-0.028829675,
-0.006109553,
-0.0010158... | def extract_all_chars(batch):
all_text = " ".join(batch["normalized_text"])
vocab = list(set(all_text))
return {"vocab": [vocab], "all_text": [all_text]}
vocabs = dataset.map(
extract_all_chars,
batched=True,
batch_size=-1,
keep_in_memory=True,
remove_columns=dataset.column_names... |
[
0.02084422,
-0.005813447,
-0.008223015,
0.054897517,
0.028493874,
-0.012396214,
-0.023427973,
-0.014384833,
0.007903675,
0.00067542307,
0.0054070135,
-0.0152122155,
-0.003193404,
-0.048975203,
0.01288974,
-0.01737502,
-0.006876705,
-0.014246937,
-0.029089008,
-0.045201182,
-0... |
Load the dataset
VoxPopuli is a large-scale multilingual speech corpus consisting of
data sourced from 2009-2020 European Parliament event recordings. It contains labelled audio-transcription data for 15
European languages. In this guide, we are using the Dutch language subset, feel free to pick another subset.
No... |
[
0.0385334,
0.025684005,
0.010106515,
0.025107333,
0.0025432636,
-0.030430444,
-0.014039702,
-0.027561879,
-0.015022999,
0.012738497,
0.014779023,
-0.018985758,
0.047050375,
-0.025151692,
0.009211937,
0.02058269,
-0.05556735,
-0.04592661,
-0.06417304,
-0.02779846,
-0.008716592... | from datasets import load_dataset, Audio
dataset = load_dataset("facebook/voxpopuli", "nl", split="train")
len(dataset)
20968
20968 examples should be sufficient for fine-tuning. SpeechT5 expects audio data to have a sampling rate of 16 kHz, so
make sure the examples in the dataset meet this requirement:
py
dataset =... |
[
0.053916525,
0.019465609,
-0.0064681484,
0.03192788,
-0.03682104,
-0.0031977578,
-0.015658118,
-0.019159786,
-0.037555017,
0.051592276,
0.019924343,
0.011514221,
0.0074123754,
-0.02041366,
-0.03149973,
0.0042509343,
-0.041010812,
-0.035261348,
-0.044069037,
-0.018486977,
-0.0... |
The dataset examples contain raw_text and normalized_text features. When deciding which feature to use as the text input,
consider that the SpeechT5 tokenizer doesn't have any tokens for numbers. In normalized_text the numbers are written
out as text. Thus, it is a better fit, and we recommend using normalized_t... |
[
0.00287536,
0.010022288,
0.03685437,
0.021219604,
-0.026362073,
-0.019754276,
0.0014532318,
-0.00593043,
-0.016187724,
0.050567627,
0.014038115,
0.0056643207,
0.021468433,
-0.037434973,
-0.07221577,
-0.033232525,
-0.038789712,
-0.033785477,
-0.038762063,
-0.02250522,
0.003849... | replacements = [
("à", "a"),
("ç", "c"),
("è", "e"),
("ë", "e"),
("í", "i"),
("ï", "i"),
("ö", "o"),
("ü", "u"),
]
def cleanup_text(inputs):
for src, dst in replacements:
inputs["normalized_text"] = inputs["normalized_text"].replace(src, dst)
return inputs
dat... |
[
0.01655334,
-0.009335971,
-0.014159321,
0.03395412,
0.027894922,
-0.036637682,
-0.017683262,
0.018064609,
0.0033367975,
0.013163578,
0.04112912,
-0.020649303,
0.018742561,
0.014844336,
0.0056460733,
-0.0032732396,
-0.010155164,
-0.011638185,
-0.034236602,
-0.04200481,
-0.0333... |
Now that you have dealt with special characters in the text, it's time to shift focus to the audio data.
Speakers
The VoxPopuli dataset includes speech from multiple speakers, but how many speakers are represented in the dataset? To
determine this, we can count the number of unique speakers and the number of example... |
[
0.01224671,
-0.013732446,
-0.003470255,
0.01921552,
0.006105668,
-0.009911982,
0.030026019,
-0.00692636,
-0.0324315,
0.05886345,
0.008652644,
0.03296919,
0.0040539373,
-0.04482678,
-0.05691077,
0.002216223,
-0.052892204,
-0.025993306,
-0.060335036,
-0.029375125,
0.007789502,
... | Now you have two sets of characters: one with the vocabulary from the dataset and one with the vocabulary from the tokenizer.
To identify any unsupported characters in the dataset, you can take the difference between these two sets. The resulting
set will contain the characters that are in the dataset but not in the ... |
[
0.040067844,
-0.0037581776,
-0.0036800336,
0.024569904,
0.00058971404,
-0.009958807,
0.032391567,
0.011507147,
-0.036869396,
0.06123576,
0.022243759,
0.03035619,
0.0036418703,
-0.010329536,
-0.060479764,
0.016646473,
-0.033409253,
-0.031839106,
-0.049692266,
-0.006742185,
0.0... | dataset_vocab - tokenizer_vocab
{' ', 'à', 'ç', 'è', 'ë', 'í', 'ï', 'ö', 'ü'}
To handle the unsupported characters identified in the previous step, define a function that maps these characters to
valid tokens. Note that spaces are already replaced by ▁ in the tokenizer and don't need to be handled separately. |
[
0.043925613,
0.008023037,
-0.019031705,
0.037790753,
-0.0070005595,
-0.047879193,
-0.012951376,
0.004587514,
-0.009093229,
0.01716398,
0.06178488,
-0.003263406,
-0.0060701054,
0.021158459,
-0.047742862,
0.031328697,
-0.0068403715,
-0.013155871,
-0.043243963,
-0.011226798,
-0.... | def select_speaker(speaker_id):
return 100 <= speaker_counts[speaker_id] <= 400
dataset = dataset.filter(select_speaker, input_columns=["speaker_id"])
Let's check how many speakers remain:
len(set(dataset["speaker_id"]))
42
Let's see how many examples are left:
len(dataset)
9973 |
[
0.0036028367,
0.028421184,
-0.024578158,
-0.005900766,
0.017465692,
-0.039003845,
-0.04126951,
0.00552435,
0.014970594,
0.013228326,
0.041126113,
-0.026370615,
0.02906647,
-0.010281528,
0.011141907,
0.015400783,
-0.016533615,
-0.020778151,
-0.032378927,
-0.063151814,
-0.02756... |
You are left with just under 10,000 examples from approximately 40 unique speakers, which should be sufficient.
Note that some speakers with few examples may actually have more audio available if the examples are long. However,
determining the total amount of audio for each speaker requires scanning through the enti... |
[
-0.009345672,
0.00716106,
-0.043050114,
0.0029959893,
-0.00036053947,
0.006379346,
-0.022725547,
-0.020240813,
0.0011673365,
0.022907017,
0.02777877,
-0.03428375,
0.06169958,
-0.05885191,
0.012919222,
0.031603586,
-0.03372538,
-0.05268195,
-0.042380072,
-0.023395587,
-0.00056... |
import os
import torch
from speechbrain.pretrained import EncoderClassifier
spk_model_name = "speechbrain/spkrec-xvect-voxceleb"
device = "cuda" if torch.cuda.is_available() else "cpu"
speaker_model = EncoderClassifier.from_hparams(
source=spk_model_name,
run_opts={"device": device},
savedir=os.path.jo... |
[
0.02499396,
0.005897287,
-0.019330809,
-0.0062631234,
0.013865209,
-0.025111027,
-0.011838474,
-0.046827093,
-0.021028291,
0.017252857,
0.022637973,
-0.030671746,
0.037988476,
-0.049256247,
-0.0012767699,
0.018072331,
-0.014911502,
-0.049753785,
-0.05648518,
-0.024847625,
-0.... |
It's important to note that the speechbrain/spkrec-xvect-voxceleb model was trained on English speech from the VoxCeleb
dataset, whereas the training examples in this guide are in Dutch. While we believe that this model will still generate
reasonable speaker embeddings for our Dutch dataset, this assumption may not... |
[
0.0047567,
0.0029834302,
-0.010345822,
-0.015431294,
0.026357714,
-0.03192585,
-0.02043982,
-0.013955318,
-0.000099790144,
0.045888163,
0.029183753,
-0.033604685,
0.018774975,
0.022230577,
-0.032457482,
0.03612294,
-0.018509159,
-0.021684956,
-0.022636296,
0.0048931055,
-0.03... | from collections import defaultdict
speaker_counts = defaultdict(int)
for speaker_id in dataset["speaker_id"]:
speaker_counts[speaker_id] += 1
By plotting a histogram you can get a sense of how much data there is for each speaker.
import matplotlib.pyplot as plt
plt.figure()
plt.hist(speaker_counts.values(), bin... |
[
-0.0032297897,
0.026726378,
0.022102827,
-0.029291885,
0.009789805,
-0.059598695,
-0.0318292,
-0.016591217,
-0.024907969,
0.013750834,
0.015125213,
-0.032054737,
0.059091233,
-0.011826704,
-0.031660046,
0.03915922,
-0.050041478,
-0.07611943,
-0.047504164,
-0.041358225,
-0.013... | def prepare_dataset(example):
audio = example["audio"]
example = processor(
text=example["normalized_text"],
audio_target=audio["array"],
sampling_rate=audio["sampling_rate"],
return_attention_mask=False,
)
# strip off the batch dimension
example["labels"] =... |
[
0.04110429,
-0.009902146,
0.018640963,
-0.010996229,
0.0037461964,
-0.053014565,
-0.012076464,
0.012789695,
0.01426463,
0.043569442,
0.041492067,
-0.013011281,
0.027324382,
0.016328154,
-0.002324927,
0.049081404,
-0.016674383,
-0.037475813,
-0.043347854,
0.008524155,
-0.02286... | import matplotlib.pyplot as plt
plt.figure()
plt.hist(speaker_counts.values(), bins=20)
plt.ylabel("Speakers")
plt.xlabel("Examples")
plt.show()
The histogram reveals that approximately one-third of the speakers in the dataset have fewer than 100 examples, while
around ten speakers have more than 500 examples. To imp... |
[
0.019917592,
0.0023415706,
-0.003389865,
-0.017106948,
0.0030613234,
-0.058370244,
-0.02222688,
-0.025888313,
0.0017319645,
0.044939924,
0.024034806,
-0.002983461,
0.046884585,
0.010893146,
0.0023396714,
0.02496156,
0.0008213538,
-0.04430183,
-0.035854705,
-0.041202527,
-0.00... | Verify the processing is correct by looking at a single example:
processed_example = prepare_dataset(dataset[0])
list(processed_example.keys())
['input_ids', 'labels', 'stop_labels', 'speaker_embeddings']
Speaker embeddings should be a 512-element vector:
processed_example["speaker_embeddings"].shape
(512,)
The lab... |
[
0.010909312,
0.011811207,
-0.0064250943,
-0.026580626,
0.011205134,
-0.04176131,
-0.026248729,
-0.007561481,
-0.009076663,
0.055556685,
0.010642352,
-0.02202065,
0.0300439,
-0.050361775,
-0.017749278,
0.021385716,
-0.010627922,
-0.08467705,
-0.051747084,
0.012143103,
0.005144... | Side note: If you find this spectrogram confusing, it may be due to your familiarity with the convention of placing low frequencies
at the bottom and high frequencies at the top of a plot. However, when plotting spectrograms as an image using the matplotlib library,
the y-axis is flipped and the spectrograms appear u... |
[
0.01691425,
-0.012722989,
0.03887429,
0.04191262,
-0.019667733,
-0.024008198,
0.0027467008,
0.025622308,
0.0015013601,
0.071237884,
0.04720256,
-0.005564612,
0.001746359,
-0.024849163,
-0.03721949,
0.035944477,
-0.028348664,
-0.061960142,
-0.05740265,
-0.0045337514,
-0.004398... | dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names)
You'll see a warning saying that some examples in the dataset are longer than the maximum input length the model can handle (600 tokens).
Remove those examples from the dataset. Here we go even further and to allow for larger batch sizes we r... |
[
0.039022822,
0.04089378,
0.047762863,
0.026286948,
-0.044555508,
-0.021115087,
0.04631955,
0.009414923,
-0.024081891,
0.06168813,
0.011807076,
0.035681825,
-0.032715023,
-0.05896188,
-0.055754524,
0.018509112,
0.0055928254,
-0.005141791,
-0.048003417,
-0.036483664,
-0.0116132... | def is_not_too_long(input_ids):
input_length = len(input_ids)
return input_length < 200
dataset = dataset.filter(is_not_too_long, input_columns=["input_ids"])
len(dataset)
8259
Next, create a basic train/test split:
dataset = dataset.train_test_split(test_size=0.1) |
[
0.022867909,
0.010977755,
0.048053022,
0.013251511,
-0.01261428,
-0.04454825,
0.0061767977,
-0.0036984752,
-0.011100857,
0.04753165,
0.036553897,
-0.00030413305,
0.022954805,
-0.03875524,
-0.03559805,
0.037973184,
-0.013360131,
-0.098307386,
-0.07165954,
-0.0044859624,
-0.005... | dataset = dataset.train_test_split(test_size=0.1)
Data collator
In order to combine multiple examples into a batch, you need to define a custom data collator. This collator will pad shorter sequences with padding
tokens, ensuring that all examples have the same length. For the spectrogram labels, the padded portions ... |
[
0.008396256,
0.013853082,
0.020894386,
0.045490827,
-0.009928906,
-0.011928014,
-0.016792512,
0.0043277,
-0.017340416,
0.04925211,
0.017740238,
0.028535424,
-0.039597157,
-0.028254068,
-0.033436943,
0.013490281,
-0.04412847,
-0.06598539,
-0.04605354,
0.009055221,
0.013312582,... | In SpeechT5, the input to the decoder part of the model is reduced by a factor 2. In other words, it throws away every
other timestep from the target sequence. The decoder then predicts a sequence that is twice as long. Since the original
target sequence length may be odd, the data collator makes sure to round the ma... |
[
0.05399648,
0.011710745,
-0.021018578,
0.056067955,
-0.05576414,
-0.022482421,
0.021087628,
0.0007112068,
0.024236271,
0.040379975,
0.039496146,
-0.0019627237,
0.07065115,
-0.050764978,
-0.024001503,
-0.002865542,
-0.023103865,
-0.034193166,
-0.0696016,
0.011413834,
0.0014966... | The use_cache=True option is incompatible with gradient checkpointing. Disable it for training.
model.config.use_cache = False
Define the training arguments. Here we are not computing any evaluation metrics during the training process. Instead, we'll
only look at the loss:
thon |
[
0.04256324,
0.040543098,
-0.006291896,
0.04604237,
-0.02769276,
-0.037540946,
-0.021955,
-0.0022901942,
0.0034212624,
0.019345652,
0.015824435,
-0.01586652,
0.038999937,
-0.06829198,
0.012506634,
0.030021533,
-0.012254116,
-0.042366836,
-0.046519347,
-0.022488093,
-0.01040933... |
from transformers import Seq2SeqTrainingArguments
training_args = Seq2SeqTrainingArguments(
output_dir="speecht5_finetuned_voxpopuli_nl", # change to a repo name of your choice
per_device_train_batch_size=4,
gradient_accumulation_steps=8,
learning_rate=1e-5,
warmup_steps=500,
max_steps=... |
[
-0.014247443,
0.0027535665,
0.007942077,
-0.00985381,
-0.030560898,
-0.0050409385,
0.0020291202,
0.0033170246,
0.005923019,
0.07818653,
-0.02181388,
-0.0039006062,
-0.006808453,
-0.026348377,
-0.0014195456,
-0.008210391,
-0.023732321,
-0.06756132,
-0.03879812,
0.014046207,
-0... | from dataclasses import dataclass
from typing import Any, Dict, List, Union
@dataclass
class TTSDataCollatorWithPadding:
processor: Any |
[
0.015720492,
-0.0016156761,
-0.035138182,
-0.022316296,
0.03087901,
0.012925409,
-0.032771975,
-0.011306036,
0.012474351,
0.013945837,
0.0003597837,
0.019550791,
0.00848877,
-0.056374896,
-0.0019243923,
0.041763566,
-0.012592661,
-0.049394585,
-0.023410667,
-0.035463538,
-0.0... |
def call(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
input_ids = [{"input_ids": feature["input_ids"]} for feature in features]
label_features = [{"input_values": feature["labels"]} for feature in features]
speaker_features = [feature["sp... |
[
0.02822841,
0.022813441,
0.0075388853,
-0.024740573,
-0.0131574245,
0.00079562044,
0.0075388853,
0.016950617,
0.008068168,
0.042776898,
-0.012845283,
-0.012546713,
0.0076881703,
-0.03335838,
0.032516956,
0.028581265,
-0.022460585,
-0.05618539,
-0.07654242,
-0.025894137,
-0.00... | Instantiate the Trainer object and pass the model, dataset, and data collator to it.
from transformers import Seq2SeqTrainer
trainer = Seq2SeqTrainer(
args=training_args,
model=model,
train_dataset=dataset["train"],
eval_dataset=dataset["test"],
data_collator=data_collator,
tokenizer=pro... |
[
0.024414362,
0.0008258119,
-0.02684567,
0.033777785,
-0.0077136075,
-0.028987534,
-0.01960964,
-0.025137966,
0.00035456545,
0.03204114,
0.018640012,
-0.007634011,
0.02839418,
-0.049870715,
0.0076557193,
0.0027207471,
-0.04321357,
-0.07508104,
-0.0625193,
-0.020680573,
-0.0214... | data_collator = TTSDataCollatorWithPadding(processor=processor)
Train the model
Load the pre-trained model from the same checkpoint as you used for loading the processor:
from transformers import SpeechT5ForTextToSpeech
model = SpeechT5ForTextToSpeech.from_pretrained(checkpoint)
The use_cache=True option is incompa... |
[
0.047754522,
-0.0022944785,
-0.04179255,
0.043730926,
-0.0408821,
-0.026946355,
-0.032335628,
-0.008039853,
-0.0029406035,
0.037475258,
-0.005146974,
-0.013708132,
0.024479331,
-0.031483915,
0.0058628516,
0.021189967,
-0.01845862,
-0.035301927,
-0.06660963,
-0.0100075975,
-0.... | trainer.train()
To be able to use your checkpoint with a pipeline, make sure to save the processor with the checkpoint:
processor.save_pretrained("YOUR_ACCOUNT_NAME/speecht5_finetuned_voxpopuli_nl")
Push the final model to the 🤗 Hub:
trainer.push_to_hub()
Inference
Inference with a pipeline
Great, now that you'v... |
[
0.023834018,
0.008882761,
-0.030479021,
0.021664532,
0.0033831866,
-0.019752955,
-0.040749952,
-0.03082796,
0.0023477494,
0.038322553,
0.001456439,
-0.025017375,
0.028248848,
-0.014260965,
-0.00073675334,
0.008602093,
-0.03525796,
-0.05825756,
-0.056588724,
0.0069256714,
-0.0... | from transformers import pipeline
pipe = pipeline("text-to-speech", model="YOUR_ACCOUNT_NAME/speecht5_finetuned_voxpopuli_nl")
Pick a piece of text in Dutch you'd like narrated, e.g.:
text = "hallo allemaal, ik praat nederlands. groetjes aan iedereen!"
To use SpeechT5 with the pipeline, you'll need a speaker embeddi... |
[
0.021560112,
0.01278306,
-0.007497355,
0.0622044,
-0.044288643,
-0.04067211,
0.020878533,
-0.0016117921,
0.008408443,
0.06493071,
0.008213707,
0.002329883,
0.042925484,
-0.03444054,
-0.015412002,
0.04053301,
-0.016260497,
-0.037027754,
-0.07088408,
0.0061828834,
0.0019751843,... | And with that, you're ready to start training! Training will take several hours. Depending on your GPU,
it is possible that you will encounter a CUDA "out-of-memory" error when you start training. In this case, you can reduce
the per_device_train_batch_size incrementally by factors of 2 and increase gradient_accumula... |
[
0.01046552,
0.009488738,
-0.04559295,
-0.009246379,
-0.015628511,
-0.0151144145,
-0.04262588,
0.0027228713,
0.012852393,
0.026674224,
0.035869192,
-0.063336596,
0.027026746,
-0.038013708,
-0.01326367,
-0.0122722,
-0.026027933,
-0.046826776,
-0.03777869,
-0.009664999,
-0.00990... | You can then listen to the result:
from IPython.display import Audio
Audio(output['audio'], rate=output['sampling_rate'])
Run inference manually
You can achieve the same inference results without using the pipeline, however, more steps will be required.
Load the model from the 🤗 Hub:
model = SpeechT5ForTextToSpe... |
[
0.03000373,
0.0140295215,
-0.027781231,
-0.0046899104,
0.016361684,
-0.015425894,
-0.036671225,
-0.017399823,
-0.006989173,
0.023570182,
0.026450656,
-0.015776815,
0.031699847,
-0.04582441,
0.0065834206,
0.010001243,
-0.025383273,
-0.06480338,
-0.044069804,
-0.013042557,
-0.0... | model = SpeechT5ForTextToSpeech.from_pretrained("YOUR_ACCOUNT/speecht5_finetuned_voxpopuli_nl")
Pick an example from the test dataset obtain a speaker embedding.
example = dataset["test"][304]
speaker_embeddings = torch.tensor(example["speaker_embeddings"]).unsqueeze(0)
Define the input text and tokenize it.
t... |
[
0.030273737,
0.0231059,
-0.04907321,
-0.012225382,
0.01736877,
-0.055139408,
-0.010773215,
-0.007961879,
-0.014435823,
0.03236257,
0.0040167067,
-0.004517454,
0.018284421,
-0.04835786,
-0.012068004,
0.008906145,
-0.011037896,
-0.0936254,
-0.061577585,
0.008040567,
-0.02530918... | text = "hallo allemaal, ik praat nederlands. groetjes aan iedereen!"
inputs = processor(text=text, return_tensors="pt")
Create a spectrogram with your model:
spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
Visualize the spectrogram, if you'd like to:
plt.figure()
plt.imshow(spectrogra... |
[
-0.000027625127,
0.01749766,
-0.023674171,
-0.0077464366,
-0.009507995,
-0.016082516,
-0.046169057,
-0.0032227682,
0.013414381,
0.045903716,
0.022612814,
-0.0035544424,
0.052419275,
-0.035584964,
-0.019856233,
0.015699249,
-0.0149621945,
-0.045048736,
-0.034376193,
-0.024499672... | example = dataset["test"][304]
speaker_embeddings = torch.tensor(example["speaker_embeddings"]).unsqueeze(0)
Now you can pass the text and speaker embeddings to the pipeline, and it will take care of the rest:
forward_params = {"speaker_embeddings": speaker_embeddings}
output = pipe(text, forward_params=forward_para... |
[
0.023032779,
-0.0041744225,
-0.037695214,
-0.018532285,
0.015436404,
-0.034398675,
-0.033796698,
-0.023620423,
0.014268283,
0.03551663,
0.021585168,
-0.016812352,
0.030815478,
-0.04979208,
0.022201477,
0.016540028,
0.0010068779,
-0.07711036,
-0.04962009,
-0.0017889101,
-0.037... | Visualize the spectrogram, if you'd like to:
plt.figure()
plt.imshow(spectrogram.T)
plt.show()
Finally, use the vocoder to turn the spectrogram into sound.
with torch.no_grad():
speech = vocoder(spectrogram)
from IPython.display import Audio
Audio(speech.numpy(), rate=16000) |
[
0.033467855,
-0.0013803648,
-0.024061471,
0.01155157,
-0.015569187,
-0.039129376,
-0.0340576,
-0.002546948,
-0.004740051,
0.024665957,
0.025034545,
-0.0010348128,
0.03128581,
-0.03898194,
-0.004799025,
-0.015613418,
-0.0069700126,
-0.032642215,
-0.036622975,
-0.0025690633,
0.... |
In our experience, obtaining satisfactory results from this model can be challenging. The quality of the speaker
embeddings appears to be a significant factor. Since SpeechT5 was pre-trained with English x-vectors, it performs best
when using English speaker embeddings. If the synthesized speech sounds poor, try us... |
[
0.03893049,
0.01042172,
0.0037438627,
-0.020999731,
-0.0033957618,
-0.021923264,
0.045068435,
-0.00927796,
-0.005981656,
0.003218159,
-0.017490305,
-0.0037829354,
0.040720724,
-0.059333477,
-0.010023891,
0.043420285,
-0.002244897,
-0.03836216,
-0.03696976,
-0.00086226064,
0.0... | Before you begin, make sure you have all the necessary libraries installed:
pip install transformers datasets evaluate
We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login:
from huggingface_hub import notebook_login
... |
[
0.0022789377,
-0.0060574515,
0.009644603,
0.008920911,
-0.019957231,
-0.029504415,
-0.009074,
0.004954515,
-0.0030930927,
0.027375087,
0.03381874,
0.01286643,
0.007069926,
-0.034041416,
-0.043699935,
-0.0052676513,
-0.014571284,
-0.031870335,
-0.054304823,
-0.011753056,
-0.00... | While the dataset contains a lot of useful information, like lang_id and english_transcription, you'll focus on the audio and intent_class in this guide. Remove the other columns with the [~datasets.Dataset.remove_columns] method:
minds = minds.remove_columns(["path", "transcription", "english_transcription", "lang_id... |
[
0.0036351262,
0.014469472,
0.019349456,
-0.012217717,
-0.029606655,
-0.029152043,
0.031396694,
-0.021792999,
-0.0075224205,
0.026779532,
0.0039743097,
0.02356883,
0.049723268,
-0.061997812,
-0.026609052,
0.027617725,
-0.013219287,
-0.008502679,
-0.06807826,
-0.017559417,
-0.0... | from huggingface_hub import notebook_login
notebook_login()
Load MInDS-14 dataset
Start by loading the MInDS-14 dataset from the 🤗 Datasets library:
from datasets import load_dataset, Audio
minds = load_dataset("PolyAI/minds14", name="en-US", split="train")
Split the dataset's train split into a smaller train and t... |
[
-0.0143641485,
0.0111272605,
-0.0011707111,
-0.016896408,
-0.028933814,
-0.037110444,
0.022856392,
-0.016426656,
0.0036901257,
0.036435172,
0.006719662,
-0.011736471,
0.01685237,
-0.015722027,
-0.0076187975,
0.036493894,
0.013564101,
-0.02671717,
-0.06735075,
-0.047562435,
0.... | To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name to an integer and vice versa:
labels = minds["train"].features["intent_class"].names
label2id, id2label = dict(), dict()
for i, label in enumerate(labels):
label2id[label] = str(i)
id2label[s... |
[
0.013069706,
0.0075553833,
0.0057253474,
-0.018487165,
-0.040959585,
-0.015096929,
0.008987585,
0.0023697058,
-0.01779528,
0.064705074,
0.031245522,
0.018708568,
0.01761539,
-0.031660654,
-0.004251633,
0.019635694,
-0.024063757,
-0.010066926,
-0.030858066,
-0.037002005,
-0.01... | minds = minds.train_test_split(test_size=0.2)
Then take a look at the dataset:
minds
DatasetDict({
train: Dataset({
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
num_rows: 450
})
test: Dataset({
features: ['path', 'audio', 'transc... |
[
-0.023888154,
0.017610768,
0.020408608,
-0.003742288,
-0.025038535,
-0.044623412,
0.025691837,
-0.01450758,
0.0029380866,
0.01928663,
0.0024623119,
-0.021615798,
0.04141371,
-0.023064425,
-0.009394776,
0.042805526,
-0.007520082,
-0.023206446,
-0.049111318,
-0.050133877,
0.010... | Now you can convert the label id to a label name:
id2label[str(2)]
'app_error'
Preprocess
The next step is to load a Wav2Vec2 feature extractor to process the audio signal:
from transformers import AutoFeatureExtractor
feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")
The MInDS-14 d... |
[
0.016897127,
0.02762929,
0.016942346,
0.0056072534,
-0.027795095,
-0.056615174,
-0.007351984,
0.003391484,
-0.006229026,
0.05031455,
0.036055245,
-0.0034310513,
0.050766747,
-0.030041011,
-0.013121274,
0.00910425,
-0.040275756,
-0.01617361,
-0.06547825,
-0.020348905,
0.014719... | minds = minds.cast_column("audio", Audio(sampling_rate=16_000))
minds["train"][0]
{'audio': {'array': array([ 2.2098757e-05, 4.6582241e-05, -2.2803260e-05, ,
-2.8419291e-04, -2.3305941e-04, -1.1425107e-04], dtype=float32),
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943... |
[
-0.004927293,
0.016581213,
-0.027513882,
-0.011266722,
0.0045059295,
-0.03264616,
-0.004976642,
-0.022032363,
0.0008436755,
0.044763204,
0.05265902,
-0.0019113189,
0.027058354,
-0.017932612,
-0.017446717,
0.028880466,
-0.008002106,
-0.033860903,
-0.033769798,
-0.026375063,
0.... | There are two fields:
audio: a 1-dimensional array of the speech signal that must be called to load and resample the audio file.
intent_class: represents the class id of the speaker's intent.
To make it easier for the model to get the label name from the label id, create a dictionary that maps the label name to an ... |
[
-0.010099905,
0.005782646,
0.021522416,
-0.013113343,
-0.05822475,
-0.038445767,
0.0018495827,
0.00683472,
0.0035075375,
0.06540891,
0.02493414,
0.026001243,
0.010475645,
-0.031892855,
-0.042082936,
0.0014550551,
-0.034718424,
-0.020094601,
-0.055759892,
-0.005602291,
0.00572... | minds = minds.remove_columns(["path", "transcription", "english_transcription", "lang_id"])
Take a look at an example now:
minds["train"][0]
{'audio': {'array': array([ 0. , 0. , 0. , , -0.00048828,
-0.00024414, -0.00024414], dtype=float32),
'path': '/root/.cache/huggingface/datasets... |
[
0.00940716,
0.04360144,
0.011979536,
-0.022452297,
-0.03640693,
-0.044361614,
-0.045746215,
0.012359623,
0.0035225945,
0.05155612,
0.06054247,
0.00047383647,
0.005178689,
-0.047890995,
-0.017524738,
0.06689536,
-0.042189687,
-0.06760123,
-0.038008727,
-0.038524557,
0.01584149... | def preprocess_function(examples):
audio_arrays = [x["array"] for x in examples["audio"]]
inputs = feature_extractor(
audio_arrays, sampling_rate=feature_extractor.sampling_rate, max_length=16000, truncation=True
)
return inputs |
[
-0.011224226,
-0.0020339915,
0.009286077,
0.009413866,
0.0021475828,
-0.051911157,
0.0007445545,
-0.000018954968,
-0.01450417,
0.02721928,
0.036178783,
-0.0014527243,
0.027403865,
-0.025685798,
-0.025856186,
0.018075192,
-0.030612815,
-0.011848977,
-0.07514054,
-0.021071158,
... | To apply the preprocessing function over the entire dataset, use 🤗 Datasets [~datasets.Dataset.map] function. You can speed up map by setting batched=True to process multiple elements of the dataset at once. Remove the columns you don't need, and rename intent_class to label because that's the name the model expects:
... |
[
0.014157512,
0.05663005,
0.03259405,
0.0192062,
-0.0034528794,
-0.018952,
-0.038977288,
-0.01081761,
-0.0052852356,
0.06806903,
0.037395604,
-0.017497413,
0.029119989,
-0.06829499,
0.0029603676,
0.05663005,
-0.040474243,
-0.059369754,
-0.051178876,
-0.014058656,
-0.015760383,... | Now create a preprocessing function that:
Calls the audio column to load, and if necessary, resample the audio file.
Checks if the sampling rate of the audio file matches the sampling rate of the audio data a model was pretrained with. You can find this information in the Wav2Vec2 model card.
Set a maximum input lengt... |
[
-0.0019412274,
0.024545852,
-0.0270481,
0.0064178,
-0.03902976,
-0.0021911212,
0.01707883,
0.00321221,
0.018998543,
0.027405564,
0.027273169,
0.023407264,
0.008837301,
0.0010905957,
0.022718815,
0.04427256,
-0.02016361,
-0.01707883,
-0.06492603,
-0.03386639,
0.02483712,
0.0... | import evaluate
accuracy = evaluate.load("accuracy")
Then create a function that passes your predictions and labels to [~evaluate.EvaluationModule.compute] to calculate the accuracy:
import numpy as np
def compute_metrics(eval_pred):
predictions = np.argmax(eval_pred.predictions, axis=1)
return accuracy.com... |
[
-0.0056520924,
0.029915258,
-0.01919849,
0.006089073,
-0.029485442,
-0.016877478,
-0.0064472537,
0.0011488649,
-0.016146788,
0.030173149,
0.03968643,
-0.011211058,
0.029972566,
-0.041663587,
0.0097568445,
0.06389945,
-0.023826186,
-0.035617497,
-0.08166522,
-0.034385353,
0.00... | Your compute_metrics function is ready to go now, and you'll return to it when you setup your training.
Train
If you aren't familiar with finetuning a model with the [Trainer], take a look at the basic tutorial here!
You're ready to start training your model now! Load Wav2Vec2 with [AutoModelForAudioClassification] a... |
[
-0.0028373501,
0.05363345,
-0.0012267684,
-0.0144629525,
0.0018024886,
-0.018107388,
0.0071453876,
-0.0062593883,
-0.0092043495,
0.03147988,
0.017820423,
-0.0305329,
0.04683242,
-0.032139894,
0.02106311,
0.056646567,
-0.02787849,
-0.029557224,
-0.054035198,
-0.061123192,
-0.0... | You're ready to start training your model now! Load Wav2Vec2 with [AutoModelForAudioClassification] along with the number of expected labels, and the label mappings:
from transformers import AutoModelForAudioClassification, TrainingArguments, Trainer
num_labels = len(id2label)
model = AutoModelForAudioClassification.f... |
[
0.04426768,
0.02668692,
-0.014951725,
0.017404513,
-0.03266467,
-0.009025378,
0.008401166,
-0.012528311,
0.017595448,
0.023778824,
0.014386262,
0.021737281,
-0.005856582,
-0.030285321,
0.0026694264,
0.031548433,
0.010831922,
-0.025776304,
-0.07678548,
0.00057051185,
0.0055187... |
Define your training hyperparameters in [TrainingArguments]. The only required parameter is output_dir which specifies where to save your model. You'll push this model to the Hub by setting push_to_hub=True (you need to be signed in to Hugging Face to upload your model). At the end of each epoch, the [Trainer] will e... |
[
0.009253654,
-0.003981398,
-0.011415091,
-0.0065405997,
-0.061961208,
-0.023370542,
0.008728305,
-0.008953454,
-0.018041998,
0.028984277,
0.027348187,
0.03311202,
0.023535652,
-0.014244474,
0.010409422,
0.009306189,
-0.02464639,
-0.023445591,
-0.07571035,
-0.00198507,
0.02644... | encoded_minds = minds.map(preprocess_function, remove_columns="audio", batched=True)
encoded_minds = encoded_minds.rename_column("intent_class", "label")
Evaluate
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load a evaluation method with the 🤗 Evaluate l... |
[
0.026220327,
0.021426745,
-0.04117862,
0.0018896395,
-0.017485032,
-0.020675942,
-0.012590378,
-0.013882624,
0.017239576,
0.019477546,
0.043171134,
0.012077811,
0.011500271,
-0.04678076,
0.0054216594,
0.042911243,
-0.0037070867,
-0.03063851,
-0.064337984,
-0.01217888,
-0.0050... | Once training is completed, share your model to the Hub with the [~transformers.Trainer.push_to_hub] method so everyone can use your model:
trainer.push_to_hub()
For a more in-depth example of how to finetune a model for audio classification, take a look at the corresponding PyTorch notebook. |
[
0.030788261,
0.008601758,
-0.032339163,
-0.018194368,
-0.028347028,
0.009542351,
-0.039031014,
-0.009678773,
0.003222069,
0.050346848,
0.0626679,
-0.01535105,
0.010727067,
-0.047216326,
0.007768866,
0.04606751,
-0.01386477,
-0.026049396,
-0.034751676,
-0.0093484875,
0.0055609... | trainer.push_to_hub()
For a more in-depth example of how to finetune a model for audio classification, take a look at the corresponding PyTorch notebook.
Inference
Great, now that you've finetuned a model, you can use it for inference!
Load an audio file you'd like to run inference on. Remember to resample the sampli... |
[
0.00441206,
0.04182661,
-0.0044894647,
-0.019140037,
-0.03256621,
-0.013517651,
-0.025613872,
-0.014228365,
-0.0011118109,
0.04036296,
0.05077739,
-0.01725418,
0.03782972,
-0.027767127,
-0.00923929,
0.03695716,
-0.033185445,
-0.031130707,
-0.0682849,
-0.039518546,
0.000047470... | from datasets import load_dataset, Audio
dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))
sampling_rate = dataset.features["audio"].sampling_rate
audio_file = dataset[0]["audio"]["path"]
The simplest way to try out your finetuned m... |
[
-0.0012397105,
0.040490497,
-0.01948404,
-0.004461128,
-0.024592927,
-0.034781426,
0.012215951,
-0.004969821,
0.0010677064,
0.054924205,
0.025690826,
-0.014697202,
0.051586594,
-0.046872947,
-0.019571872,
0.015224193,
-0.042832684,
-0.048131872,
-0.05875953,
-0.036830835,
0.0... | from transformers import pipeline
classifier = pipeline("audio-classification", model="stevhliu/my_awesome_minds_model")
classifier(audio_file)
[
{'score': 0.09766869246959686, 'label': 'cash_deposit'},
{'score': 0.07998877018690109, 'label': 'app_error'},
{'score': 0.0781070664525032, 'label': 'joint_accou... |
[
0.030490108,
0.036383152,
-0.0064446293,
0.020056285,
-0.047457524,
-0.032169767,
0.022148743,
0.016113352,
-0.021807117,
0.029408293,
0.02411309,
0.03530134,
0.013401697,
-0.050589096,
-0.020696834,
0.016796604,
-0.027344303,
-0.013337643,
-0.07453138,
0.005764936,
0.0173802... |
training_args = TrainingArguments(
output_dir="my_awesome_mind_model",
evaluation_strategy="epoch",
save_strategy="epoch",
learning_rate=3e-5,
per_device_train_batch_size=32,
gradient_accumulation_steps=4,
per_device_eval_batch_size=32,
num_train_epochs=10,
warmup_ratio=0.... |
[
0.022093438,
0.024082419,
-0.031651996,
0.008335121,
-0.019431923,
-0.012828217,
-0.039178647,
0.025041137,
0.027545251,
0.031251337,
0.028575515,
-0.0041103237,
0.0370895,
-0.071030974,
-0.009851899,
0.032281604,
-0.010066537,
-0.032453313,
-0.047277667,
-0.024955282,
0.0093... | You can also manually replicate the results of the pipeline if you'd like:
Load a feature extractor to preprocess the audio file and return the input as PyTorch tensors:
from transformers import AutoFeatureExtractor
feature_extractor = AutoFeatureExtractor.from_pretrained("stevhliu/my_awesome_minds_model")
inputs = f... |
[
0.010296146,
-0.02194431,
-0.00976871,
0.012391033,
-0.00021438696,
-0.026579805,
0.029863281,
0.011997313,
-0.0019723137,
0.049593847,
0.051971022,
-0.009166988,
0.025361503,
-0.010325861,
-0.0054600774,
0.038539976,
0.0072801034,
-0.011544163,
-0.0059095123,
-0.031467874,
0... | Get the class with the highest probability, and use the model's id2label mapping to convert it to a label:
import torch
predicted_class_ids = torch.argmax(logits).item()
predicted_label = model.config.id2label[predicted_class_ids]
predicted_label
'cash_deposit' |
[
0.048298404,
0.01401338,
-0.013093886,
-0.018675003,
0.00052122504,
-0.014398284,
0.043736573,
0.007648198,
0.005859104,
0.013635603,
-0.02859699,
0.004590344,
0.01971567,
-0.053630047,
-0.009986137,
0.03800577,
-0.0011645147,
-0.05209043,
-0.023778554,
0.012081729,
0.0211269... | Before you begin, make sure you have all the necessary libraries installed:
pip install transformers datasets evaluate jiwer
We encourage you to login to your Hugging Face account so you can upload and share your model with the community. When prompted, enter your token to login:
from huggingface_hub import notebook_... |
[
0.015779693,
0.014816103,
-0.023372492,
-0.005444646,
-0.024169447,
-0.021445312,
0.011765942,
0.015069679,
-0.0054482687,
0.035355784,
0.048802577,
-0.0020630246,
0.021966955,
-0.052859798,
-0.013838023,
0.05146875,
0.009215688,
-0.01046908,
-0.037239496,
-0.038949326,
0.013... | Pass your inputs to the model and return the logits:
from transformers import AutoModelForAudioClassification
model = AutoModelForAudioClassification.from_pretrained("stevhliu/my_awesome_minds_model")
with torch.no_grad():
logits = model(**inputs).logits
Get the class with the highest probability, and use the mo... |
[
0.012101884,
0.015586284,
0.031477366,
-0.017054858,
-0.041120082,
-0.03513495,
0.009885168,
-0.009940585,
-0.010432419,
0.050430287,
0.024854928,
0.0284848,
0.042394694,
-0.03217009,
-0.014976687,
0.027390296,
-0.0067402017,
-0.007329017,
-0.05220366,
-0.029870247,
-0.033638... | from datasets import load_dataset, Audio
minds = load_dataset("PolyAI/minds14", name="en-US", split="train[:100]")
Split the dataset's train split into a train and test set with the [~Dataset.train_test_split] method:
minds = minds.train_test_split(test_size=0.2)
Then take a look at the dataset: |
[
0.013887978,
0.008332787,
0.0038001928,
-0.020120295,
-0.041290823,
-0.0148553,
0.00742765,
0.004235488,
-0.015283685,
0.06511458,
0.030926662,
0.017259786,
0.018047461,
-0.030705558,
-0.0040074764,
0.017315062,
-0.024597613,
-0.009756132,
-0.031230677,
-0.03590146,
-0.017812... | minds = minds.train_test_split(test_size=0.2)
Then take a look at the dataset:
minds
DatasetDict({
train: Dataset({
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'],
num_rows: 16
})
test: Dataset({
features: ['path', 'audio', 'transcr... |
[
-0.0064981533,
0.009198497,
-0.007971068,
0.014079331,
-0.03520555,
-0.04447625,
0.043783113,
-0.020086514,
0.034858983,
0.056144044,
0.021674952,
0.0072310003,
0.031191135,
-0.045660354,
-0.0553065,
-0.018526956,
-0.026050374,
-0.007415115,
-0.040028624,
-0.018050425,
-0.022... |
minds["train"][0]
{'audio': {'array': array([-0.00024414, 0. , 0. , , 0.00024414,
0.00024414, 0.00024414], dtype=float32),
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602ba9e2963e11ccd901c... |
[
0.008691369,
0.031650394,
-0.006524036,
0.00047708853,
0.0044999686,
-0.0250235,
-0.044933565,
-0.021305975,
0.003526506,
0.03238508,
0.017970487,
-0.03226753,
0.049988225,
-0.037380964,
-0.0007415765,
0.039908294,
-0.069413394,
-0.04872456,
-0.03326671,
-0.027888786,
-0.0267... | There are two fields:
audio: a 1-dimensional array of the speech signal that must be called to load and resample the audio file.
transcription: the target text.
Preprocess
The next step is to load a Wav2Vec2 processor to process the audio signal:
from transformers import AutoProcessor
processor = AutoProcessor.from_... |
[
0.009975169,
0.01939852,
0.012076321,
-0.011227371,
-0.023162201,
-0.033561844,
0.032910984,
-0.026034484,
-0.01579048,
0.021690685,
0.0067809923,
0.023912106,
0.04771102,
-0.054134745,
-0.023303691,
0.026869284,
-0.012359304,
-0.012741333,
-0.07295315,
-0.009402127,
-0.01934... | from huggingface_hub import notebook_login
notebook_login()
Load MInDS-14 dataset
Start by loading a smaller subset of the MInDS-14 dataset from the 🤗 Datasets library. This'll give you a chance to experiment and make sure everything works before spending more time training on the full dataset.
from datasets import ... |
[
0.0010648704,
-0.0150302285,
0.0106297955,
0.010368519,
-0.014576433,
-0.031270575,
-0.011399872,
0.0046307677,
0.0005543514,
0.019953212,
0.03179313,
0.010808563,
0.0040463354,
-0.037871227,
-0.042629194,
-0.00833332,
-0.015704045,
-0.03721116,
-0.055060416,
-0.014177645,
-0... | While the dataset contains a lot of useful information, like lang_id and english_transcription, you'll focus on the audio and transcription in this guide. Remove the other columns with the [~datasets.Dataset.remove_columns] method:
minds = minds.remove_columns(["english_transcription", "intent_class", "lang_id"])
Tak... |
[
0.003221757,
0.009904602,
0.0038624264,
0.010007697,
-0.033992298,
-0.05275581,
0.03517054,
-0.022283511,
0.022946274,
0.060502753,
0.03440468,
0.000682092,
0.039824598,
-0.040943928,
-0.03614259,
-0.022092048,
-0.039235476,
-0.01894025,
-0.049044345,
-0.02565623,
-0.01349824... |
minds = minds.cast_column("audio", Audio(sampling_rate=16_000))
minds["train"][0]
{'audio': {'array': array([-2.38064706e-04, -1.58618059e-04, -5.43987835e-06, ,
2.78103951e-04, 2.38446111e-04, 1.18740834e-04], dtype=float32),
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be6... |
[
0.0018955217,
0.022374803,
0.028390946,
-0.007523819,
-0.0089950785,
-0.050867718,
-0.0027404036,
0.0072834645,
-0.03781575,
0.06782362,
0.03268819,
-0.027822835,
0.023787795,
-0.04000079,
-0.04002992,
0.021078346,
-0.031464566,
-0.038864568,
-0.028303543,
-0.019155512,
-0.01... | As you can see in the transcription above, the text contains a mix of upper and lowercase characters. The Wav2Vec2 tokenizer is only trained on uppercase characters so you'll need to make sure the text matches the tokenizer's vocabulary:
def uppercase(example):
return {"transcription": example["transcription"].up... |
[
0.008029066,
0.028008703,
-0.0030341567,
0.02709273,
0.011127627,
-0.019478714,
-0.04576997,
-0.01959321,
-0.002837366,
0.033776462,
0.021081666,
-0.029654589,
0.02639144,
-0.01833375,
-0.032545626,
0.03154378,
-0.043107927,
-0.07568218,
-0.033776462,
-0.010025598,
-0.0316296... | Calls the audio column to load and resample the audio file.
Extracts the input_values from the audio file and tokenize the transcription column with the processor.
def prepare_dataset(batch):
audio = batch["audio"]
batch = processor(audio["array"], sampling_rate=audio["sampling_rate"], text=batch["transcript... |
[
-0.0034515301,
0.0033878153,
0.025005389,
-0.038593058,
-0.019311093,
-0.056506064,
-0.041301854,
-0.00005734346,
-0.023694681,
0.05167101,
0.06553538,
-0.001414472,
0.029345289,
-0.019471291,
-0.031893887,
0.041884392,
-0.040923204,
-0.041214474,
-0.0081627965,
-0.018204274,
... | def uppercase(example):
return {"transcription": example["transcription"].upper()}
minds = minds.map(uppercase)
Now create a preprocessing function that:
Calls the audio column to load and resample the audio file.
Extracts the input_values from the audio file and tokenize the transcription column with the proces... |
[
-0.0063587823,
0.050757214,
0.016928492,
-0.026947105,
-0.023372058,
-0.022609003,
-0.0057299696,
-0.016278483,
-0.024728598,
0.037022244,
-0.0035096945,
-0.031709127,
0.07014444,
-0.052198537,
0.0041826656,
0.03419612,
-0.0518594,
-0.04349407,
-0.060479086,
-0.046518024,
-0.... | Preprocess
The next step is to load a Wav2Vec2 processor to process the audio signal:
from transformers import AutoProcessor
processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base")
The MInDS-14 dataset has a sampling rate of 8000kHz (you can find this information in its dataset card), which means you'll n... |
[
0.017464794,
0.0014937457,
0.028269643,
0.0009738765,
-0.01518861,
-0.054937527,
-0.006048748,
-0.001651814,
-0.039931573,
0.040324986,
0.03225999,
0.0012197606,
0.025543842,
-0.020640211,
-0.024981821,
-0.002588808,
-0.041814342,
0.0020882583,
-0.07429914,
-0.014570387,
0.01... | To apply the preprocessing function over the entire dataset, use 🤗 Datasets [~datasets.Dataset.map] function. You can speed up map by increasing the number of processes with the num_proc parameter. Remove the columns you don't need with the [~datasets.Dataset.remove_columns] method:
encoded_minds = minds.map(prepare_... |
[
0.023213688,
-0.0017612843,
0.015695876,
0.018516932,
-0.014007743,
-0.016971352,
0.030236317,
-0.01039139,
0.0053382483,
0.02783542,
0.019642353,
0.006088529,
-0.01958233,
-0.03850441,
-0.025314474,
0.025389504,
-0.025689615,
-0.053149894,
-0.044116512,
-0.008778286,
-0.0243... |
🤗 Transformers doesn't have a data collator for ASR, so you'll need to adapt the [DataCollatorWithPadding] to create a batch of examples. It'll also dynamically pad your text and labels to the length of the longest element in its batch (instead of the entire dataset) so they are a uniform length. While it is possibl... |
[
0.013797781,
-0.00061448343,
-0.028712146,
-0.02595694,
0.016792255,
0.020142006,
-0.020098502,
-0.013123481,
0.013319246,
0.036020692,
-0.018938415,
0.02449233,
-0.011753128,
-0.0508698,
-0.011310846,
0.04857863,
0.0044627083,
-0.069489196,
-0.03454158,
-0.025536409,
-0.0000... |
def call(self, features: List[Dict[str, Union[List[int], torch.Tensor]]]) -> Dict[str, torch.Tensor]:
# split inputs and labels since they have to be of different lengths and need
# different padding methods
input_features = [{"input_values": feature["input_values"][0]} for feature in ... |
[
0.0090494575,
0.007920887,
-0.04246766,
-0.011717619,
-0.023672098,
-0.006221066,
-0.0030722176,
0.016413026,
-0.0050437315,
0.030624645,
0.029454276,
0.012581462,
0.028618298,
-0.032101538,
0.012372468,
0.02499573,
-0.02325411,
-0.027893785,
-0.057180867,
-0.012602362,
-0.00... | import evaluate
wer = evaluate.load("wer")
Then create a function that passes your predictions and labels to [~evaluate.EvaluationModule.compute] to calculate the WER:
import numpy as np
def compute_metrics(pred):
pred_logits = pred.predictions
pred_ids = np.argmax(pred_logits, axis=-1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.