【问题标题】:librosa.util.exceptions.ParameterError: Invalid shape for monophonic audio: ndim=2, shape=(172972, 2)librosa.util.exceptions.ParameterError:单声道音频的形状无效:ndim=2,shape=(172972, 2)
【发布时间】:2020-04-27 02:12:52
【问题描述】:

请有人帮我解决这个问题

我正在关注本教程: https://data-flair.training/blogs/python-mini-project-speech-emotion-recognition/

并使用他们从 RAVDESS 数据集中获取的数据集并降低了它们的采样率。我可以轻松地使用这些数据进行训练。但是当我从这里使用原始数据时: https://zenodo.org/record/1188976

只需“Audio_Speech_Actors_01-24.zip”并尝试训练模型它给我以下错误:

Traceback (most recent call last):
  File "C:/Users/raj.pandey/Desktop/speech-emotion-recognition/main.py", line 64, in <module>
    x_train, x_test, y_train, y_test = load_data(test_size=0.20)
  File "C:/Users/raj.pandey/Desktop/speech-emotion-recognition/main.py", line 57, in load_data
    feature = extract_feature(file, mfcc=True, chroma=True, mel=True)
  File "C:/Users/raj.pandey/Desktop/speech-emotion-recognition/main.py", line 32, in extract_feature
    stft = np.abs(librosa.stft(X))
  File "C:\Users\raj.pandey\Desktop\speech-emotion-recognition\lib\site-packages\librosa\core\spectrum.py", line 215, in stft
    util.valid_audio(y)
  File "C:\Users\raj.pandey\Desktop\speech-emotion-recognition\lib\site-packages\librosa\util\utils.py", line 268, in valid_audio
    'ndim={:d}, shape={}'.format(y.ndim, y.shape))
librosa.util.exceptions.ParameterError: Invalid shape for monophonic audio: ndim=2, shape=(172972, 2)

火车在同一数据集上提供的教程,只是它们降低了采样率。为什么它不在原始版本上运行?

它是否必须在代码中对此做任何事情:

X = sound_file.read(dtype="float32")

我也只是出于好奇尝试从 .mp3 文件进行预测,结果出现错误。然后我将那个 .mp3 文件转换为 wav 并尝试但仍然在标题中给出错误。

如何解决此错误并使其在原始数据上进行训练?如果它开始对原始文件进行训练,那么我认为它可以预测 .mp3 到 wav 转换文件。

下面是我正在使用的代码:

import librosa
import soundfile
import os
import glob
import 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 - 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', 'fearful', 'disgust']


# 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(X, sr=sample_rate).T, axis=0)
            result = np.hstack((result, mel))
    return result


# DataFlair - Load the data and extract features for each sound file
def load_data(test_size=0.2):
    x, y = [], []
    for file in glob.glob("C:\\Users\\raj.pandey\\Desktop\\speech-emotion-recognition\\Dataset\\Actor_*\\*.wav"):
        # for file in glob.glob("C:\\Users\\raj.pandey\\Desktop\\speech-emotion-recognition\\Dataset\\newactor\\*.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.20)

# DataFlair - Get the shape of the training and testing datasets
# print((x_train.shape[0], x_test.shape[0]))

# DataFlair - Get the number of features extracted
# print(f'Features extracted: {x_train.shape[1]}')

# 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)

# print(model.fit(x_train, y_train))

# DataFlair - Predict for the test set
y_pred = model.predict(x_test)
# print("This is y_pred: ", y_pred)


# 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))

# Predicting random files
tar_file = "C:\\Users\\raj.pandey\\Desktop\\speech-emotion-recognition\\Dataset\\newactor\\pls-hold-while-try.wav"
new_feature = extract_feature(tar_file, mfcc=True, chroma=True, mel=True)
data = []
data.append(new_feature)
data = np.array(data)
z_pred = model.predict(data)
print("This is output: ", z_pred)

教程提供的训练数据集是这样的:https://drive.google.com/file/d/1wWsrN2Ep7x6lWqOXfr4rpKGYrJhWc8z7/view

您可以从这里获得的原始数据集(不适用于程序):https://zenodo.org/record/1188976(Audio_speech_actor one)

在预测随机文件时,如果您将任何带有语音的 .wav 文件放入其中,则会导致错误。如果您尝试文本到语音转换器并获取 .wav 并将其传递到这里,它总是会说“fearfull”。我已尝试将 .mp3 转换为 .wav 以使其正常工作,但仍然是一个错误。

有人检查过我怎样才能让它工作?

【问题讨论】:

标签: python-3.x audio speech-recognition librosa


【解决方案1】:

我刚刚遇到了同样的问题。对于阅读本文但不想删除立体声文件的任何人,可以使用命令行工具 ffmpeg 将它们转换为单声道:

ffmpeg -i stereo_file_name.wav -ac 1 mono_file_name.wav 

Link to ffmpeg Related Stack Overflow Post

【讨论】:

    【解决方案2】:

    从 pydub 导入 AudioSegment

        file_name=os.path.basename(file)
        #converting stereo audio to mono
        sound = AudioSegment.from_wav(file)
        sound = sound.set_channels(1)
        sound.export(file, format="wav")
        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)
    

    【讨论】:

      【解决方案3】:

      因为音频文件有 2 个音频通道,所以它必须只有一个音频通道。

      【讨论】:

        【解决方案4】:

        我正在处理相同的数据集并且也遇到了相同的错误。我所做的是使用在线转换器https://convertio.co/ 按照本网站的指示https://videoconvert.minitool.com/video-converter/stereo-to-mono.html(第 1 点,convertio)将音频转换为单声道

        array(['fearful'], dtype='<U7')
        

        上面这行也是我的输出,它预测它是fearful,可能是因为准确度(我的是73.96%,但它会变化)

        【讨论】:

          【解决方案5】:

          火车在同一数据集上提供的教程,只是它们降低了采样率。为什么它不在原始版本上运行?

          即使人们已经给出了这个问题的答案,该教程的作者或作者也没有具体说明发布在他们的 Google Drive 上的数据集包含所有带有单声道的音轨,而在原来的那个中有一些立体声声道中的音轨。

          正如 Arryan Sinha 所示,只需使用包 pydub 即可完成工作。

          除此之外,我建议不要过多关注该教程,因为分类器的结果在大多数情况下只有大约 50% 的准确率,这不是很好。为了有效地验证分类器是否良好,请尝试打印混淆矩阵。这肯定有助于查看分类器是否好。

          【讨论】:

            【解决方案6】:

            一些音频文件是立体声的,(并且代码需要单声道)那些会导致中断。从数据集中删除这些文件可消除此错误。在 load_data() 中,添加一行 print(file)。它会告诉你哪些文件破坏了代码,然后删除它们。

            def load_data(test_size=0.2):
                x,y=[],[]
                for file in glob.glob("\Actor_*\\*.wav"):
                    file_name=os.path.basename(file)
                    print(file) 
                    emotion=emotions[file_name.split("-")[2]] 
                    ...
            

            我找到了 4 个导致此问题的文件:

            • Actor_01/03-01-02-01-01-02-01.wav
            • Actor_05/03-01-02-01-02-02-05.wav
            • Actor_20/03-01-03-01-02-01-20.wav
            • Actor_20/03-01-06-01-01-02-20.wav

            【讨论】:

              猜你喜欢
              • 2019-01-16
              • 2020-10-25
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-07-13
              • 2021-07-18
              相关资源
              最近更新 更多