采用Python语言,通过训练情绪识别数据集 基于深度学习中的卷积神经网络(CNN)实现语音情绪识别。基于深度学习的语音情绪识别。建立识别7种情绪基于深度学习的语音情绪识别
采用Python语言通过训练情绪识别数据集 基于深度学习中的卷积神经网络CNN实现语音情绪识别。基于深度学习的语音情绪识别。建立识别7种情绪基于深度学习的语音情绪识别代码仅供参考。文章目录基于深度学习的语音情绪识别一、环境配置二、数据集三、技术流程四、代码实现1. 导入所需库2. 加载数据并提取特征3. 构建改进的CNN模型4. 训练模型5. 可视化训练结果6. 评估模型性能7. 使用模型进行预测五、模型改进改进后的模型示例以下文字及代码仅供参考。附源码和数据集和运行结果能识别出sad,happy,等7种情绪采用的Python语言基于深度学习的语音情绪识别。使用的神经网络是卷积神经网络CNN。首先先设计出了一个卷积神经网络感觉还不太完善就对其神经网络进行改进得到了一个更完善的神经网络显著的提高了模型的准确率上图为语音信号特征提取上图为卷积神经网络上图卷积神经网络示意图采用的 Python 语言 基于深度学习的语音情绪识别。使用 的神经网络是卷积神经网络 CNN 。 首先先设计出了一个卷积神经网络 感觉还不 太完善 就对其神经网络进行改进得到了一个更完善的神经网络显著的提高 了模型的准确率。 为了完成我的实验设计我首先学习了语音情绪识别所要解决的问题。 1. 语 音信号的基本参数语音信号在计算机中的存储。 2. 语音信号预处理。 3. 语音信 号特征提取。 4. 神经网络的学习特别是卷积神经网络本实验中用到的神经网 络就是卷积神经网络。1上图为优化器基于深度学习的语音情绪识别使用Python语言基于深度学习中的卷积神经网络CNN实现语音情绪识别。该系统能够识别7种情绪sad, happy, angry, fearful, disgusted, surprised 和 neutral。一、环境配置pipinstallnumpy pandas librosa matplotlib tensorflow keras二、数据集推荐使用RAVDESSThe Ryerson Audio-Visual Database of Emotional Speech and Song数据集它包含24位专业演员演绎的7种基本情绪共1440个音频文件。三、技术流程数据预处理特征提取MFCC构建CNN模型训练模型评估模型预测情绪四、代码实现1. 导入所需库importosimportnumpyasnpimportpandasaspdimportlibrosaimportlibrosa.displayimportmatplotlib.pyplotaspltfrompython_speech_featuresimportmfccfromsklearn.model_selectionimporttrain_test_splitfromtensorflow.keras.modelsimportSequentialfromtensorflow.keras.layersimportDense,Dropout,Conv2D,MaxPool2D,Flattenfromtensorflow.keras.utilsimportto_categoricalfromtensorflow.keras.callbacksimportModelCheckpoint2. 加载数据并提取特征defextract_features(file_path,max_length100):audio,sample_ratelibrosa.load(file_path,res_typekaiser_fast)mfccsmfcc(audio,sampleratesample_rate,nfft1024,winlen0.025,winstep0.01,numcep13)# 填充或截断到统一长度ifmfccs.shape[0]max_length:mfccsmfccs[:max_length,:]else:pad_widthmax_length-mfccs.shape[0]mfccsnp.pad(mfccs,pad_width((0,pad_width),(0,0)),modeconstant)returnmfccsdefload_data(data_dir,max_length100,test_size0.2):features[]labels[]emotions{01:neutral,03:happy,04:sad,05:angry,06:fearful,07:disgusted,08:surprised}forsubdir,dirs,filesinos.walk(data_dir):forfileinfiles:iffile.endswith(.wav):file_pathos.path.join(subdir,file)emotion_codefile.split(-)[2]emotionemotions.get(emotion_code,None)ifemotion:mfccsextract_features(file_path,max_length)features.append(mfccs)labels.append(emotion)# 将标签转换为数字编码unique_labelssorted(list(set(labels)))label_to_index{label:ifori,labelinenumerate(unique_labels)}encoded_labels[label_to_index[label]forlabelinlabels]# 转换为numpy数组Xnp.array(features)yto_categorical(encoded_labels)# 分割训练集和测试集returntrain_test_split(X,y,test_sizetest_size,random_state42),unique_labels# 使用示例DATA_DIRpath/to/your/audio/files(X_train,X_test,y_train,y_test),classesload_data(DATA_DIR)print(fNumber of classes:{len(classes)})print(fClass labels:{classes})3. 构建改进的CNN模型defbuild_model(input_shape,num_classes):modelSequential()# 第一层卷积层model.add(Conv2D(64,(3,3),activationrelu,input_shapeinput_shape))model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 第二层卷积层model.add(Conv2D(128,(3,3),activationrelu))model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 第三层卷积层model.add(Conv2D(256,(3,3),activationrelu))model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 全连接层model.add(Flatten())model.add(Dense(256,activationrelu))model.add(Dropout(0.5))model.add(Dense(num_classes,activationsoftmax))# 编译模型model.compile(optimizeradam,losscategorical_crossentropy,metrics[accuracy])returnmodel# 构建模型调整输入形状以适应我们的MFCC特征input_shape(X_train.shape[1],X_train.shape[2],1)# 添加通道维度num_classeslen(classes)modelbuild_model(input_shape,num_classes)# 打印模型结构model.summary()4. 训练模型defreshape_data(X):returnX.reshape(X.shape[0],X.shape[1],X.shape[2],1)# 重塑数据以适应CNN输入X_train_cnnreshape_data(X_train)X_test_cnnreshape_data(X_test)# 设置回调以保存最佳模型checkpointModelCheckpoint(best_model.h5,monitorval_accuracy,verbose1,save_best_onlyTrue,modemax)# 训练模型historymodel.fit(X_train_cnn,y_train,validation_data(X_test_cnn,y_test),epochs50,batch_size32,callbacks[checkpoint])5. 可视化训练结果defplot_training_history(history):# 绘制准确率曲线plt.figure(figsize(12,4))plt.subplot(1,2,1)plt.plot(history.history[accuracy],labelTraining Accuracy)plt.plot(history.history[val_accuracy],labelValidation Accuracy)plt.title(Training and Validation Accuracy)plt.xlabel(Epoch)plt.ylabel(Accuracy)plt.legend()# 绘制损失曲线plt.subplot(1,2,2)plt.plot(history.history[loss],labelTraining Loss)plt.plot(history.history[val_loss],labelValidation Loss)plt.title(Training and Validation Loss)plt.xlabel(Epoch)plt.ylabel(Loss)plt.legend()plt.tight_layout()plt.show()# 显示训练历史plot_training_history(history)6. 评估模型性能# 评估模型test_loss,test_accmodel.evaluate(X_test_cnn,y_test,verbose0)print(f\nTest accuracy:{test_acc:.4f})# 显示混淆矩阵fromsklearn.metricsimportconfusion_matriximportseabornassnsdefplot_confusion_matrix(y_true,y_pred,classes):cmconfusion_matrix(np.argmax(y_true,axis1),np.argmax(y_pred,axis1))plt.figure(figsize(10,8))sns.heatmap(cm,annotTrue,fmtd,cmapBlues,xticklabelsclasses,yticklabelsclasses)plt.xlabel(Predicted Label)plt.ylabel(True Label)plt.title(Confusion Matrix)plt.show()# 预测测试集y_predmodel.predict(X_test_cnn)plot_confusion_matrix(y_test,y_pred,classes)7. 使用模型进行预测defpredict_emotion(file_path,model,classes,max_length100):# 提取特征featuresextract_features(file_path,max_length)# 重塑特征以匹配模型输入featuresfeatures.reshape(1,features.shape[0],features.shape[1],1)# 进行预测predictionmodel.predict(features)# 获取预测标签predicted_classnp.argmax(prediction)predicted_emotionclasses[predicted_class]# 返回预测结果returnpredicted_emotion,prediction[0]# 使用示例audio_filepath/to/audio/file.wavpredicted_emotion,probabilitiespredict_emotion(audio_file,model,classes)print(fPredicted emotion:{predicted_emotion})fori,probinenumerate(probabilities):print(f{classes[i]}:{prob:.4f})五、模型改进原始的CNN模型可能不够完善可以从以下几个方面进行改进增加数据增强通过添加背景噪声、改变音调和速度等方法来扩充数据集优化网络结构尝试不同的卷积核大小、层数和滤波器数量组合引入Batch Normalization加速训练过程并提高模型稳定性使用迁移学习利用在大规模语音数据集上预训练的模型进行微调尝试其他架构如结合RNN或Transformer的混合模型改进后的模型示例fromtensorflow.keras.layersimportBatchNormalizationdefbuild_improved_model(input_shape,num_classes):modelSequential()# 第一层卷积层model.add(Conv2D(64,(3,3),activationrelu,input_shapeinput_shape))model.add(BatchNormalization())model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 第二层卷积层model.add(Conv2D(128,(3,3),activationrelu))model.add(BatchNormalization())model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 第三层卷积层model.add(Conv2D(256,(3,3),activationrelu))model.add(BatchNormalization())model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 第四层卷积层model.add(Conv2D(512,(3,3),activationrelu))model.add(BatchNormalization())model.add(MaxPool2D((2,2)))model.add(Dropout(0.25))# 全连接层model.add(Flatten())model.add(Dense(512,activationrelu))model.add(BatchNormalization())model.add(Dropout(0.5))model.add(Dense(256,activationrelu))model.add(BatchNormalization())model.add(Dropout(0.5))model.add(Dense(num_classes,activationsoftmax))# 编译模型model.compile(optimizeradam,losscategorical_crossentropy,metrics[accuracy])returnmodel基于深度学习的语音情绪识别系统使用了改进的CNN架构在RAVDESS数据集上表现良好。你可以根据具体需求进一步调整网络结构、超参数或尝试其他深度学习架构以获得更好的性能。