Transformers 文件

音訊分類

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

音訊分類

音訊分類 - 就像文字分類一樣 - 將類別標籤作為輸入資料的輸出。唯一的區別是,輸入不再是文字,而是原始的音訊波形。音訊分類的一些實際應用包括識別說話者意圖、語言分類,甚至透過聲音識別動物物種。

本指南將向您展示如何:

  1. MInDS-14 資料集上微調 Wav2Vec2 以分類說話者意圖。
  2. 使用您的微調模型進行推理。

要檢視所有與此任務相容的架構和檢查點,我們建議檢視 任務頁面

在開始之前,請確保您已安裝所有必要的庫

pip install transformers datasets evaluate

我們鼓勵您登入 Hugging Face 賬戶,以便您可以上傳並與社群分享您的模型。出現提示時,輸入您的令牌進行登入

>>> from huggingface_hub import notebook_login

>>> notebook_login()

載入 MInDS-14 資料集

首先從 🤗 Datasets 庫載入 MInDS-14 資料集

>>> from datasets import load_dataset, Audio

>>> minds = load_dataset("PolyAI/minds14", name="en-US", split="train")

使用 train_test_split 方法將資料集的 `train` 分割成一個更小的訓練集和測試集。這將讓你有機會進行實驗,並在花費更多時間處理整個資料集之前確保一切正常。

>>> minds = minds.train_test_split(test_size=0.2)

然後檢視資料集

>>> 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
    })
})

雖然資料集包含許多有用的資訊,如 `lang_id` 和 `english_transcription`,但本指南中您將重點關注 `audio` 和 `intent_class`。使用 remove_columns 方法移除其他列。

>>> minds = minds.remove_columns(["path", "transcription", "english_transcription", "lang_id"])

下面是一個例子

>>> 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}

有兩個欄位

  • `audio`: 語音訊號的一維 `array`,必須呼叫它來載入和重取樣音訊檔案。
  • `intent_class`: 表示說話者意圖的類別 ID。

為了讓模型更容易從標籤 ID 獲取標籤名稱,建立一個將標籤名稱對映到整數的字典,反之亦然

>>> 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

現在你可以將標籤 ID 轉換為標籤名稱了

>>> id2label[str(2)]
'app_error'

預處理

下一步是載入 Wav2Vec2 特徵提取器來處理音訊訊號

>>> from transformers import AutoFeatureExtractor

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")

MInDS-14 資料集的取樣率為 8kHz(您可以在其資料集卡片中找到此資訊),這意味著您需要將資料集重取樣到 16kHz 才能使用預訓練的 Wav2Vec2 模型

>>> 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}

現在建立一個預處理函式,該函式將

  1. 呼叫 `audio` 列以載入,並在必要時重新取樣音訊檔案。
  2. 檢查音訊檔案的取樣率是否與預訓練模型的音訊資料取樣率匹配。您可以在 Wav2Vec2 模型卡片中找到此資訊。
  3. 設定最大輸入長度以批次處理較長的輸入而不截斷它們。
>>> 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

要對整個資料集應用預處理函式,請使用 🤗 Datasets 的 map 函式。您可以透過設定 `batched=True` 一次處理資料集的多個元素來加速 `map`。移除不必要的列並將 `intent_class` 重新命名為 `label`,這是模型所要求的。

>>> encoded_minds = minds.map(preprocess_function, remove_columns="audio", batched=True)
>>> encoded_minds = encoded_minds.rename_column("intent_class", "label")

評估

在訓練期間包含一個度量指標通常有助於評估模型的效能。您可以使用 🤗 Evaluate 庫快速載入評估方法。對於此任務,載入 accuracy 度量(請參閱 🤗 Evaluate 快速入門以瞭解如何載入和計算度量指標的更多資訊)

>>> import evaluate

>>> accuracy = evaluate.load("accuracy")

然後建立一個函式,將您的預測和標籤傳遞給 compute 以計算準確度。

>>> import numpy as np


>>> def compute_metrics(eval_pred):
...     predictions = np.argmax(eval_pred.predictions, axis=1)
...     return accuracy.compute(predictions=predictions, references=eval_pred.label_ids)

您的 compute_metrics 函式現在可以使用了,您將在設定訓練時再次用到它。

訓練

Pytorch
隱藏 Pytorch 內容

如果您不熟悉如何使用 Trainer 對模型進行微調,請參閱此處的基本教程!

現在您已準備好開始訓練模型!使用 AutoModelForAudioClassification 載入 Wav2Vec2,並傳入預期的標籤數量和標籤對映。

>>> from transformers import AutoModelForAudioClassification, TrainingArguments, Trainer

>>> num_labels = len(id2label)
>>> model = AutoModelForAudioClassification.from_pretrained(
...     "facebook/wav2vec2-base", num_labels=num_labels, label2id=label2id, id2label=id2label
... )

此時,只剩下三個步驟

  1. TrainingArguments 中定義您的訓練超引數。唯一必需的引數是 `output_dir`,它指定了儲存模型的位置。您將透過設定 `push_to_hub=True` 將此模型推送到 Hub(您需要登入 Hugging Face 才能上傳模型)。在每個 epoch 結束時,Trainer 將評估準確性並儲存訓練檢查點。
  2. 將訓練引數與模型、資料集、分詞器、資料整理器和 compute_metrics 函式一起傳遞給 Trainer
  3. 呼叫 train() 來微調您的模型。
>>> training_args = TrainingArguments(
...     output_dir="my_awesome_mind_model",
...     eval_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.1,
...     logging_steps=10,
...     load_best_model_at_end=True,
...     metric_for_best_model="accuracy",
...     push_to_hub=True,
... )

>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     train_dataset=encoded_minds["train"],
...     eval_dataset=encoded_minds["test"],
...     processing_class=feature_extractor,
...     compute_metrics=compute_metrics,
... )

>>> trainer.train()

訓練完成後,使用 push_to_hub() 方法將您的模型分享到 Hub,以便所有人都可以使用您的模型。

>>> trainer.push_to_hub()

有關如何微調音訊分類模型的更深入示例,請檢視相應的 PyTorch notebook

推理

太棒了,現在您已經微調了一個模型,您可以將其用於推理了!

載入音訊檔案進行推理。如有必要,請記住將音訊檔案的取樣率重取樣以匹配模型的取樣率。

>>> 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"]

嘗試對微調模型進行推理的最簡單方法是在 pipeline() 中使用它。例項化一個用於音訊分類的 `pipeline`,並傳入您的音訊檔案

>>> 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_account'},
    {'score': 0.07667109370231628, 'label': 'pay_bill'},
    {'score': 0.0755252093076706, 'label': 'balance'}
]

如果需要,您也可以手動複製 pipeline 的結果

Pytorch
隱藏 Pytorch 內容

載入一個特徵提取器來預處理音訊檔案並以 PyTorch 張量的形式返回 `input`

>>> from transformers import AutoFeatureExtractor

>>> feature_extractor = AutoFeatureExtractor.from_pretrained("stevhliu/my_awesome_minds_model")
>>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")

將您的輸入傳遞給模型並返回 logits

>>> from transformers import AutoModelForAudioClassification

>>> model = AutoModelForAudioClassification.from_pretrained("stevhliu/my_awesome_minds_model")
>>> with torch.no_grad():
...     logits = model(**inputs).logits

獲取機率最高的類別,並使用模型的 `id2label` 對映將其轉換為標籤

>>> import torch

>>> predicted_class_ids = torch.argmax(logits).item()
>>> predicted_label = model.config.id2label[predicted_class_ids]
>>> predicted_label
'cash_deposit'
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.