/ Модель

Характеристики

Параметры
403 млн
Лицензия
Apache 2.0
Архитектура
wav2vec2 · dense
Базовая модель
wav2vec2-large-xlsr-53
Библиотека
transformers
Опубликована
20 сен 2024

speech-emotion-recognition-with-facebook-wav2vec2-large-xlsr-53

Классификация текстаТекст → label3 профессии

Дообученная на речевых данных модель Wav2Vec2 классифицирует аудио по семи категориям эмоций.

548скачиваний за 30 дней2лайкавеса обновлены15 дек 2024

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Модель firdhokk/speech-emotion-recognition-with-facebook-wav2vec2-large-xlsr-53 — дообученная разработчиком модель Wav2Vec2 Large XLSR-53 для классификации эмоций в аудиозаписях речи. Она принимает аудио и относит его к одному из семи классов: гнев, отвращение, страх, радость, нейтральное состояние, грусть или удивление. В README описано обучение на данных из RAVDESS, SAVEE, TESS и URDU; базовая архитектура извлекает многоязычные речевые представления. Модель содержит около 402,7 млн параметров и доступна в формате safetensors для Transformers.

Её можно применять для анализа эмоциональной окраски речи в записях и голосовых приложениях. В README приведены метрики оценки, однако их условия и детализация тестового набора ограничены, поэтому результаты могут не переноситься на другие говорящие, языки и акустические условия. Модель распространяется по лицензии Apache-2.0.

Сценарии применения

  • Определение эмоциональной окраски голосовых записей
  • Классификация речи по категориям гнева, радости, грусти и другим эмоциям
  • Анализ эмоций в аудиоматериалах для исследований
  • Добавление распознавания эмоций в приложение для обработки голосовых сообщений

Ограничения

Метрики в README приведены без подробного описания состава и условий тестирования; качество на других языках, говорящих и акустических условиях не подтверждено. Класс calm исключён при обучении, а поддержка языков для классификации эмоций отдельно не описана.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

🎧 Speech Emotion Recognition with Wav2Vec2

This project leverages the Wav2Vec2 model to recognize emotions in speech. The goal is to classify audio recordings into different emotional categories, such as Happy, Sad, Surprised, and etc.

🗂 Dataset

The dataset used for training and evaluation is sourced from multiple datasets, including:

The dataset contains recordings labeled with various emotions. Below is the distribution of the emotions in the dataset:

EmotionCount
sad752
happy752
angry752
neutral716
disgust652
fearful652
surprised652
calm192

This distribution reflects the balance of emotions in the dataset, with some emotions having more samples than others. Excluded the "calm" emotion during training due to its underrepresentation.

🎤 Preprocessing

  • Audio Loading: Using Librosa to load the audio files and convert them to numpy arrays.
  • Feature Extraction: The audio data is processed using the Wav2Vec2 Feature Extractor, which standardizes and normalizes the audio features for input to the model.

🔧 Model

