import pandas as pd
import numpy as np
import os
import seaborn as sns
import matplotlib.pyplot as plt
import librosa
import librosa.display
from IPython.display import Audio
import warnings
warnings.filterwarnings('ignore')
Load the dataset
paths = []
labels = []
for dirname, , filenames in os.walk('/content/TESS Toronto emotional speech set data'):
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
print('Dataset is Loaded')
Check dataset length and sample paths
print(f'Number of samples: {len(paths)}')
print('Sample paths:', paths[:5])
print('Sample labels:', labels[:5])
def preprocess_audio(file_path):
# Extract MFCC features from the new audio file
mfcc_features = extract_mfcc(file_path)
mfcc_features = np.expand_dims(mfcc_features, axis=0) # Shape should be (1, 40)
mfcc_features = np.expand_dims(mfcc_features, axis=-1) # Shape should be (1, 40, 1)
return mfcc_features
new_file_path = '/content/zzz01j79-fm6wj-5mw42-3bbzz-x45618.mp3' # Replace with your MP3 file path
predicted_emotion = predict_emotion(new_file_path, model)
print(f'The predicted emotion for the new file is: {predicted_emotion}') in this i want to increases the accuracy of my model use hyper parameter and give me code
Improving the accuracy of your Recurrent Neural Network (RNN) model for speech emotion recognition involves tuning various hyperparameters and potentially enhancing your feature extraction process. Below, I provide a comprehensive approach to optimize your model using Keras Tuner, a powerful library for hyperparameter optimization in Keras models. Additionally, I'll suggest some architectural enhancements and best practices to further boost your model's performance.
1. Setting Up Keras Tuner for Hyperparameter Optimization
Keras Tuner automates the process of hyperparameter selection by searching for the best combination of hyperparameters within a defined search space. Here's how you can integrate it into your existing workflow:
a. Install Keras Tuner
First, ensure that you have Keras Tuner installed:
python
!pip install -U keras-tuner
b. Define the Hypermodel
Create a function that defines the model architecture with hyperparameters to tune. You can tune parameters like the number of LSTM units, number of LSTM layers, dropout rates, learning rate, and more.
python
import keras_tuner as kt
from keras.optimizers import Adam, RMSprop
def build_model(hp):
model = Sequential()
# Tune the number of LSTM layers
for i in range(hp.Int('num_layers', 1, 3)):
# Tune the number of units in the LSTM layer
units = hp.Int(f'lstm_units_{i}', min_value=128, max_value=512, step=64)
return_seq = True if i < hp.get('num_layers') - 1 else False
model.add(LSTM(units, return_sequences=return_seq, input_shape=(40,1) if i == 0 else None))
# Tune the dropout rate
dropout = hp.Float(f'dropout_{i}', 0.2, 0.5, step=0.1)
model.add(Dropout(dropout))
# Add Dense layers
for j in range(hp.Int('dense_layers', 1, 3)):
units = hp.Int(f'dense_units_{j}', min_value=64, max_value=256, step=64)
model.add(Dense(units, activation='relu'))
dropout = hp.Float(f'dense_dropout_{j}', 0.2, 0.5, step=0.1)
model.add(Dropout(dropout))
# Output layer
model.add(Dense(7, activation='softmax'))
# Tune the learning rate for the optimizer
learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
optimizer = Adam(learning_rate=learning_rate)
model.compile(
optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
c. Initialize the Tuner
Choose a tuner (e.g., RandomSearch, BayesianOptimization, etc.) based on your requirements. Here, we'll use Hyperband, which is efficient and effective.
tuner.search(X, y,
epochs=50,
validation_split=0.2,
batch_size=hp.Choice('batch_size', values=[32, 64, 128]),
callbacks=[stop_early])
f. Retrieve the Best Model
After the search is complete, retrieve the model with the best performance.
python
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
model = tuner.hypermodel.build(best_hps)
# Optionally, train the model further
history = model.fit(X, y,
epochs=50,
validation_split=0.2,
batch_size=best_hps.get('batch_size'),
callbacks=[stop_early])
g. Save the Best Model
python
model.save('/content/model_rnn_best.h5')
2. Enhancing the Model Architecture
While hyperparameter tuning is crucial, architectural improvements can also significantly impact performance. Here are some suggestions:
a. Use Bidirectional LSTM
Bidirectional LSTMs can capture dependencies in both forward and backward directions, potentially improving context understanding.
python
from keras.layers import Bidirectional
def build_bidirectional_model(hp):
model = Sequential()
for i in range(hp.Int('num_layers', 1, 3)):
units = hp.Int(f'lstm_units_{i}', min_value=128, max_value=512, step=64)
return_seq = True if i < hp.get('num_layers') - 1 else False
model.add(Bidirectional(LSTM(units, return_sequences=return_seq), input_shape=(40,1) if i == 0 else None))
dropout = hp.Float(f'dropout_{i}', 0.2, 0.5, step=0.1)
model.add(Dropout(dropout))
# Add Dense layers
for j in range(hp.Int('dense_layers', 1, 3)):
units = hp.Int(f'dense_units_{j}', min_value=64, max_value=256, step=64)
model.add(Dense(units, activation='relu'))
dropout = hp.Float(f'dense_dropout_{j}', 0.2, 0.5, step=0.1)
model.add(Dropout(dropout))
model.add(Dense(7, activation='softmax'))
learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
optimizer = Adam(learning_rate=learning_rate)
model.compile(
optimizer=optimizer,
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
You can replace the build_model function with build_bidirectional_model in the tuner to explore bidirectional architectures.
b. Incorporate Batch Normalization
Batch Normalization can accelerate training and improve model performance.
python
from keras.layers import BatchNormalization
# Inside the build_model function after each LSTM/ Dense layer
model.add(BatchNormalization())
c. Add More Features
While MFCCs are powerful, combining them with other features like Chroma, Spectral Contrast, or Mel Spectrograms can provide more information to the model.
Combine MFCCs with other features like Chroma, Spectral Contrast, and Tonnetz to provide more information to the model.
c. Ensemble Methods
Combine predictions from multiple models to improve overall accuracy.
d. Advanced Architectures
Explore more advanced architectures such as Convolutional Neural Networks (CNNs) combined with LSTMs (CNN-LSTM), Transformer-based models, or attention mechanisms.
e. Regularization Techniques
Implement techniques like L2 regularization, batch normalization, and dropout to prevent overfitting.
5. Conclusion
By integrating Keras Tuner for hyperparameter optimization and enhancing your model architecture with Bidirectional LSTMs and other improvements, you can significantly boost the accuracy of your speech emotion recognition model. Additionally, incorporating data augmentation and exploring more sophisticated features and architectures can further enhance performance. Remember to monitor for overfitting and ensure that your model generalizes well to unseen data.
Feel free to experiment with the suggested modifications and tailor them to your specific dataset and requirements. Good luck with your NLP project!