source
stringclasses
470 values
url
stringlengths
49
167
file_type
stringclasses
1 value
chunk
stringlengths
1
512
chunk_id
stringlengths
5
9
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#train-the-model
.md
Also, define a `collate_fn`, which will be used to batch examples together. Each batch consists of 2 keys, namely `pixel_values` and `labels`. ```py >>> 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": labels} ```
95_6_11
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#train-the-model
.md
... return {"pixel_values": pixel_values, "labels": labels} ``` Then you just pass all of this along with the datasets to `Trainer`: ```py >>> trainer = Trainer( ... model, ... args, ... train_dataset=train_dataset, ... eval_dataset=val_dataset, ... processing_class=image_processor, ... compute_metrics=compute_metrics, ... data_collator=collate_fn, ... ) ```
95_6_12
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#train-the-model
.md
... compute_metrics=compute_metrics, ... data_collator=collate_fn, ... ) ``` 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: ```py >>> train_results = trainer.train() ```
95_6_13
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#train-the-model
.md
Now fine-tune our model by calling the `train` method: ```py >>> 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: ```py >>> trainer.push_to_hub() ```
95_6_14
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
Great, now that you have fine-tuned a model, you can use it for inference! Load a video for inference: ```py >>> sample_test_video = next(iter(test_dataset)) ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/sample_gif_two.gif" alt="Teams playing basketball"/> </div>
95_7_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
</div> The simplest way to try out your fine-tuned model for inference is to use it in a [`pipeline`](https://huggingface.co/docs/transformers/main/en/main_classes/pipelines#transformers.VideoClassificationPipeline). Instantiate a `pipeline` for video classification with your model, and pass your video to it: ```py >>> from transformers import pipeline
95_7_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
>>> 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'}, {'score': 0.01663011871278286, 'label': 'BalanceBeam'}, {'score': 0.009560945443809032, 'label': 'BandMarching'}, {'score': 0.0068979403004050255, 'label': 'BaseballPitch'}] ```
95_7_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
{'score': 0.009560945443809032, 'label': 'BandMarching'}, {'score': 0.0068979403004050255, 'label': 'BaseballPitch'}] ``` You can also manually replicate the results of the `pipeline` if you'd like. ```py >>> 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": torch.tensor(
95_7_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
... inputs = { ... "pixel_values": perumuted_sample_test_video.unsqueeze(0), ... "labels": torch.tensor( ... [sample_test_video["label"]] ... ), # this can be skipped if you don't have labels available. ... }
95_7_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
... 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
95_7_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/video_classification.md
https://huggingface.co/docs/transformers/en/tasks/video_classification/#inference
.md
... # forward pass ... with torch.no_grad(): ... outputs = model(**inputs) ... logits = outputs.logits ... return logits ``` Now, pass your input to the model and return the `logits`: ```py >>> logits = run_inference(trained_model, sample_test_video["video"]) ``` Decoding the `logits`, we get: ```py >>> predicted_class_idx = logits.argmax(-1).item() >>> print("Predicted class:", model.config.id2label[predicted_class_idx]) # Predicted class: BasketballDunk ```
95_7_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/
.md
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
96_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. -->
96_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
[[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](../model_doc/bark), [MMS](../model_doc/mms), [VITS](../model_doc/vits) and [SpeechT5](../model_doc/speecht5). You can easily generate audio using the `"text-to-audio"` pipeline (or its alias - `"text-to-speech"`). Some models, like Bark,
96_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
You can easily generate audio using the `"text-to-audio"` pipeline (or its alias - `"text-to-speech"`). Some models, like Bark, can also be conditioned to generate non-verbal communications such as laughing, sighing and crying, or even add music. Here's an example of how you would use the `"text-to-speech"` pipeline with Bark: ```py >>> from transformers import pipeline
96_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
>>> 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: ```python >>> from IPython.display import Audio >>> Audio(output["audio"], rate=output["sampling_rate"]) ``` For more examples on what Bark and other pretrained TTS models can do, refer to our
96_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
``` For more examples on what Bark and other pretrained TTS models can do, refer to our [Audio course](https://huggingface.co/learn/audio-course/chapter6/pre-trained_models). If you are looking to fine-tune a TTS model, the only text-to-speech models currently available in 🤗 Transformers
96_1_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
are [SpeechT5](model_doc/speecht5) and [FastSpeech2Conformer](model_doc/fastspeech2_conformer), though more will be added in the future. SpeechT5 is pre-trained on a combination of speech-to-text and text-to-speech data, allowing it to learn a unified space of hidden representations shared by both text and speech. This means that the same pre-trained model can be fine-tuned for different tasks. Furthermore, SpeechT5 supports multiple speakers through x-vector speaker embeddings.
96_1_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
The remainder of this guide illustrates how to: 1. Fine-tune [SpeechT5](../model_doc/speecht5) that was originally trained on English speech on the Dutch (`nl`) language subset of the [VoxPopuli](https://huggingface.co/datasets/facebook/voxpopuli) dataset. 2. 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: ```bash pip install datasets soundfile speechbrain accelerate ```
96_1_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
```bash pip install datasets soundfile speechbrain accelerate ``` Install 🤗Transformers from source as not all the SpeechT5 features have been merged into an official release yet: ```bash pip install git+https://github.com/huggingface/transformers.git ``` <Tip> 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: ```bash !nvidia-smi ``` or alternatively for AMD GPUs: ```bash !rocm-smi ``` </Tip>
96_1_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
```bash !nvidia-smi ``` or alternatively for AMD GPUs: ```bash !rocm-smi ``` </Tip> We encourage you to log in to your Hugging Face account to upload and share your model with the community. When prompted, enter your token to log in: ```py >>> from huggingface_hub import notebook_login
96_1_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-to-speech
.md
>>> notebook_login() ```
96_1_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#load-the-dataset
.md
[VoxPopuli](https://huggingface.co/datasets/facebook/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. Note that VoxPopuli or any other automated speech recognition (ASR) dataset may not be the most suitable
96_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#load-the-dataset
.md
Note that VoxPopuli or any other automated speech recognition (ASR) dataset may not be the most suitable option for training TTS models. The features that make it beneficial for ASR, such as excessive background noise, are typically undesirable in TTS. However, finding top-quality, multilingual, and multi-speaker TTS datasets can be quite challenging. Let's load the data: ```py >>> from datasets import load_dataset, Audio
96_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#load-the-dataset
.md
>>> 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 = dataset.cast_column("audio", Audio(sampling_rate=16000)) ```
96_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#preprocess-the-data
.md
Let's begin by defining the model checkpoint to use and loading the appropriate processor: ```py >>> from transformers import SpeechT5Processor >>> checkpoint = "microsoft/speecht5_tts" >>> processor = SpeechT5Processor.from_pretrained(checkpoint) ```
96_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
Start by cleaning up the text data. You'll need the tokenizer part of the processor to process the text: ```py >>> tokenizer = processor.tokenizer ``` 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_text` as input text.
96_4_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
out as text. Thus, it is a better fit, and we recommend using `normalized_text` as input text. Because SpeechT5 was trained on the English language, it may not recognize certain characters in the Dutch dataset. If left as is, these characters will be converted to `<unk>` tokens. However, in Dutch, certain characters like `à` are used to stress syllables. In order to preserve the meaning of the text, we can replace this character with a regular `a`.
96_4_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
used to stress syllables. In order to preserve the meaning of the text, we can replace this character with a regular `a`. To identify unsupported tokens, extract all unique characters in the dataset using the `SpeechT5Tokenizer` which works with characters as tokens. To do this, write the `extract_all_chars` mapping function that concatenates the transcriptions from all examples into one string and converts it to a set of characters.
96_4_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
the transcriptions from all examples into one string and converts it to a set of characters. Make sure to set `batched=True` and `batch_size=-1` in `dataset.map()` so that all transcriptions are available at once for the mapping function. ```py >>> def extract_all_chars(batch): ... all_text = " ".join(batch["normalized_text"]) ... vocab = list(set(all_text)) ... return {"vocab": [vocab], "all_text": [all_text]}
96_4_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
>>> vocabs = dataset.map( ... extract_all_chars, ... batched=True, ... batch_size=-1, ... keep_in_memory=True, ... remove_columns=dataset.column_names, ... )
96_4_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
>>> dataset_vocab = set(vocabs["vocab"][0]) >>> tokenizer_vocab = {k for k, _ in tokenizer.get_vocab().items()} ``` 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 tokenizer. ```py >>> dataset_vocab - tokenizer_vocab
96_4_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
set will contain the characters that are in the dataset but not in the tokenizer. ```py >>> 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. ```py >>> replacements = [ ... ("à", "a"), ... ("ç", "c"), ... ("è", "e"),
96_4_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
```py >>> replacements = [ ... ("à", "a"), ... ("ç", "c"), ... ("è", "e"), ... ("ë", "e"), ... ("í", "i"), ... ("ï", "i"), ... ("ö", "o"), ... ("ü", "u"), ... ]
96_4_7
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#text-cleanup-for-speecht5-tokenization
.md
>>> def cleanup_text(inputs): ... for src, dst in replacements: ... inputs["normalized_text"] = inputs["normalized_text"].replace(src, dst) ... return inputs >>> dataset = dataset.map(cleanup_text) ``` Now that you have dealt with special characters in the text, it's time to shift focus to the audio data.
96_4_8
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speakers
.md
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 examples each speaker contributes to the dataset. With a total of 20,968 examples in the dataset, this information will give us a better understanding of the distribution of speakers and examples in the data. ```py >>> from collections import defaultdict >>> speaker_counts = defaultdict(int)
96_5_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speakers
.md
>>> 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. ```py >>> import matplotlib.pyplot as plt
96_5_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speakers
.md
>>> plt.figure() >>> plt.hist(speaker_counts.values(), bins=20) >>> plt.ylabel("Speakers") >>> plt.xlabel("Examples") >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/tts_speakers_histogram.png" alt="Speakers histogram"/> </div> The histogram reveals that approximately one-third of the speakers in the dataset have fewer than 100 examples, while
96_5_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speakers
.md
</div> 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 improve training efficiency and balance the dataset, we can limit the data to speakers with between 100 and 400 examples. ```py >>> def select_speaker(speaker_id): ... return 100 <= speaker_counts[speaker_id] <= 400
96_5_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speakers
.md
>>> dataset = dataset.filter(select_speaker, input_columns=["speaker_id"]) ``` Let's check how many speakers remain: ```py >>> len(set(dataset["speaker_id"])) 42 ``` Let's see how many examples are left: ```py >>> len(dataset) 9973 ``` 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,
96_5_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speakers
.md
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 entire dataset, which is a time-consuming process that involves loading and decoding each audio file. As such, we have chosen to skip this step here.
96_5_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speaker-embeddings
.md
To enable the TTS model to differentiate between multiple speakers, you'll need to create a speaker embedding for each example. The speaker embedding is an additional input into the model that captures a particular speaker's voice characteristics. To generate these speaker embeddings, use the pre-trained [spkrec-xvect-voxceleb](https://huggingface.co/speechbrain/spkrec-xvect-voxceleb) model from SpeechBrain.
96_6_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speaker-embeddings
.md
model from SpeechBrain. Create a function `create_speaker_embedding()` that takes an input audio waveform and outputs a 512-element vector containing the corresponding speaker embedding. ```py >>> import os >>> import torch >>> from speechbrain.inference.classifiers import EncoderClassifier >>> from accelerate.test_utils.testing import get_backend
96_6_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speaker-embeddings
.md
>>> spk_model_name = "speechbrain/spkrec-xvect-voxceleb" >>> device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) >>> speaker_model = EncoderClassifier.from_hparams( ... source=spk_model_name, ... run_opts={"device": device}, ... savedir=os.path.join("/tmp", spk_model_name), ... )
96_6_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speaker-embeddings
.md
>>> def create_speaker_embedding(waveform): ... with torch.no_grad(): ... speaker_embeddings = speaker_model.encode_batch(torch.tensor(waveform)) ... speaker_embeddings = torch.nn.functional.normalize(speaker_embeddings, dim=2) ... speaker_embeddings = speaker_embeddings.squeeze().cpu().numpy() ... return speaker_embeddings ``` It's important to note that the `speechbrain/spkrec-xvect-voxceleb` model was trained on English speech from the VoxCeleb
96_6_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speaker-embeddings
.md
``` 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 hold true in all cases. For optimal results, we recommend training an X-vector model on the target speech first. This will ensure that the model
96_6_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#speaker-embeddings
.md
For optimal results, we recommend training an X-vector model on the target speech first. This will ensure that the model is better able to capture the unique voice characteristics present in the Dutch language.
96_6_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
Finally, let's process the data into the format the model expects. Create a `prepare_dataset` function that takes in a single example and uses the `SpeechT5Processor` object to tokenize the input text and load the target audio into a log-mel spectrogram. It should also add the speaker embeddings as an additional input. ```py >>> def prepare_dataset(example): ... audio = example["audio"]
96_7_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
... 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"] = example["labels"][0] ... # use SpeechBrain to obtain x-vector ... example["speaker_embeddings"] = create_speaker_embedding(audio["array"])
96_7_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
... return example ``` Verify the processing is correct by looking at a single example: ```py >>> 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: ```py >>> processed_example["speaker_embeddings"].shape (512,) ``` The labels should be a log-mel spectrogram with 80 mel bins. ```py >>> import matplotlib.pyplot as plt
96_7_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
>>> plt.figure() >>> plt.imshow(processed_example["labels"].T) >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/tts_logmelspectrogram_1.png" alt="Log-mel spectrogram with 80 mel bins"/> </div> Side note: If you find this spectrogram confusing, it may be due to your familiarity with the convention of placing low frequencies
96_7_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
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 upside down. Now apply the processing function to the entire dataset. This will take between 5 and 10 minutes. ```py >>> dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names) ```
96_7_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
```py >>> 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 remove anything over 200 tokens. ```py >>> def is_not_too_long(input_ids): ... input_length = len(input_ids) ... return input_length < 200
96_7_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#processing-the-dataset
.md
>>> dataset = dataset.filter(is_not_too_long, input_columns=["input_ids"]) >>> len(dataset) 8259 ``` Next, create a basic train/test split: ```py >>> dataset = dataset.train_test_split(test_size=0.1) ```
96_7_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
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 are replaced with the special value `-100`. This special value instructs the model to ignore that part of the spectrogram when calculating the spectrogram loss. ```py >>> from dataclasses import dataclass >>> from typing import Any, Dict, List, Union
96_8_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
>>> @dataclass ... class TTSDataCollatorWithPadding: ... processor: Any ... 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["speaker_embeddings"] for feature in features]
96_8_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
... # collate the inputs and targets into a batch ... batch = processor.pad(input_ids=input_ids, labels=label_features, return_tensors="pt") ... # replace padding with -100 to ignore loss correctly ... batch["labels"] = batch["labels"].masked_fill(batch.decoder_attention_mask.unsqueeze(-1).ne(1), -100) ... # not used during fine-tuning ... del batch["decoder_attention_mask"]
96_8_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
... # round down target lengths to multiple of reduction factor ... if model.config.reduction_factor > 1: ... target_lengths = torch.tensor([len(feature["input_values"]) for feature in label_features]) ... target_lengths = target_lengths.new( ... [length - length % model.config.reduction_factor for length in target_lengths] ... ) ... max_length = max(target_lengths)
96_8_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
... ) ... max_length = max(target_lengths) ... batch["labels"] = batch["labels"][:, :max_length]
96_8_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
... # also add in the speaker embeddings ... batch["speaker_embeddings"] = torch.tensor(speaker_features)
96_8_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#data-collator
.md
... return batch ``` 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 maximum length of the batch down to be a multiple of 2. ```py >>> data_collator = TTSDataCollatorWithPadding(processor=processor) ```
96_8_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
Load the pre-trained model from the same checkpoint as you used for loading the processor: ```py >>> from transformers import SpeechT5ForTextToSpeech
96_9_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
>>> model = SpeechT5ForTextToSpeech.from_pretrained(checkpoint) ``` The `use_cache=True` option is incompatible with gradient checkpointing. Disable it for training. ```py >>> 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: ```python >>> from transformers import Seq2SeqTrainingArguments
96_9_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
>>> 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=4000, ... gradient_checkpointing=True, ... fp16=True, ... eval_strategy="steps", ... per_device_eval_batch_size=2, ... save_steps=1000, ... eval_steps=1000, ... logging_steps=25,
96_9_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
... per_device_eval_batch_size=2, ... save_steps=1000, ... eval_steps=1000, ... logging_steps=25, ... report_to=["tensorboard"], ... load_best_model_at_end=True, ... greater_is_better=False, ... label_names=["labels"], ... push_to_hub=True, ... ) ``` Instantiate the `Trainer` object and pass the model, dataset, and data collator to it. ```py >>> from transformers import Seq2SeqTrainer
96_9_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
>>> trainer = Seq2SeqTrainer( ... args=training_args, ... model=model, ... train_dataset=dataset["train"], ... eval_dataset=dataset["test"], ... data_collator=data_collator, ... processing_class=processor, ... ) ``` 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
96_9_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
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_accumulation_steps` by 2x to compensate. ```py >>> trainer.train() ``` To be able to use your checkpoint with a pipeline, make sure to save the processor with the checkpoint: ```py >>> processor.save_pretrained("YOUR_ACCOUNT_NAME/speecht5_finetuned_voxpopuli_nl") ```
96_9_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#train-the-model
.md
```py >>> processor.save_pretrained("YOUR_ACCOUNT_NAME/speecht5_finetuned_voxpopuli_nl") ``` Push the final model to the 🤗 Hub: ```py >>> trainer.push_to_hub() ```
96_9_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#inference-with-a-pipeline
.md
Great, now that you've fine-tuned a model, you can use it for inference! First, let's see how you can use it with a corresponding pipeline. Let's create a `"text-to-speech"` pipeline with your checkpoint: ```py >>> from transformers import pipeline
96_10_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#inference-with-a-pipeline
.md
>>> 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.: ```py >>> text = "hallo allemaal, ik praat nederlands. groetjes aan iedereen!" ``` To use SpeechT5 with the pipeline, you'll need a speaker embedding. Let's get it from an example in the test dataset: ```py >>> example = dataset["test"][304] >>> speaker_embeddings = torch.tensor(example["speaker_embeddings"]).unsqueeze(0) ```
96_10_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#inference-with-a-pipeline
.md
>>> 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: ```py >>> forward_params = {"speaker_embeddings": speaker_embeddings} >>> output = pipe(text, forward_params=forward_params) >>> output {'audio': array([-6.82714235e-05, -4.26525949e-04, 1.06134125e-04, ..., -1.22392643e-03, -7.76011671e-04, 3.29112721e-04], dtype=float32),
96_10_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#inference-with-a-pipeline
.md
-1.22392643e-03, -7.76011671e-04, 3.29112721e-04], dtype=float32), 'sampling_rate': 16000} ``` You can then listen to the result: ```py >>> from IPython.display import Audio >>> Audio(output['audio'], rate=output['sampling_rate']) ```
96_10_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
You can achieve the same inference results without using the pipeline, however, more steps will be required. Load the model from the 🤗 Hub: ```py >>> model = SpeechT5ForTextToSpeech.from_pretrained("YOUR_ACCOUNT/speecht5_finetuned_voxpopuli_nl") ``` Pick an example from the test dataset obtain a speaker embedding. ```py >>> example = dataset["test"][304] >>> speaker_embeddings = torch.tensor(example["speaker_embeddings"]).unsqueeze(0) ``` Define the input text and tokenize it. ```py
96_11_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
``` Define the input text and tokenize it. ```py >>> text = "hallo allemaal, ik praat nederlands. groetjes aan iedereen!" >>> inputs = processor(text=text, return_tensors="pt") ``` Create a spectrogram with your model: ```py >>> spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings) ``` Visualize the spectrogram, if you'd like to: ```py >>> plt.figure() >>> plt.imshow(spectrogram.T) >>> plt.show() ``` <div class="flex justify-center">
96_11_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
```py >>> plt.figure() >>> plt.imshow(spectrogram.T) >>> plt.show() ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/tts_logmelspectrogram_2.png" alt="Generated log-mel spectrogram"/> </div> Finally, use the vocoder to turn the spectrogram into sound. ```py >>> with torch.no_grad(): ... speech = vocoder(spectrogram)
96_11_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
>>> from IPython.display import Audio
96_11_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
>>> Audio(speech.numpy(), rate=16000) ``` 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 using a different speaker embedding.
96_11_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
when using English speaker embeddings. If the synthesized speech sounds poor, try using a different speaker embedding. Increasing the training duration is also likely to enhance the quality of the results. Even so, the speech clearly is Dutch instead of English, and it does capture the voice characteristics of the speaker (compare to the original audio in the example). Another thing to experiment with is the model's configuration. For example, try using `config.reduction_factor = 1` to
96_11_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/text-to-speech.md
https://huggingface.co/docs/transformers/en/tasks/text-to-speech/#run-inference-manually
.md
Another thing to experiment with is the model's configuration. For example, try using `config.reduction_factor = 1` to see if this improves the results. Finally, it is essential to consider ethical considerations. Although TTS technology has numerous useful applications, it may also be used for malicious purposes, such as impersonating someone's voice without their knowledge or consent. Please use TTS judiciously and responsibly.
96_11_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/
.md
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
97_0_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/
.md
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. -->
97_0_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#audio-classification
.md
[[open-in-colab]] <Youtube id="KWwzcmG98Ds"/> Audio classification - just like with text - assigns a class label as output from the input data. The only difference is instead of text inputs, you have raw audio waveforms. Some practical applications of audio classification include identifying speaker intent, language classification, and even animal species by their sounds. This guide will show you how to:
97_1_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#audio-classification
.md
This guide will show you how to: 1. Fine-tune [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) on the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset to classify speaker intent. 2. Use your fine-tuned model for inference. <Tip> To see all architectures and checkpoints compatible with this task, we recommend checking the [task-page](https://huggingface.co/tasks/audio-classification) </Tip> Before you begin, make sure you have all the necessary libraries installed:
97_1_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#audio-classification
.md
</Tip> Before you begin, make sure you have all the necessary libraries installed: ```bash 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: ```py >>> from huggingface_hub import notebook_login
97_1_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#audio-classification
.md
>>> notebook_login() ```
97_1_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
Start by loading the MInDS-14 dataset from the 🤗 Datasets library: ```py >>> from datasets import load_dataset, Audio
97_2_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
>>> minds = load_dataset("PolyAI/minds14", name="en-US", split="train") ``` Split the dataset's `train` split into a smaller train and test set with the [`~datasets.Dataset.train_test_split`] method. This will give you a chance to experiment and make sure everything works before spending more time on the full dataset. ```py >>> minds = minds.train_test_split(test_size=0.2) ``` Then take a look at the dataset: ```py >>> minds DatasetDict({ train: Dataset({
97_2_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
``` Then take a look at the dataset: ```py >>> minds DatasetDict({ train: Dataset({ features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'], num_rows: 450 }) test: Dataset({ features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'], num_rows: 113 }) }) ```
97_2_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
features: ['path', 'audio', 'transcription', 'english_transcription', 'intent_class', 'lang_id'], num_rows: 113 }) }) ``` While the dataset contains a lot of useful information, like `lang_id` and `english_transcription`, you will focus on the `audio` and `intent_class` in this guide. Remove the other columns with the [`~datasets.Dataset.remove_columns`] method: ```py >>> minds = minds.remove_columns(["path", "transcription", "english_transcription", "lang_id"]) ``` Here's an example: ```py
97_2_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
``` Here's an example: ```py >>> minds["train"][0] {'audio': {'array': array([ 0. , 0. , 0. , ..., -0.00048828, -0.00024414, -0.00024414], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav', 'sampling_rate': 8000}, 'intent_class': 2} ``` There are two fields:
97_2_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
'sampling_rate': 8000}, 'intent_class': 2} ``` 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 integer and vice versa: ```py >>> labels = minds["train"].features["intent_class"].names >>> label2id, id2label = dict(), dict()
97_2_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#load-minds-14-dataset
.md
```py >>> labels = minds["train"].features["intent_class"].names >>> label2id, id2label = dict(), dict() >>> for i, label in enumerate(labels): ... label2id[label] = str(i) ... id2label[str(i)] = label ``` Now you can convert the label id to a label name: ```py >>> id2label[str(2)] 'app_error' ```
97_2_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
The next step is to load a Wav2Vec2 feature extractor to process the audio signal: ```py >>> from transformers import AutoFeatureExtractor
97_3_0
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") ``` The MInDS-14 dataset has a sampling rate of 8kHz (you can find this information in its [dataset card](https://huggingface.co/datasets/PolyAI/minds14)), which means you'll need to resample the dataset to 16kHz to use the pretrained Wav2Vec2 model: ```py >>> minds = minds.cast_column("audio", Audio(sampling_rate=16_000)) >>> minds["train"][0]
97_3_1
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
```py >>> 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/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~APP_ERROR/602b9a5fbb1e6d0fbce91f52.wav', 'sampling_rate': 16000}, 'intent_class': 2} ``` Now create a preprocessing function that:
97_3_2
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
'sampling_rate': 16000}, 'intent_class': 2} ``` Now create a preprocessing function that: 1. Calls the `audio` column to load, and if necessary, resample the audio file. 2. 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](https://huggingface.co/facebook/wav2vec2-base). 3. Set a maximum input length to batch longer inputs without truncating them. ```py
97_3_3
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
3. Set a maximum input length to batch longer inputs without truncating them. ```py >>> 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 ```
97_3_4
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
... ) ... return inputs ``` 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 unnecessary columns and rename `intent_class` to `label`, as required by the model: ```py >>> encoded_minds = minds.map(preprocess_function, remove_columns="audio", batched=True)
97_3_5
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#preprocess
.md
```py >>> encoded_minds = minds.map(preprocess_function, remove_columns="audio", batched=True) >>> encoded_minds = encoded_minds.rename_column("intent_class", "label") ```
97_3_6
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tasks/audio_classification.md
https://huggingface.co/docs/transformers/en/tasks/audio_classification/#evaluate
.md
Including a metric during training is often helpful for evaluating your model's performance. You can quickly load an evaluation method with the 🤗 [Evaluate](https://huggingface.co/docs/evaluate/index) library. For this task, load the [accuracy](https://huggingface.co/spaces/evaluate-metric/accuracy) metric (see the 🤗 Evaluate [quick tour](https://huggingface.co/docs/evaluate/a_quick_tour) to learn more about how to load and compute a metric): ```py >>> import evaluate
97_4_0