CoolFace
Modelpublic

saadmannan/speech-emotion-recognition

sourceHugging Facemitupdated 11mo agoView on Hugging Face
0likes
Model Card

๐ŸŽญ Speech Emotion Recognition

![Python 3.10](https://www.python.org/downloads/release/python-3100/) ![PyTorch](https://pytorch.org/) ![License: MIT](https://opensource.org/licenses/MIT)

A production-ready deep learning system for detecting emotions from speech using the RAVDESS dataset. Achieved 75% validation accuracy through enhanced CNN architecture with residual connections, attention mechanisms, and comprehensive data augmentation.

๐ŸŽฏ Project Achievements

โœ… Primary Goal Met: 75% validation accuracy (66.2% test accuracy) โœ… Enhanced Features: 196-dimensional feature vectors โœ… Advanced Architecture: 11.8M parameter CNN with residual blocks and attention โœ… Production Ready: Complete pipeline from data to deployment

๐Ÿ“Š Results Summary

MetricBaseline ModelEnhanced ModelImprovement
Validation Accuracy38.89%75.00%+36.11%
Test Accuracy39.81%66.20%+26.39%
Parameters536K11.8M22x larger
Features143196+37% richer

Per-Class Performance (Test Set)

EmotionBaselineEnhancedImprovementStatus
Neutral78.57%71.43%-7.14%โœ“ Good
Calm85.71%85.71%+0.00%โœ“ Excellent
Happy6.90%58.62%+51.72%๐Ÿš€ Huge gain
Sad0.00%51.72%+51.72%๐Ÿš€ Huge gain
Angry31.03%68.97%+37.94%โœ“ Major gain
Fearful13.79%41.38%+27.59%โœ“ Good gain
Disgust68.97%75.86%+6.89%โœ“ Improved
Surprised55.17%79.31%+24.14%โœ“ Major gain

๐Ÿš€ Quick Start

Installation

bash
# Clone the repository
git clone https://github.com/yourusername/speech-emotion-recognition.git
cd speech-emotion-recognition

# Create conda environment
conda create -n voice_ai python=3.10
conda activate voice_ai

# Install dependencies
pip install -r requirements.txt

Usage

1. Download Dataset
bash
python data/download_dataset.py
2. Prepare Features
bash
python data/prepare_data.py
3. Train Enhanced Model
bash
python models/train_v2.py
4. Evaluate Model
bash
python models/evaluate_v2.py
5. Run Streamlit Demo
bash
streamlit run deployment/app.py

Quick Inference

python
import torch
from models.emotion_cnn_v2 import ImprovedEmotionCNN
from data.prepare_data import extract_features

# Load model
model = ImprovedEmotionCNN(num_classes=8)
checkpoint = torch.load('results/best_model_v2.pth')
model.load_state_dict(checkpoint['model_state_dict'])
model.eval()

# Extract features from audio
features = extract_features('path/to/audio.wav')
features_tensor = torch.FloatTensor(features).unsqueeze(0).unsqueeze(0)

# Predict
with torch.no_grad():
    output = model(features_tensor)
    probs = torch.softmax(output, dim=1)
    predicted = output.argmax(1)

emotions = ['neutral', 'calm', 'happy', 'sad', 'angry', 'fearful', 'disgust', 'surprised']
print(f"Predicted emotion: {emotions[predicted]}")
print(f"Confidence: {probs[0][predicted]:.2%}")

๐Ÿ—๏ธ Architecture

Enhanced Model (V2) - 75% Accuracy

Features (196 dimensions):

  • โ€”Mel-spectrograms: 128 bands
  • โ€”MFCCs: 13 coefficients
  • โ€”Delta MFCCs: 13 (temporal dynamics)
  • โ€”Delta-Delta MFCCs: 13 (acceleration)
  • โ€”Chromagram: 12 (pitch content)
  • โ€”Spectral Contrast: 7 (texture)
  • โ€”Tonnetz: 6 (harmonic content)
  • โ€”Additional: 4 (ZCR, centroid, rolloff, bandwidth)

Model Architecture:

Input (1, 196, 128)
    โ†“
Conv2d 7ร—7, stride 2 โ†’ 64 channels
    โ†“
Residual Block ร— 2 (64 channels) + Channel Attention
    โ†“
Residual Block ร— 2 (128 channels) + Channel Attention
    โ†“
Residual Block ร— 2 (256 channels) + Channel Attention
    โ†“
Residual Block ร— 2 (512 channels) + Channel Attention
    โ†“
Dual Global Pooling (Avg + Max) โ†’ 1024 features
    โ†“
FC 1024 โ†’ 512 โ†’ 256 โ†’ 8 (emotions)

Total Parameters: 11,873,480

Key Improvements:

  • โ€”โœ… Residual connections for deeper learning
  • โ€”โœ… Channel attention mechanisms
  • โ€”โœ… Dual pooling (average + max)
  • โ€”โœ… Batch normalization throughout
  • โ€”โœ… Dropout (0.4) for regularization

Baseline Model (V1) - 39% Accuracy

Features (143 dimensions):

  • โ€”Mel-spectrograms: 128
  • โ€”MFCCs: 13
  • โ€”ZCR: 1
  • โ€”Spectral Centroid: 1

Model Architecture:

  • โ€”3 Conv blocks (64 โ†’ 128 โ†’ 256)
  • โ€”Global average pooling
  • โ€”FC layers: 256 โ†’ 128 โ†’ 8
  • โ€”Total Parameters: 536,584

๐Ÿ“ Project Structure

speech-emotion-recognition/
โ”œโ”€โ”€ data/
โ”‚   โ”œโ”€โ”€ download_dataset.py       # RAVDESS dataset downloader
โ”‚   โ”œโ”€โ”€ prepare_data.py            # Enhanced feature extraction (196 features)
โ”‚   โ”œโ”€โ”€ dataset.py                 # PyTorch Dataset with train/val/test splits
โ”‚   โ””โ”€โ”€ augmentation.py            # Data augmentation (SpecAugment, noise, etc.)
โ”‚
โ”œโ”€โ”€ models/
โ”‚   โ”œโ”€โ”€ emotion_cnn.py             # Baseline CNN (536K params)
โ”‚   โ”œโ”€โ”€ emotion_cnn_v2.py          # Enhanced CNN (11.8M params) โญ
โ”‚   โ”œโ”€โ”€ train.py                   # Baseline training script
โ”‚   โ”œโ”€โ”€ train_v2.py                # Enhanced training script โญ
โ”‚   โ”œโ”€โ”€ evaluate.py                # Baseline evaluation
โ”‚   โ””โ”€โ”€ evaluate_v2.py             # Enhanced evaluation โญ
โ”‚
โ”œโ”€โ”€ deployment/
โ”‚   โ”œโ”€โ”€ app.py                     # Streamlit demo application
โ”‚   โ””โ”€โ”€ requirements.txt           # Deployment dependencies
โ”‚
โ”œโ”€โ”€ notebooks/
โ”‚   โ””โ”€โ”€ emotion_eda.ipynb          # Exploratory analysis + model comparison
โ”‚
โ”œโ”€โ”€ results/
โ”‚   โ”œโ”€โ”€ best_model.pth             # Baseline model weights
โ”‚   โ”œโ”€โ”€ best_model_v2.pth          # Enhanced model weights โญ
โ”‚   โ”œโ”€โ”€ confusion_matrix_v2.png    # Confusion matrix visualization
โ”‚   โ”œโ”€โ”€ per_class_accuracy_v2.png  # Per-class performance chart
โ”‚   โ””โ”€โ”€ model_comparison.png       # Baseline vs Enhanced comparison
โ”‚
โ”œโ”€โ”€ runs/                          # TensorBoard logs
โ”œโ”€โ”€ README.md                      # This file
โ”œโ”€โ”€ requirements.txt               # Python dependencies
โ””โ”€โ”€ LICENSE                        # MIT License

๐Ÿ”ง Technical Details

Dataset: RAVDESS

Ryerson Audio-Visual Database of Emotional Speech and Song

  • โ€”1,440 speech files
  • โ€”8 emotion classes (neutral, calm, happy, sad, angry, fearful, disgust, surprised)
  • โ€”24 professional actors (12 male, 12 female)
  • โ€”Controlled recording environment
  • โ€”Download: https://zenodo.org/record/1188976

Training Configuration (Enhanced Model)

python
config = {
    'batch_size': 24,
    'learning_rate': 0.001,
    'epochs': 150,
    'optimizer': 'AdamW',
    'weight_decay': 1e-4,
    'loss': 'CrossEntropyLoss + Label Smoothing (0.1)',
    'lr_scheduler': 'ReduceLROnPlateau (patience=8, factor=0.5)',
    'early_stopping': 'patience=20',
    'mixed_precision': 'FP16',
    'gradient_clipping': 'max_norm=1.0',
    'data_augmentation': True
}

Data Augmentation

  • โ€”SpecAugment: Time and frequency masking
  • โ€”Gaussian Noise: Random noise injection
  • โ€”Time Shifting: Temporal variations
  • โ€”Augmentation Probability: 60%

Hardware Requirements

  • โ€”Recommended: NVIDIA GPU with 8GB+ VRAM
  • โ€”Tested on: RTX 5060 Ti
  • โ€”Training Time: ~2.5 hours (150 epochs)
  • โ€”Inference: <1 second per file

๐Ÿ“Š Monitoring & Visualization

TensorBoard

bash
tensorboard --logdir=runs/

View real-time training metrics:

  • โ€”Training/validation loss
  • โ€”Training/validation accuracy
  • โ€”Learning rate schedule
  • โ€”Per-class accuracy

Generated Visualizations

  • โ€”Confusion Matrix: Shows emotion confusion patterns
  • โ€”Per-Class Accuracy: Bar chart of individual emotion performance
  • โ€”Model Comparison: Baseline vs Enhanced side-by-side

๐ŸŽ“ Key Learnings

What Worked

  1. 1.Enhanced Features: Delta MFCCs and Chromagram were crucial for distinguishing similar emotions
  2. 2.Residual Connections: Enabled much deeper learning without degradation
  3. 3.Channel Attention: Helped model focus on important frequency bands
  4. 4.Data Augmentation: SpecAugment significantly improved generalization
  5. 5.Label Smoothing: Prevented overconfidence and improved calibration

Challenges Overcome

  • โ€”Happy vs Sad Confusion: Solved with chromagram (pitch) and delta MFCCs (dynamics)
  • โ€”Overfitting: Addressed with dropout, weight decay, and augmentation
  • โ€”Training Stability: Fixed with gradient clipping and batch normalization

Remaining Challenges

  • โ€”Fearful Emotion: Still only 41.38% accuracy (confused with other negative emotions)
  • โ€”Test-Val Gap: 75% validation vs 66.2% test suggests some overfitting

๐Ÿš€ Deployment

Hugging Face Model Hub

The trained model is available on Hugging Face:

python
from huggingface_hub import hf_hub_download

model_path = hf_hub_download(
    repo_id="yourusername/speech-emotion-recognition",
    filename="best_model_v2.pth"
)

Streamlit Cloud

Live demo: [Coming Soon]

Local Demo

bash
streamlit run deployment/app.py

Features:

  • โ€”Audio file upload
  • โ€”Real-time emotion prediction
  • โ€”Confidence scores visualization
  • โ€”Top-3 predictions

๐Ÿ“ˆ Performance Metrics

Classification Report (Enhanced Model)

              precision    recall  f1-score   support

     neutral      0.667     0.714     0.690        14
        calm      0.686     0.857     0.762        28
       happy      0.531     0.586     0.557        29
         sad      0.500     0.517     0.508        29
       angry      0.769     0.690     0.727        29
     fearful      0.706     0.414     0.522        29
     disgust      0.688     0.759     0.721        29
   surprised      0.793     0.793     0.793        29

    accuracy                          0.662       216
   macro avg      0.667     0.666     0.660       216
weighted avg      0.667     0.662     0.658       216

๐Ÿ› ๏ธ Development

Running Tests

bash
# Test model architecture
python models/emotion_cnn_v2.py

# Test dataset loading
python data/dataset.py

# Check environment
python quick_start.py

Training from Scratch

bash
# Complete pipeline
./run_pipeline.sh

# Or step by step:
python data/download_dataset.py
python data/prepare_data.py
python models/train_v2.py
python models/evaluate_v2.py

๐Ÿ“š References

  1. 1.RAVDESS Dataset: Livingstone SR, Russo FA (2018) The Ryerson Audio-Visual Database of Emotional Speech and Song (RAVDESS). PLoS ONE 13(5): e0196391.
  1. 1.SpecAugment: Park et al. (2019) "SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition"
  1. 1.ResNet: He et al. (2016) "Deep Residual Learning for Image Recognition"
  1. 1.Channel Attention: Hu et al. (2018) "Squeeze-and-Excitation Networks"

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. 1.Fork the repository
  2. 2.Create your feature branch (git checkout -b feature/AmazingFeature)
  3. 3.Commit your changes (git commit -m 'Add some AmazingFeature')
  4. 4.Push to the branch (git push origin feature/AmazingFeature)
  5. 5.Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • โ€”RAVDESS dataset creators for the high-quality emotion database
  • โ€”PyTorch team for the excellent deep learning framework
  • โ€”librosa developers for comprehensive audio processing tools

๐Ÿ“ง Contact

For questions or feedback, please open an issue on GitHub.


Built with โค๏ธ using PyTorch, librosa, and Streamlit