The model used is the Wav2Vec2 Large XLR-53 model, fine-tuned for audio classification tasks:

  • Model: facebook/wav2vec2-large-xlsr-53
  • Output: Emotion labels (Angry', 'Disgust', 'Fearful', 'Happy', 'Neutral', 'Sad', 'Surprised') I map the emotion labels to numeric IDs and use them for model training and evaluation.

⚙️ Training

The model is trained with the following parameters:

  • Learning Rate: 5e-05
  • Train Batch Size: 2
  • Eval Batch Size: 2
  • Random Seed: 42
  • Gradient Accumulation Steps: 5
  • Total Train Batch Size: 10 (effective batch size after gradient accumulation)
  • Optimizer: Adam with parameters: betas=(0.9, 0.999) and epsilon=1e-08
  • Learning Rate Scheduler: linear
  • Warmup Ratio for LR Scheduler: 0.1
  • Number of Epochs: 25
  • Mixed Precision Training: Native AMP (Automatic Mixed Precision)

These parameters ensure efficient model training and stability, especially when dealing with large datasets and deep models like Wav2Vec2. The training utilizes Wandb for experiment tracking and monitoring.

📊 Metrics

The following evaluation metrics were obtained after training the model:

  • Loss: 0.4989
  • Accuracy: 0.9168
  • Precision: 0.9209
  • Recall: 0.9168
  • F1 Score: 0.9166

These metrics demonstrate the model's performance on the speech emotion recognition task. The high values for accuracy, precision, recall, and F1 score indicate that the model is effectively identifying emotional states from speech data.

🧪 Results

After training, the model is evaluated on the test dataset, and the results are monitored using Wandb in this Link.

Training LossEpochStepValidation LossAccuracyPrecisionRecallF1
1.93430.99953941.92770.25050.14250.25050.1691
1.79441.99907881.64460.45740.57590.45740.4213
1.46012.998511821.32420.59530.61830.59530.5709
1.05513.998015761.07640.66230.66590.66230.6447
0.89345.019710.92090.70590.71720.70590.6825
1.11565.999523650.82920.74650.76350.74650.7442
0.63076.999027590.64390.80430.80900.80430.8020
0.7747.998531530.66660.79210.81170.79210.7916
0.55378.998035470.51110.82450.82680.82450.8205
0.376210.039420.55060.83060.83900.83060.8296
0.71610.999543360.54990.82760.84650.82760.8268
0.537211.999047300.54630.83770.86060.83770.8404
0.374612.998551240.47580.86110.87140.86110.8597
0.431713.998055180.44380.87420.88430.87420.8756
0.210415.059130.44260.88030.88640.88030.8806
0.319315.999563070.47410.86710.87510.86710.8683
0.344516.999067010.38500.90370.90470.90370.9038
0.277717.998570950.48020.88340.89230.88340.8836
0.440618.998074890.40530.90470.90960.90470.9043
0.170720.078840.44340.90670.91290.90670.9069
0.213820.999582780.50510.90370.91550.90370.9053
0.181221.999086720.42380.89550.90070.89550.8953
0.363922.998590660.40210.91380.91820.91380.9143
0.319323.998094600.49890.91680.92090.91680.9166
0.206724.987398500.49590.89760.90320.89760.8975

🚀 How to Use

from transformers import AutoModelForAudioClassification, AutoFeatureExtractor
import librosa
import torch
import numpy as np

model_id = "firdhokk/speech-emotion-recognition-with-facebook-wav2vec2-large-xlsr-53"
model = AutoModelForAudioClassification.from_pretrained(model_id)

feature_extractor = AutoFeatureExtractor.from_pretrained(model_id, do_normalize=True, return_attention_mask=True)
id2label = model.config.id2label
def preprocess_audio(audio_path, feature_extractor, max_duration=30.0):
    audio_array, sampling_rate = librosa.load(audio_path, sr=feature_extractor.sampling_rate)
    
    max_length = int(feature_extractor.sampling_rate * max_duration)
    if len(audio_array) > max_length:
        audio_array = audio_array[:max_length]
    else:
        audio_array = np.pad(audio_array, (0, max_length - len(audio_array)))

    inputs = feature_extractor(
        audio_array,
        sampling_rate=feature_extractor.sampling_rate,
        max_length=max_length,
        truncation=True,
        return_attention_mask=True,
        return_tensors="pt",
    )
    return inputs
def predict_emotion(audio_path, model, feature_extractor, id2label, max_duration=30.0):
    inputs = preprocess_audio(audio_path, feature_extractor, max_duration)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = model.to(device)
    inputs = {key: value.to(device) for key, value in inputs.items()}

    with torch.no_grad():
        outputs = model(**inputs)

    logits = outputs.logits
    predicted_id = torch.argmax(logits, dim=-1).item()
    predicted_label = id2label[predicted_id]
    
    return predicted_label
audio_path = "/content/drive/MyDrive/Audio/Speech_URDU/Happy/SM5_F4_H058.wav"

predicted_emotion = predict_emotion(audio_path, model, feature_extractor, id2label)
print(f"Predicted Emotion: {predicted_emotion}")

🎯 Framework versions

  • Transformers 4.44.2
  • Pytorch 2.4.1+cu121
  • Datasets 3.0.0
  • Tokenizers 0.19.1

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers · text-classification

Нельзя запустить

Для архитектуры wav2vec2 нет загрузчика под задачу text-classification.

Класс архитектуры
Wav2Vec2ForSequenceClassification
Ревизия весов
611e6db

0 моделей