You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

语音情感分类器TypeError求助:melspectrogram参数传递错误

问题解决:RAVDESS语音情感分类器TypeError错误

错误信息

TypeError: melspectrogram() takes 0 positional arguments but 1 positional argument (and 1 keyword-only argument) were given

错误原因

这是librosa版本兼容性问题:新版本的librosa.feature.melspectrogram要求音频输入必须通过关键字参数y=传递,不再支持位置参数传入音频信号。你的代码中直接用位置参数传入了音频数组X,触发了这个错误。

修复方法

修改extract_feature函数中调用melspectrogram的代码,将位置参数X改为关键字参数y=X即可。

修正后的完整代码

# 从音频文件提取特征(mfcc, chroma, mel)
def extract_feature(file_name, **kwargs):
    mfcc = kwargs.get("mfcc")
    chroma = kwargs.get("chroma")
    mel = kwargs.get("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:
            # 关键修改:将位置参数X改为关键字参数y=X
            mel = np.mean(librosa.feature.melspectrogram(y=X, sr=sample_rate).T, axis=0)
            result = np.hstack((result, mel))
    return result

# RAVDESS数据集情感映射
emotions={
  '01':'neutral',
  '02':'calm',
  '03':'happiness',
  '04':'sadness',
  '05':'angry',
  '06':'fearful',
  '07':'disgust',
  '08':'surprised'
}

# 关注的情感类别
observed_emotions=['happiness', 'neutral', 'sadness']

# 加载数据集并提取特征
def load_data(test_size=0.2): 
    a,b=[],[]
    for file in glob.glob("/content/drive/MyDrive/Depression detection/speech-emotion-recognition-ravdess-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)
        a.append(feature)
        b.append(emotion)
    return train_test_split(np.array(a), b, test_size=test_size, random_state=9)

# 划分数据集
atrain, atest, btrain, btest = load_data(test_size=0.25)

补充说明

你代码中调用mfcc时已经正确使用了y=X的形式,只需要对melspectrogram做同样的修改即可。这个问题常见于librosa 0.9.0及以上版本,旧版本允许位置参数,但新版本强制要求关键字参数明确指定输入信号。

内容的提问来源于stack exchange,提问作者Sahil khurana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:12:58