Question: import os import numpy as np import librosa from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.metrics import confusion _ matrix, classification _ report import pickle import
import os import numpy as np import librosa from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.metrics import confusionmatrix, classificationreport import pickle import soundfile as sf from sklearn.modelselection import traintestsplit, GridSearchCV, StratifiedKFold import sounddevice as sd from sklearn.preprocessing import StandardScaler from sklearn.featureselection import SelectKBest, fclassif # Paths to audio files audiofiles "Ifrah": C:software testvoicesIfrawav", "Sharonne": C:software testvoicesSharonnewav", "Talha": C:software testvoicesTalhaconverted.wav" # Define a function to load an audio file and extract features def extractfeaturesaudiopath: y sr librosa.loadaudiopath return extractfeaturesfromarrayy sr # Extract features from an audio array def extractfeaturesfromarrayy sr: mfccs npmeanlibrosafeature.mfccyy srsr nmfccT axis chroma npmeanlibrosafeature.chromastftyy srsrT axis spectralcontrast npmeanlibrosafeature.spectralcontrastyy srsrT axis zerocrossings npmeanlibrosafeature.zerocrossingrateyyT axis spectralrolloff npmeanlibrosafeature.spectralrolloffyy srsrT axis rms npmeanlibrosafeature.rmsyyT axis melspectrogram npmeanlibrosafeature.melspectrogramyy srsrT axis spectralbandwidth npmeanlibrosafeature.spectralbandwidthyy srsrT axis mfccdelta npmeanlibrosafeature.deltalibrosafeature.mfccyy srsr nmfccT axis features nphstackmfccs chroma, spectralcontrast, zerocrossings, spectralrolloff, rms melspectrogram, spectralbandwidth, mfccdelta return features # Augment audio data def augmentaudioy sr: noise nprandom.normal leny # Reduced noise level ynoisy y noise ypitched librosa.effects.pitchshifty srsr nsteps # Smaller pitch shift yspeed librosa.effects.timestretchyastypefloat rate # Less aggressive time stretch return ynoisy, ypitched, yspeed # Function to record and save audio for a speaker def recordandsave: duration # seconds printPlease record your audio for speaker identification..." recording sdrecintduration samplerate channels dtype'float sdwait filename "speakerrecorded.wav" sfwritefilename recording, printfRecording saved as filename return filename # Extract features from uploaded files data labels for label, audiopath in audiofiles.items: y sr librosa.loadaudiopath # Original features features extractfeaturesaudiopath data.appendfeatures labels.appendlabel # Augmented features augmentedaudios augmentaudioy sr for augy in augmentedaudios: augfeatures extractfeaturesfromarrayaugy sr data.appendaugfeatures labels.appendlabel # Convert data and labels to NumPy arrays data nparraydata labels nparraylabels # Split data into training and testing sets Xtrain, Xtest, ytrain, ytest traintestsplitdata labels, testsize randomstate # Normalize features scaler StandardScaler Xtrain scaler.fittransformXtrain Xtest scaler.transformXtest # Feature selection to reduce dimensionality and remove noise selector SelectKBestscorefuncfclassif, k # Increased k to retain more features Xtrain selector.fittransformXtrain, ytrain Xtest selector.transformXtest # Train a Random Forest Classifier with GridSearch for hyperparameter tuning paramgrid nestimators': 'maxdepth': None 'minsamplessplit': # Increased to prevent overfitting 'minsamplesleaf': # Increased to prevent overfitting kfold StratifiedKFoldnsplits grid GridSearchCVRandomForestClassifierrandomstate paramgrid, cvkfold, refitTrue, verbose grid.fitXtrain, ytrain # Use the best model from grid search rfclassifier grid.bestestimator # Train a Gradient Boosting Classifier for comparison gbclassifier GradientBoostingClassifierrandomstate gbclassifier.fitXtrain, ytrain # Predict on the test set with Random Forest ypredrf rfclassifier.predictXtest # Predict on the test set with Gradient Boosting ypredgb gbclassifier.predictXtest # Evaluate the Random Forest model confmatrixrf confusionmatrixytest, ypredrf classreportrf classificationreportytest, ypredrf printRandom Forest Confusion Matrix:" printconfmatrixrf print
Random Forest Classification Report:" printclassreportrf # Evaluate the Gradient Boosting model confmatrixgb confusionmatrixytest, ypredgb classreportgb classificationreportytest, ypredgb printGradient Boosting Confusion Matrix:" printconfmatrixgb print
Gradient Boosting Classification Report:" printclassreportgb # Save the trained models and scaler with openrfclassifiermodel.pklwb as modelfile: pickle.dumprfclassifier, modelfile with opengbclassifiermodel.pklwb as modelfile: pickle.dumpgbclassifier, modelfile with openscalerpklwb as scalerfile: pickle.dumpscaler scalerfile # Save the feature selector with openselectorpklwb as selectorfile: pickle.dumpselector selectorfile # Function to record and predict the speaker def recordandpredict: # Record audio filename recordandsave # Extract features from the recorded audio features extractfeaturesfilenamereshape # Load scaler, selector, and model for prediction with openscalerpklrb as scalerfile: scaler pickle.loadscalerfile features scaler.transformfeatures with openselectorpklrb as selectorfile: selector pickle.loadselectorfile features selector.transformfeatures with openrfclassifiermodel.pklrb as modelfile: model pickle.loadmodelfile prediction model.predictfeatures printfThe speaker is predicted to be: prediction
# Record and predict speaker once def main: while True: recordandpredict cont inputDo you want to identify another speaker? yesno: striplower if cont 'yes': break # Run the main function if namemain: main
Can you correct this code in order to allow the machine to correctly identify the person who records the Audio from the audio that we put in the code to teach the machine our voice the machine must allow the user to record an audio and identify if it is ifrah or sharonne or talha
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
