17 KiB
17 KiB
!pip install librosa soundfile numpy sklearn pyaudio
Looking in indexes: https://pypi.org/simple, https://pypi.ngc.nvidia.com Requirement already satisfied: librosa in c:\users\user\anaconda3\lib\site-packages (0.10.0.post2) Requirement already satisfied: soundfile in c:\users\user\anaconda3\lib\site-packages (0.12.1) Requirement already satisfied: numpy in c:\users\user\anaconda3\lib\site-packages (1.20.3) Requirement already satisfied: sklearn in c:\users\user\anaconda3\lib\site-packages (0.0) Requirement already satisfied: pyaudio in c:\users\user\anaconda3\lib\site-packages (0.2.13) Requirement already satisfied: audioread>=2.1.9 in c:\users\user\anaconda3\lib\site-packages (from librosa) (3.0.0) Requirement already satisfied: scipy>=1.2.0 in c:\users\user\anaconda3\lib\site-packages (from librosa) (1.7.1) Requirement already satisfied: scikit-learn>=0.20.0 in c:\users\user\anaconda3\lib\site-packages (from librosa) (1.2.0) Requirement already satisfied: joblib>=0.14 in c:\users\user\anaconda3\lib\site-packages (from librosa) (1.2.0) Requirement already satisfied: decorator>=4.3.0 in c:\users\user\appdata\roaming\python\python39\site-packages (from librosa) (5.1.1) Requirement already satisfied: numba>=0.51.0 in c:\users\user\anaconda3\lib\site-packages (from librosa) (0.54.1) Requirement already satisfied: pooch<1.7,>=1.0 in c:\users\user\anaconda3\lib\site-packages (from librosa) (1.6.0) Requirement already satisfied: soxr>=0.3.2 in c:\users\user\anaconda3\lib\site-packages (from librosa) (0.3.5) Requirement already satisfied: typing-extensions>=4.1.1 in c:\users\user\anaconda3\lib\site-packages (from librosa) (4.4.0) Requirement already satisfied: lazy-loader>=0.1 in c:\users\user\anaconda3\lib\site-packages (from librosa) (0.2) Requirement already satisfied: msgpack>=1.0 in c:\users\user\anaconda3\lib\site-packages (from librosa) (1.0.2) Requirement already satisfied: cffi>=1.0 in c:\users\user\anaconda3\lib\site-packages (from soundfile) (1.14.6) Requirement already satisfied: pycparser in c:\users\user\anaconda3\lib\site-packages (from cffi>=1.0->soundfile) (2.20) Requirement already satisfied: llvmlite<0.38,>=0.37.0rc1 in c:\users\user\anaconda3\lib\site-packages (from numba>=0.51.0->librosa) (0.37.0) Requirement already satisfied: setuptools in c:\users\user\anaconda3\lib\site-packages (from numba>=0.51.0->librosa) (65.6.3) Requirement already satisfied: appdirs>=1.3.0 in c:\users\user\anaconda3\lib\site-packages (from pooch<1.7,>=1.0->librosa) (1.4.4) Requirement already satisfied: packaging>=20.0 in c:\users\user\anaconda3\lib\site-packages (from pooch<1.7,>=1.0->librosa) (21.0) Requirement already satisfied: requests>=2.19.0 in c:\users\user\anaconda3\lib\site-packages (from pooch<1.7,>=1.0->librosa) (2.30.0) Requirement already satisfied: threadpoolctl>=2.0.0 in c:\users\user\anaconda3\lib\site-packages (from scikit-learn>=0.20.0->librosa) (2.2.0) Requirement already satisfied: pyparsing>=2.0.2 in c:\users\user\anaconda3\lib\site-packages (from packaging>=20.0->pooch<1.7,>=1.0->librosa) (2.4.7) Requirement already satisfied: charset-normalizer<4,>=2 in c:\users\user\anaconda3\lib\site-packages (from requests>=2.19.0->pooch<1.7,>=1.0->librosa) (2.0.4) Requirement already satisfied: idna<4,>=2.5 in c:\users\user\anaconda3\lib\site-packages (from requests>=2.19.0->pooch<1.7,>=1.0->librosa) (3.2) Requirement already satisfied: urllib3<3,>=1.21.1 in c:\users\user\anaconda3\lib\site-packages (from requests>=2.19.0->pooch<1.7,>=1.0->librosa) (1.26.14) Requirement already satisfied: certifi>=2017.4.17 in c:\users\user\anaconda3\lib\site-packages (from requests>=2.19.0->pooch<1.7,>=1.0->librosa) (2023.5.7)
WARNING: Ignoring invalid distribution -andas (c:\users\user\anaconda3\lib\site-packages) WARNING: Ignoring invalid distribution -andas (c:\users\user\anaconda3\lib\site-packages)
import librosa
import soundfile
import os, glob, pickle
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
#DataFlair - Extract features (mfcc, chroma, mel) from a sound file
def extract_feature(file_name, mfcc, chroma, mel):
with soundfile.SoundFile(file_name) as sound_file:
X = sound_file.read(dtype="float32")
sample_rate=sound_file.samplerate
if chroma:
stft=np.abs(librosa.stft(X))
result=np.array([])
if mfcc:
mfccs=np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)
result=np.hstack((result, mfccs))
if chroma:
chroma=np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0)
result=np.hstack((result, chroma))
if mel:
mel=np.mean(librosa.feature.melspectrogram(y=X, sr=sample_rate).T,axis=0)
result=np.hstack((result, mel))
return result
#DataFlair - Emotions in the RAVDESS dataset
emotions={
'01':'neutral',
'02':'calm',
'03':'happy',
'04':'sad',
'05':'angry',
'06':'fearful',
'07':'disgust',
'08':'surprised'
}
#DataFlair - Emotions to observe
observed_emotions=['calm', 'happy', 'disgust']
#DataFlair - Load the data and extract features for each sound file
from pathlib import Path
path = str(Path.cwd())
def load_data(test_size=0.2):
x,y=[],[]
for file in glob.glob(f"{path}\data\Actor_*\*.wav"):
file_name=os.path.basename(file)
emotion=emotions[file_name.split("-")[2]]
if emotion not in observed_emotions:
continue
feature=extract_feature(file, mfcc=True, chroma=True, mel=True)
x.append(feature)
y.append(emotion)
return train_test_split(np.array(x), y, test_size=test_size, random_state=9)
#DataFlair - Split the dataset
x_train,x_test,y_train,y_test=load_data(test_size=0.25)
#DataFlair - Get the shape of the training and testing datasets
print((x_train.shape[0], x_test.shape[0]))
(432, 144)
#DataFlair - Get the number of features extracted
print(f'Features extracted: {x_train.shape[1]}')
Features extracted: 180
#DataFlair - Initialize the Multi Layer Perceptron Classifier
model=MLPClassifier(alpha=0.01, batch_size=256, epsilon=1e-08, hidden_layer_sizes=(300,), learning_rate='adaptive', max_iter=500)
#DataFlair - Train the model
model.fit(x_train,y_train)
c:\Users\User\anaconda3\lib\site-packages\sklearn\neural_network\_multilayer_perceptron.py:679: ConvergenceWarning: Stochastic Optimizer: Maximum iterations (500) reached and the optimization hasn't converged yet. warnings.warn(
MLPClassifier(alpha=0.01, batch_size=256, hidden_layer_sizes=(300,), learning_rate='adaptive', max_iter=500)In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
MLPClassifier(alpha=0.01, batch_size=256, hidden_layer_sizes=(300,), learning_rate='adaptive', max_iter=500)
#DataFlair - Predict for the test set
y_pred=model.predict(x_test)
#DataFlair - Calculate the accuracy of our model
accuracy=accuracy_score(y_true=y_test, y_pred=y_pred)
#DataFlair - Print the accuracy
print("Accuracy: {:.2f}%".format(accuracy*100))
Accuracy: 84.03%