import os
import zipfile
import numpy as np
import pandas as pd
import librosa
import librosa.display
import soundfile as sf
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.utils import class_weight
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
Set matplotlib to display inline
%matplotlib inline
Set random seed for reproducibility
import tensorflow as tf
import random
seed = 42
random.seed(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
-----------------------------
2. Data Download
-----------------------------
Ensure you have your Kaggle API token in /content
You can upload the kaggle.json file by clicking the folder icon on the left sidebar in Colab
DATASET_PATH = '/content/TESS Toronto emotional speech set data'
Assistant
Initialize lists to hold file paths and labels
paths = []
labels = []
Traverse the dataset directory to collect file paths and labels
for dirname, , filenames in os.walk(DATASET_PATH):
for filename in filenames:
paths.append(os.path.join(dirname, filename))
label = filename.split('')[-1]
label = label.split('.')[0]
labels.append(label.lower())
if len(paths) >= 2800:
break # Limit to 2800 samples for manageability
print('Dataset is Loaded')
Display dataset statistics
print(f'Number of samples: {len(paths)}')
print('Sample paths:', paths[:5])
print('Sample labels:', labels[:5])
Display sample audio waves and spectrograms for each emotion
emotions = df['label'].unique()
for emotion in emotions:
path = df['speech'][df['label'] == emotion].iloc[0]
data, sampling_rate = librosa.load(path)
waveplot(data, sampling_rate, emotion)
spectrogram_plot(data, sampling_rate, emotion)
# Uncomment the line below to listen to the audio (not recommended for large datasets)
# display(Audio(path))
-----------------------------
5. Data Augmentation
-----------------------------
Define a function to apply various augmentations to an audio signal
def augment_audio(y, sr):
augmentations = []
code
# 1. Additive Gaussian Noise
noise = np.random.randn(len(y))
augmented_y = y + 0.005 * noise
augmentations.append(augmented_y)
# 2. Time Shifting
shift = np.random.randint(int(sr * 0.2)) # Shift by up to 20% of the length
augmented_y = np.roll(y, shift)
augmentations.append(augmented_y)
# 3. Pitch Shifting
augmented_y = librosa.effects.pitch_shift(y, sr, n_steps=2) # Shift by +2 steps
augmentations.append(augmented_y)
# 4. Time Stretching
augmented_y = librosa.effects.time_stretch(y, rate=1.1) # Stretch by a factor of 1.1
# To ensure the stretched signal has the same length
if len(augmented_y) > len(y):
augmented_y = augmented_y[:len(y)]
else:
augmented_y = np.pad(augmented_y, (0, len(y) - len(augmented_y)), 'constant')
augmentations.append(augmented_y)
return augmentations
Apply augmentation and expand the dataset
augmented_paths = []
augmented_labels = []
print("Applying data augmentation...")
for index, row in df.iterrows():
try:
y, sr = librosa.load(row['speech'], duration=3, offset=0.5)
augmentations = augment_audio(y, sr)
for augmented_y in augmentations:
augmented_paths.append(augmented_y)
augmented_labels.append(row['label'])
except Exception as e:
print(f"Error processing {row['speech']}: {e}")
print(f"Original dataset size: {df.shape}")
print(f"Augmented data size: {len(augmented_paths)}")
print("Extracting features from all samples...")
X_features = []
for i, speech in enumerate(combined_speeches):
if isinstance(speech, str):
# Original data: load from file
y, sr = librosa.load(speech, duration=3, offset=0.5)
else:
# Augmented data: already loaded as numpy array
y = speech
sr = 22050 # Default sampling rate
features = extract_features(y, sr)
X_features.append(features)
if (i+1) % 500 == 0:
print(f"Processed {i+1}/{len(combined_speeches)} samples")
print("Feature extraction completed.")
Determine the maximum sequence length
max_len = max([x.shape[0] for x in X_features])
print(f'Max sequence length: {max_len}')
Pad sequences to have the same length
from keras.preprocessing.sequence import pad_sequences
print("Splitting data into training and testing sets...")
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=seed, stratify=y)
print(f'Training set size: {X_train.shape}')
print(f'Testing set size: {X_test.shape}')
-----------------------------
10. Model Definition
-----------------------------
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, Bidirectional, Conv1D, MaxPooling1D, BatchNormalization, GlobalMaxPooling1D
print("Loading the best model...")
from keras.models import load_model
Change the file name to 'best_model.keras'
best_model = load_model('best_model.keras')
-----------------------------
15. Evaluate the Model
-----------------------------
Evaluate on the test set
print("Evaluating the model on the test set...")
test_loss, test_acc = best_model.evaluate(X_test, y_test, verbose=0)
print(f'Test Accuracy: {test_acc * 100:.2f}%')
print(f'Test Loss: {test_loss:.4f}')
-----------------------------
16. Save the Model
-----------------------------
Save the model for future use
print("Saving the model...")
best_model.save('/content/enhanced_model_rnn.h5')
-----------------------------
17. Prediction Function
-----------------------------
Define a function to preprocess and extract features from a new audio file
def preprocess_audio(file_path):
try:
y, sr = librosa.load(file_path, duration=3, offset=0.5)
features = extract_features(y, sr)
# Pad the sequence
features_padded = pad_sequences([features], maxlen=max_len, dtype='float32', padding='post', truncating='post')
return features_padded
except Exception as e:
print(f"Error processing {file_path}: {e}")
return None
Define a function to predict emotion from a new audio file
def predict_emotion(file_path, model):
features = preprocess_audio(file_path)
if features is not None:
prediction = model.predict(features)
predicted_label_index = np.argmax(prediction, axis=1)[0]
predicted_emotion = le.inverse_transform([predicted_label_index])[0]
return predicted_emotion
else:
return "Error in processing audio."
-----------------------------
18. Test Prediction
-----------------------------
Example prediction with a new audio file
Ensure you have the MP3 file uploaded to Colab or accessible via a file path
new_file_path = '/content/zzz01j79-fm6wj-5mw42-3bbzz-x45618.mp3' # Replace with your MP3 file path
If the file is not already present, upload it
from google.colab import files
import shutil
if not os.path.exists(new_file_path):
print("Please upload the new audio file.")
uploaded = files.upload()
for filename in uploaded.keys():
shutil.move(filename, new_file_path)
print(f"Uploaded and moved {filename} to {new_file_path}")
Predict the emotion
predicted_emotion = predict_emotion(new_file_path, best_model)
print(f'The predicted emotion for the new file is: {predicted_emotion}')
print(f'Test Accuracy: {test_acc * 100:.2f}%')
in this code print graph of the result like f1 score presicio accuracy all graphs
To enhance your model evaluation with additional metrics such as Precision, Recall, F1-Score, and visualize these metrics using various plots, you can integrate the following steps into your existing code. These steps will help you gain deeper insights into your model's performance beyond just accuracy and loss.
Here's a comprehensive guide to implementing these metrics and their corresponding visualizations:
1. Import Necessary Libraries
First, ensure you have imported all the necessary libraries required for computing and plotting the additional metrics.
python
from sklearn.metrics import classification_report, confusion_matrix, precision_recall_fscore_support
import itertools
2. Generate Predictions on the Test Set
After evaluating the model on the test set, generate predictions to compute detailed metrics.
python
# Generate predictions on the test set
print("Generating predictions on the test set...")
y_pred = best_model.predict(X_test)
y_pred_classes = np.argmax(y_pred, axis=1)
y_true_classes = np.argmax(y_test, axis=1)
3. Classification Report
The classification report provides a detailed breakdown of Precision, Recall, and F1-Score for each class.
import numpy as np
# Set width of bar
bar_width = 0.25
# Set position of bar on X axis
r = np.arange(len(metrics_df['Class']))
# Make the plot
plt.figure(figsize=(12, 6))
plt.bar(r, metrics_df['Precision'], color='b', width=bar_width, edgecolor='grey', label='Precision')
plt.bar(r + bar_width, metrics_df['Recall'], color='g', width=bar_width, edgecolor='grey', label='Recall')
plt.bar(r + 2*bar_width, metrics_df['F1-Score'], color='r', width=bar_width, edgecolor='grey', label='F1-Score')
# Add labels and title
plt.xlabel('Classes', fontweight='bold', fontsize=14)
plt.ylabel('Scores', fontweight='bold', fontsize=14)
plt.xticks(r + bar_width, metrics_df['Class'], fontsize=12)
plt.ylim(0, 1)
plt.title('Precision, Recall, and F1-Score per Class', fontsize=16)
plt.legend()
# Show the plot
plt.show()
Here’s how you can integrate all the above steps into your existing code, particularly after evaluating the model on the test set.
python
8. Final Evaluation and Insights
After integrating these metrics, you can analyze the results to understand:
Which classes the model is performing well on (high precision and recall).
Which classes need improvement (low precision and/or recall).
Overall model performance through the averaged metrics like macro/micro F1-score.
Potential issues like confusion between specific classes, as visualized by the confusion matrix.
These insights can guide you in making informed decisions on further improving your model, such as collecting more data for underperforming classes, tweaking the model architecture, or applying more advanced data augmentation techniques.
9. Complete Code Snippet Integration
For clarity, here’s how the additional evaluation steps integrate into your existing code.
python
10. Additional Recommendations
Cross-Validation: To ensure your model's robustness, consider implementing cross-validation techniques.
Hyperparameter Tuning: Experiment with different hyperparameters (e.g., learning rate, number of LSTM units, dropout rates) to optimize model performance.
Feature Engineering: Explore additional features such as Spectral Centroid, Zero-Crossing Rate, or Mel-Spectrograms to enrich the feature set.
Advanced Models: Consider leveraging more sophisticated architectures like Attention Mechanisms or Transformer-based models for potentially better performance.
Handling Class Imbalance: Although you've computed class weights, you might also explore techniques like SMOTE or Balanced Batch Generators for handling class imbalance more effectively.
By integrating these additional evaluation metrics and visualizations, you'll gain a comprehensive understanding of your model's strengths and areas for improvement, enabling you to make more informed decisions for subsequent iterations and enhancements.