英文

XLSR-Wav2Vec2自动语音识别(ASR)模型的希腊(el)版本

由希腊陆军学院和希腊克里特技术大学开发

模型描述

更新:我们使用额外的来自CSS10的1.22GB数据集重复了微调过程。

Wav2Vec2是用于自动语音识别(ASR)的预训练模型,由Alexei Baevski,Michael Auli和Alex Conneau于2020年9月发布。在Wav2Vec2在英语ASR数据集LibriSpeech上展现出卓越性能之后,Facebook AI提出了XLSR-Wav2Vec2。XLSR代表跨语言语音表示,并指的是XLSR-Wav2Vec2在多种语言中学习到的有用的语音表示能力。

类似于Wav2Vec2,XLSR-Wav2Vec2从数十万小时的超过50种语言的未标记语音中学习强大的语音表示。与BERT的掩码语言建模类似,该模型通过在将特征向量传递到变压器网络之前随机屏蔽特征向量来学习上下文化的语音表示。

该模型在单个NVIDIA RTX 3080上进行了50个时期的训练,大约8小时。

如何进行推断使用:

对于实时演示,请确保语音文件采样率为16kHz。

在ASR_Inference.ipynb中提供了在CommonVoice提取上测试的说明。下面还提供了代码片段:

#!/usr/bin/env python
# coding: utf-8

# Loading dependencies and defining preprocessing functions 

from transformers import Wav2Vec2ForCTC
from transformers import Wav2Vec2Processor
from datasets import load_dataset, load_metric
import re
import torchaudio
import librosa
import numpy as np
from datasets import load_dataset, load_metric
import torch

chars_to_ignore_regex = '[\\\\\\\\,\\\\\\\\?\\\\\\\\.\\\\\\\\!\\\\\\\\-\\\\\\\\;\\\\\\\\:\\\\\\\\"\\\\\\\\“\\\\\\\\%\\\\\\\\‘\\\\\\\\”\\\\\\\\�]'

def remove_special_characters(batch):
    batch["text"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower() + " "
    return batch

def speech_file_to_array_fn(batch):
    speech_array, sampling_rate = torchaudio.load(batch["path"])
    batch["speech"] = speech_array[0].numpy()
    batch["sampling_rate"] = sampling_rate
    batch["target_text"] = batch["text"]
    return batch

def resample(batch):
    batch["speech"] = librosa.resample(np.asarray(batch["speech"]), 48_000, 16_000)
    batch["sampling_rate"] = 16_000
    return batch

def prepare_dataset(batch):
    # check that all files have the correct sampling rate
    assert (
        len(set(batch["sampling_rate"])) == 1
    ), f"Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."

    batch["input_values"] = processor(batch["speech"], sampling_rate=batch["sampling_rate"][0]).input_values
    
    with processor.as_target_processor():
        batch["labels"] = processor(batch["target_text"]).input_ids
    return batch


# Loading model and dataset processor

model = Wav2Vec2ForCTC.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek").to("cuda")
processor = Wav2Vec2Processor.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek")


# Preparing speech dataset to be suitable for inference

common_voice_test = load_dataset("common_voice", "el", split="test")

common_voice_test = common_voice_test.remove_columns(["accent", "age", "client_id", "down_votes", "gender", "locale", "segment", "up_votes"])

common_voice_test = common_voice_test.map(remove_special_characters, remove_columns=["sentence"])

common_voice_test = common_voice_test.map(speech_file_to_array_fn, remove_columns=common_voice_test.column_names)

common_voice_test = common_voice_test.map(resample, num_proc=8)

common_voice_test = common_voice_test.map(prepare_dataset, remove_columns=common_voice_test.column_names, batch_size=8, num_proc=8, batched=True)


# Loading test dataset

common_voice_test_transcription = load_dataset("common_voice", "el", split="test")


#Performing inference on a random sample. Change the "example" value to try inference on different CommonVoice extracts

example = 123

input_dict = processor(common_voice_test["input_values"][example], return_tensors="pt", sampling_rate=16_000, padding=True)

logits = model(input_dict.input_values.to("cuda")).logits

pred_ids = torch.argmax(logits, dim=-1)

print("Prediction:")
print(processor.decode(pred_ids[0]))
# πού θέλεις να πάμε ρώτησε φοβισμένα ο βασιλιάς

print("\\\\
Reference:")
print(common_voice_test_transcription["sentence"][example].lower())
# πού θέλεις να πάμε; ρώτησε φοβισμένα ο βασιλιάς.

评估

可以按照以下方式评估该模型在Common Voice的希腊测试数据上的效果。

import torch
import torchaudio
from datasets import load_dataset, load_metric
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import re

test_dataset = load_dataset("common_voice", "el", split="test") 
wer = load_metric("wer")

processor = Wav2Vec2Processor.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek") 
model = Wav2Vec2ForCTC.from_pretrained("lighteternal/wav2vec2-large-xlsr-53-greek")
model.to("cuda")

chars_to_ignore_regex = '[\\\\\\\\,\\\\\\\\?\\\\\\\\.\\\\\\\\!\\\\\\\\-\\\\\\\\;\\\\\\\\:\\\\\\\\"\\\\\\\\“\\\\\\\\%\\\\\\\\‘\\\\\\\\”\\\\\\\\�]'
resampler = torchaudio.transforms.Resample(48_000, 16_000)

# Preprocessing the datasets.
# We need to read the aduio files as arrays

def speech_file_to_array_fn(batch):
  batch["sentence"] = re.sub(chars_to_ignore_regex, '', batch["sentence"]).lower()
  speech_array, sampling_rate = torchaudio.load(batch["path"])
  batch["speech"] = resampler(speech_array).squeeze().numpy()
  return batch
  
test_dataset = test_dataset.map(speech_file_to_array_fn)

# Preprocessing the datasets.
# We need to read the aduio files as arrays

def evaluate(batch):
  inputs = processor(batch["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
  with torch.no_grad():
    logits = model(inputs.input_values.to("cuda"), attention_mask=inputs.attention_mask.to("cuda")).logits
  pred_ids = torch.argmax(logits, dim=-1)
  batch["pred_strings"] = processor.batch_decode(pred_ids)
  return batch

result = test_dataset.map(evaluate, batched=True, batch_size=8)
print("WER: {:2f}".format(100 * wer.compute(predictions=result["pred_strings"], references=result["sentence"])))

测试结果:10.497628%

如何进行训练:

在Fine_Tune_XLSR_Wav2Vec2_on_Greek_ASR_with_?_Transformers.ipynb笔记本中提供了复制该过程的说明和代码。

指标

Metric Value
Training Loss 0.0545
Validation Loss 0.1661
CER on CommonVoice Test (%) * 2.8753
WER on CommonVoice Test (%) * 10.4976
* Reference transcripts were lower-cased and striped of punctuation and special characters.

致谢

研究工作得到了希腊研究和创新基金会(HFRI)HFRI博士研究生奖学金(奖学金编号:50,第二次召集)的支持。

基于Patrick von Platen的教程: https://huggingface.co/blog/fine-tune-xlsr-wav2vec2 原始协作笔记本在这里: https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/Fine_Tune_XLSR_Wav2Vec2_on_Turkish_ASR_with_%F0%9F%A4%97_Transformers.ipynb#scrollTo=V7YOT2mnUiea