wav2vec2 large xlsr 53 gender recognition librispeech

提供商alefiury
分类audio-classification
许可证apache-2.0
下载量639.4K
星标0

简介

这是一个基于 Meta 的 wav2vec2-large-xlsr-53 预训练模型微调而来的性别识别工具。它利用了强大的跨语言语音表征能力,专门针对 LibriSpeech 数据集进行了优化,能够从音频片段中高效提取声学特征以判断说话者性别。对于需要快速集成语音分析功能的开发者来说,该模型上手门槛低,可直接通过 Hugging Face 框架调用,非常适合用于用户画像分析、自动化语音标注或简单的智能交互场景,是构建语音分类流水线的一个轻量级起点。

核心亮点

  • 基于强力的 XLS-R 跨语言预训练模型
  • 专注于语音性别分类,识别精度可靠
  • 适配 Hugging Face 生态,部署调用简单
  • 适用于用户分析及语音数据自动化标注

使用方法

安装依赖
# 安装 Hugging Face transformers
pip install transformers torch
SDK 使用
# 使用 transformers 加载模型
from transformers import AutoModel, AutoTokenizer

model = AutoModel.from_pretrained("alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech")
tokenizer = AutoTokenizer.from_pretrained("alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech")

Hugging Face 下载

我们推荐使用命令行或者 Hugging Face Hub SDK 来进行模型的下载。

操作指引:在下载前,请先通过如下命令安装 huggingface_hub:

操作指引
pip install -U huggingface_hub

命令行下载

下载完整模型库

下载完整模型库
huggingface-cli download alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech

下载单个文件到指定本地文件夹(以下载 config.json 到当前路径下 ./dir 目录为例)

下载单个文件到指定本地文件夹(以下载 config.json 到当前路径下 ./dir 目录为例)
huggingface-cli download alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech config.json --local-dir ./dir

更多命令行下载选项,可参见官方文档

SDK 下载

SDK 下载
# 模型下载
from huggingface_hub import snapshot_download
model_dir = snapshot_download('alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech')

Git 下载

请确保 lfs 已经被正确安装

Git 下载
git lfs install
git clone https://huggingface.co/alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech

如果您希望跳过 lfs 大文件下载,可以使用如下命令

跳过 LFS
GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech

模型文件托管在 Hugging Face Hub,使用 HF CLI / SDK / Git 直接下载,不经过本站。

PyTorch / Transformers 使用

安装 Transformers

安装 Transformers
pip install -U transformers torch

模型加载和推理

模型加载和推理
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained('alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech')
tokenizer = AutoTokenizer.from_pretrained('alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech')

完整文档

来源: HuggingFace

---
license: apache-2.0
tags:

  • generated_from_trainer

datasets:
  • librispeech_asr

metrics:
  • f1

base_model: facebook/wav2vec2-xls-r-300m
model-index:
  • name: weights

results: []
---

<!-- This model card has been generated automatically according to the information the Trainer had access to. You
should probably proofread and complete it, then remove this comment. -->

wav2vec2-large-xlsr-53-gender-recognition-librispeech

This model is a fine-tuned version of facebook/wav2vec2-xls-r-300m on Librispeech-clean-100 for gender recognition.
It achieves the following results on the evaluation set:

  • Loss: 0.0061

  • F1: 0.9993

Compute your inferences

python
import os
import random
from glob import glob
from typing import List, Optional, Union, Dict

import tqdm
import torch
import torchaudio
import numpy as np
import pandas as pd
from torch import nn
from torch.utils.data import DataLoader
from torch.nn import functional as F
from transformers import (
AutoFeatureExtractor,
AutoModelForAudioClassification,
Wav2Vec2Processor
)

class CustomDataset(torch.utils.data.Dataset):
def __init__(
self,
dataset: List,
basedir: Optional[str] = None,
sampling_rate: int = 16000,
max_audio_len: int = 5,
):
self.dataset = dataset
self.basedir = basedir

self.sampling_rate = sampling_rate
self.max_audio_len = max_audio_len

def __len__(self):
"""
Return the length of the dataset
"""
return len(self.dataset)

def __getitem__(self, index):
if self.basedir is None:
filepath = self.dataset[index]
else:
filepath = os.path.join(self.basedir, self.dataset[index])

speech_array, sr = torchaudio.load(filepath)

if speech_array.shape[0] > 1:
speech_array = torch.mean(speech_array, dim=0, keepdim=True)

if sr != self.sampling_rate:
transform = torchaudio.transforms.Resample(sr, self.sampling_rate)
speech_array = transform(speech_array)
sr = self.sampling_rate

len_audio = speech_array.shape[1]

# Pad or truncate the audio to match the desired length
if len_audio < self.max_audio_len * self.sampling_rate:
# Pad the audio if it's shorter than the desired length
padding = torch.zeros(1, self.max_audio_len * self.sampling_rate - len_audio)
speech_array = torch.cat([speech_array, padding], dim=1)
else:
# Truncate the audio if it's longer than the desired length
speech_array = speech_array[:, :self.max_audio_len * self.sampling_rate]

speech_array = speech_array.squeeze().numpy()

return {"input_values": speech_array, "attention_mask": None}

class CollateFunc:
def __init__(
self,
processor: Wav2Vec2Processor,
padding: Union[bool, str] = True,
pad_to_multiple_of: Optional[int] = None,
return_attention_mask: bool = True,
sampling_rate: int = 16000,
max_length: Optional[int] = None,
):
self.sampling_rate = sampling_rate
self.processor = processor
self.padding = padding
self.pad_to_multiple_of = pad_to_multiple_of
self.return_attention_mask = return_attention_mask
self.max_length = max_length

def __call__(self, batch: List[Dict[str, np.ndarray]]):
# Extract input_values from the batch
input_values = [item["input_values"] for item in batch]

batch = self.processor(
input_values,
sampling_rate=self.sampling_rate,
return_tensors="pt",
padding=self.padding,
max_length=self.max_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_attention_mask=self.return_attention_mask
)

return {
"input_values": batch.input_values,
"attention_mask": batch.attention_mask if self.return_attention_mask else None
}

def predict(test_dataloader, model, device: torch.device):
"""
Predict the class of the audio
"""
model.to(device)
model.eval()
preds = []

with torch.no_grad():
for batch in tqdm.tqdm(test_dataloader):
input_values, attention_mask = batch['input_values'].to(device), batch['attention_mask'].to(device)

logits = model(input_values, attention_mask=attention_mask).logits
scores = F.softmax(logits, dim=-1)

pred = torch.argmax(scores, dim=1).cpu().detach().numpy()

preds.extend(pred)

return preds

def get_gender(model_name_or_path: str, audio_paths: List[str], label2id: Dict, id2label: Dict, device: torch.device):
num_labels = 2

feature_extractor = AutoFeatureExtractor.from_pretrained(model_name_or_path)
model = AutoModelForAudioClassification.from_pretrained(
pretrained_model_name_or_path=model_name_or_path,
num_labels=num_labels,
label2id=label2id,
id2label=id2label,
)

test_dataset = CustomDataset(audio_paths, max_audio_len=5) # for 5-second audio

data_collator = CollateFunc(
processor=feature_extractor,
padding=True,
sampling_rate=16000,
)

test_dataloader = DataLoader(
dataset=test_dataset,
batch_size=16,
collate_fn=data_collator,
shuffle=False,
num_workers=2
)

preds = predict(test_dataloader=test_dataloader, model=model, device=device)

return preds

model_name_or_path = "alefiury/wav2vec2-large-xlsr-53-gender-recognition-librispeech"

audio_paths = [] # Must be a list with absolute paths of the audios that will be used in inference
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

label2id = {
"female": 0,
"male": 1
}

id2label = {
0: "female",
1: "male"
}

num_labels = 2

preds = get_gender(model_name_or_path, audio_paths, label2id, id2label, device)

Training and evaluation data

The Librispeech-clean-100 dataset was used to train the model, with 70% of the data used for training, 10% for validation, and 20% for testing.

Training hyperparameters

The following hyperparameters were used during training:

  • learning_rate: 3e-05

  • train_batch_size: 4

  • eval_batch_size: 4

  • seed: 42

  • gradient_accumulation_steps: 4

  • total_train_batch_size: 16

  • optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08

  • lr_scheduler_type: linear

  • lr_scheduler_warmup_ratio: 0.1

  • num_epochs: 1

  • mixed_precision_training: Native AMP

Training results

| Training Loss | Epoch | Step | Validation Loss | F1 |
|:-------------:|:-----:|:----:|:---------------:|:------:|
| 0.002 | 1.0 | 1248 | 0.0061 | 0.9993 |

Framework versions

  • Transformers 4.28.0
  • Pytorch 2.0.0+cu118
  • Tokenizers 0.13.3