Improving the accuracy of your emotion recognition model from 27% to around 80% is achievable by addressing several key areas, including data preprocessing, feature extraction, model architecture, and training strategies. Below are detailed steps and explanations to help you enhance your model's performance:
1. Enhance Feature Extraction
Current Approach:
- MFCC Averaging: You're currently averaging the MFCC features over time, which reduces the temporal information crucial for sequence-based models like RNNs.
Improvements:
- Use Full MFCC Sequences: Instead of averaging, retain the temporal dimension of MFCC features. This allows the LSTM to capture temporal dependencies in the data.
- Add Additional Features: Incorporate other audio features such as Chroma, Spectral Contrast, and Tonal Centroid Features (TCF) to provide more information to the model.
Implementation:
def extract_features(filename):
y, sr = librosa.load(filename, duration=3, offset=0.5)
# Extract MFCC
mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40)
# Extract Chroma
stft = np.abs(librosa.stft(y))
chroma = librosa.feature.chroma_stft(S=stft, sr=sr)
# Extract Spectral Contrast
contrast = librosa.feature.spectral_contrast(S=stft, sr=sr)
# Extract Tonnetz
tonnetz = librosa.feature.tonnetz(y=librosa.effects.harmonic(y), sr=sr)
# Combine all features
features = np.vstack([mfcc, chroma, contrast, tonnetz])
return features.T # Transpose to shape (time_steps, features)
Update Feature Extraction in Data Preparation:
# Extract features without averaging
X_features = df['speech'].apply(lambda x: extract_features(x))
# Determine maximum length for padding
max_len = max(X_features.apply(lambda x: x.shape[0]))
print(f'Max sequence length: {max_len}')
from keras.preprocessing.sequence import pad_sequences
# Pad sequences to have the same length
X_padded = pad_sequences(X_features, maxlen=max_len, dtype='float32', padding='post', truncating='post')
# Reshape for LSTM input
X = X_padded[..., np.newaxis] # Shape: (samples, max_len, features, 1)
2. Handle Class Imbalance
Current Situation:
- The dataset may have uneven class distributions, which can bias the model towards majority classes.
Improvements:
- Oversampling Minority Classes: Use techniques like SMOTE or simple oversampling to balance classes.
- Use Class Weights: Assign higher weights to minority classes during training to mitigate imbalance.
Implementation:
from sklearn.utils import class_weight
# Encode labels as integers
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y_int = le.fit_transform(df['label'])
# Compute class weights
class_weights = class_weight.compute_class_weight('balanced', classes=np.unique(y_int), y=y_int)
class_weights = dict(enumerate(class_weights))
print(f'Class weights: {class_weights}')
# One-hot encode labels
from keras.utils import to_categorical
y = to_categorical(y_int, num_classes=7)
3. Improve Model Architecture
Current Architecture:
- A single-layer LSTM with dropout and dense layers.
Improvements:
- Use Bidirectional LSTM: Captures dependencies in both directions.
- Stack Multiple LSTM Layers: Allows the model to learn more complex patterns.
- Incorporate Convolutional Layers: Extracts local features before LSTM processing.
- Use Batch Normalization: Stabilizes and accelerates training.
Implementation:
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout, Bidirectional, Conv1D, MaxPooling1D, BatchNormalization, GlobalMaxPooling1D
model = Sequential()
# Add Convolutional Layer
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(max_len, X_padded.shape[2])))
model.add(BatchNormalization())
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.3))
# Add Bidirectional LSTM
model.add(Bidirectional(LSTM(128, return_sequences=True)))
model.add(BatchNormalization())
model.add(Dropout(0.3))
# Add another LSTM layer
model.add(Bidirectional(LSTM(64)))
model.add(BatchNormalization())
model.add(Dropout(0.3))
# Fully connected layers
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(7, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
4. Optimize Training Strategy
Improvements:
- Use Early Stopping: Prevents overfitting by stopping training when validation loss stops improving.
- Use Model Checkpointing: Saves the best model during training.
- Increase Epochs: Allows the model more time to learn, especially with early stopping.
- Use Learning Rate Scheduler: Adjusts the learning rate during training for better convergence.
Implementation:
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
# Define callbacks
early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
checkpoint = ModelCheckpoint('best_model.h5', monitor='val_loss', save_best_only=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=5, min_lr=0.0001)
# Train the model with class weights and callbacks
history = model.fit(X, y,
validation_split=0.2,
epochs=100,
batch_size=64,
class_weight=class_weights,
callbacks=[early_stop, checkpoint, reduce_lr])
5. Apply Data Augmentation
Improvements:
- Augment Audio Data: Increase dataset variability by applying transformations such as:
- Noise Injection: Add random noise to the audio signal.
- Time Shifting: Slightly shift the audio forward or backward in time.
- Pitch Shifting: Alter the pitch of the audio.
- Time Stretching: Speed up or slow down the audio.
Implementation:
def augment_audio(y, sr):
augmentations = []
# Add noise
noise = np.random.randn(len(y))
augmented = y + 0.005 * noise
augmentations.append(augmented)
# Time shifting
shift = np.random.randint(-sr//10, sr//10)
augmented = np.roll(y, shift)
augmentations.append(augmented)
# Pitch shifting
augmented = librosa.effects.pitch_shift(y, sr, n_steps=2)
augmentations.append(augmented)
# Time stretching
augmented = librosa.effects.time_stretch(y, rate=1.1)
augmentations.append(augmented)
return augmentations
# Apply augmentation to the dataset
augmented_paths = []
augmented_labels = []
for index, row in df.iterrows():
y, sr = librosa.load(row['speech'], duration=3, offset=0.5)
augmentations = augment_audio(y, sr)
for augmented_y in augmentations:
# Save augmented audio temporarily
temp_path = f"/content/temp_{index}.wav"
librosa.output.write_wav(temp_path, augmented_y, sr)
augmented_paths.append(temp_path)
augmented_labels.append(row['label'])
# Create augmented dataframe
aug_df = pd.DataFrame({'speech': augmented_paths, 'label': augmented_labels})
# Combine original and augmented data
df_combined = pd.concat([df, aug_df], ignore_index=True)
print(f'Combined dataset size: {df_combined.shape}')
# Re-extract features for the combined dataset
X_features = df_combined['speech'].apply(lambda x: extract_features(x))
X_padded = pad_sequences(X_features, maxlen=max_len, dtype='float32', padding='post', truncating='post')
X = X_padded[..., np.newaxis]
# Encode labels
y_int = le.transform(df_combined['label'])
y = to_categorical(y_int, num_classes=7)
# Recompute class weights if necessary
class_weights = class_weight.compute_class_weight('balanced', classes=np.unique(y_int), y=y_int)
class_weights = dict(enumerate(class_weights))
6. Tune Hyperparameters
Improvements:
- Experiment with Different Optimizers: Try Adam, RMSprop, or SGD with momentum.
- Adjust Learning Rates: Use a lower learning rate for finer convergence.
- Change Batch Sizes: Smaller batches can provide a regularizing effect.
Implementation:
- You can adjust the optimizer and learning rate in the
compile step:
from keras.optimizers import Adam
optimizer = Adam(learning_rate=0.0001)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
7. Evaluate with Cross-Validation
Improvements:
- Use K-Fold Cross-Validation: Provides a more robust evaluation of model performance.
Implementation:
from sklearn.model_selection import StratifiedKFold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for train_index, val_index in skf.split(X, y_int):
X_train, X_val = X[train_index], X[val_index]
y_train, y_val = y[train_index], y[val_index]
history = model.fit(X_train, y_train,
validation_data=(X_val, y_val),
epochs=100,
batch_size=64,
class_weight=class_weights,
callbacks=[early_stop, checkpoint, reduce_lr])
8. Post-Training Enhancements
Improvements:
- Ensemble Models: Combine predictions from multiple models to improve accuracy.
- Fine-Tuning: After initial training, fine-tune specific layers for better performance.
9. Final Evaluation and Testing
Implementation:
After training, evaluate your best model on a separate test set to ensure it generalizes well.
# Load the best model
from keras.models import load_model
best_model = load_model('best_model.h5')
# Evaluate on test data
test_loss, test_acc = best_model.evaluate(X_test, y_test, verbose=0)
print(f'Test Accuracy: {test_acc * 100:.2f}%')
10. Prediction on New Audio Files
Ensure that the new audio files undergo the same preprocessing and feature extraction steps as the training data.
def preprocess_audio(file_path):
features = extract_features(file_path)
features = pad_sequences([features], maxlen=max_len, dtype='float32', padding='post', truncating='post')
features = features[..., np.newaxis]
return features
def predict_emotion(file_path, model):
preprocessed_audio = preprocess_audio(file_path)
prediction = model.predict(preprocessed_audio)
predicted_label_index = np.argmax(prediction, axis=1)[0]
return le.inverse_transform([predicted_label_index])[0]
# Example prediction
new_file_path = '/content/zzz01j79-fm6wj-5mw42-3bbzz-x45618.mp3' # Replace with your MP3 file path
predicted_emotion = predict_emotion(new_file_path, best_model)
print(f'The predicted emotion for the new file is: {predicted_emotion}')
Summary of Steps to Increase Accuracy:
-
Enhance Feature Extraction:
- Use full MFCC sequences instead of averaging.
- Incorporate additional audio features (Chroma, Spectral Contrast, Tonnetz).
-
Address Class Imbalance:
- Apply class weighting or oversampling techniques.
-
Improve Model Architecture:
- Utilize Bidirectional LSTM layers.
- Incorporate Convolutional layers for feature extraction.
- Add Batch Normalization and more dropout layers.
-
Optimize Training Strategy:
- Implement Early Stopping and Model Checkpointing.
- Use Learning Rate Schedulers.
-
Apply Data Augmentation:
- Augment audio data with noise, shifts, pitch changes, and stretching.
-
Tune Hyperparameters:
- Experiment with different optimizers, learning rates, and batch sizes.
-
Use Cross-Validation:
- Evaluate model robustness with K-Fold Cross-Validation.
-
Post-Training Enhancements:
- Consider ensemble methods and fine-tuning for better performance.
By systematically applying these enhancements, you should observe a significant improvement in your model's accuracy, potentially reaching or surpassing the 80% target. Remember to iteratively test and validate each change to understand its impact on your model's performance.