简体   繁体   中英

Getting error while unit testing my machine learning model on Audio files

I am getting errors when training my machine learning model which is for checking what a person is feeling while saying somthing. I am working with librosa, soundfile & MLPClassifier from sklearn. This is my code:

;imported required libraries
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

; created a function that basically gathers features from audio files
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(X, sr=sample_rate).T,axis=0)
            result=np.hstack((result, mel))
    return result
; defined emotions
emotions={
  '01':'neutral',
  '02':'calm',
  '03':'happy',
  '04':'sad',
  '05':'angry',
  '06':'fearful',
  '07':'disgust',
  '08':'surprised'
}
observed_emotions=['calm', 'happy', 'fearful', 'disgust']
;to load data
def load_data(test_size=0.2):
    x,y=[],[]
    for file in glob.glob("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)

x_train,x_test,y_train,y_test=load_data(test_size=0.23)

print((x_train.shape[0], x_test.shape[0]))

; used the mlpclassifier
model=MLPClassifier(alpha=0.01, batch_size=256, epsilon=1e-08, hidden_layer_sizes=(300,), learning_rate='adaptive', max_iter=500)

;trained my model
model.fit(x_train,y_train)

; This is the part used for unit testing and I am getting a lot of errors
a,b = [],[]
file_name=os.path.basename("data/what.wav")
emotion=emotions[file_name.split("-")[2]]
if emotion not in observed_emotions:
    continue
feature=extract_feature(file, mfcc=True, chroma=True, mel=True)
a.append(feature)
b.append(emotion)

This is the error that I am getting, which when i try to remove via other methods like using pydub , I get different types of errors. I am a begineer to this and still have to learn a lot. So i hope can find a way to resolve this .

IndexError                                Traceback (most recent call last)
<ipython-input-41-8b30084e3248> in <module>
      1 a,b = [],[]
      2 file_name=os.path.basename("data/what.wav")
----> 3 emotion=emotions[file_name.split("-")[2]]
      4 if emotion not in observed_emotions:
      5     continue

IndexError: list index out of range

Your call to os.path.basename("data/what.wav") returns 'what.wav'

You then split that using "-" as the splitter, which returns ['what.wav'], a list of one element.

But you then try to reference the third element of the list with [2], which throws an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM