Views
No views yet
emotions = ['angry' 'disgust' 'fear' 'happy' 'neutral' 'sad' 'surprise']pip install transformers librosa torch1from transformers import *
2import librosa
3import torch
4
5feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("r-f/wav2vec-english-speech-emotion-recognition")
6model = Wav2Vec2ForCTC.from_pretrained("r-f/wav2vec-english-speech-emotion-recognition")
7
8def predict_emotion(audio_path):
9 audio, rate = librosa.load(audio_path, sr=16000)
10 inputs = feature_extractor(audio, sampling_rate=rate, return_tensors="pt", padding=True)
11
12 with torch.no_grad():
13 outputs = model(inputs.input_values)
14 predictions = torch.nn.functional.softmax(outputs.logits.mean(dim=1), dim=-1) # Average over sequence length
15 predicted_label = torch.argmax(predictions, dim=-1)
16 emotion = model.config.id2label[predicted_label.item()]
17 return emotion
18
19emotion = predict_emotion("example_audio.wav")
20print(f"Predicted emotion: {emotion}")
21>> Predicted emotion: angry| Step | Training Loss | Validation Loss | Accuracy |
|---|---|---|---|
| 500 | 1.8124 | 1.365212 | 0.486258 |
| 1000 | 0.8872 | 0.773145 | 0.79704 |
| 1500 | 0.7035 | 0.574954 | 0.852008 |
| 2000 | 0.6879 | 1.286738 | 0.775899 |
| 2500 | 0.6498 | 0.697455 | 0.832981 |
| 3000 | 0.5696 | 0.33724 | 0.892178 |
| 3500 | 0.4218 | 0.307072 | 0.911205 |
| 4000 | 0.3088 | 0.374443 | 0.930233 |
| 4500 | 0.2688 | 0.260444 | 0.936575 |
| 5000 | 0.2973 | 0.302985 | 0.92389 |
| 5500 | 0.1765 | 0.165439 | 0.961945 |
| 6000 | 0.1475 | 0.170199 | 0.961945 |
| 6500 | 0.1274 | 0.15531 | 0.966173 |
| 7000 | 0.0699 | 0.103882 | 0.976744 |
| 7500 | 0.083 | 0.104075 | 0.97463 |