基于CNN的五折交叉验证多分类预测模型 - MATLAB实现
基于CNN的五折交叉验证多分类预测模型 - MATLAB实现
本文将介绍如何使用MATLAB构建一个基于卷积神经网络(CNN)的五折交叉验证多分类预测模型。
1. 数据导入和环境准备matlab% 关闭报警信息warning off % 关闭开启的图窗close all % 清空变量clear % 清空命令行clc% 导入数据res = xlsread('7变量170样本.xlsx');
2. 设置随机种子matlab% 设置随机种子为250,确保结果可复现rng(250);
3. 五折交叉验证matlab% 设置折数K = 5; % 随机分配数据到 K 个折中indices = crossvalind('Kfold', size(res, 1), K); % 初始化混淆矩阵n_classes = 4; % 类别数confusion_mat = zeros(n_classes, n_classes);
4. 循环进行五折交叉验证matlabfor k = 1:K disp(['第 ' num2str(k) ' 折交叉验证...']) % 划分训练集和测试集 test_idx = (indices == k); % 当前折为测试集 train_idx = ~test_idx; % 其他折为训练集 P_train = res(train_idx, 1:7)'; % 训练集特征 T_train = res(train_idx, 8)'; % 训练集标签 M = size(P_train, 2); P_test = res(test_idx, 1:7)'; % 测试集特征 T_test = res(test_idx, 8)'; % 测试集标签 N = size(P_test, 2); % 数据归一化 [P_train, ps_input] = mapminmax(P_train, 0, 1); P_test = mapminmax('apply', P_test, ps_input); t_train = categorical(T_train); t_test = categorical(T_test); % 数据平铺 p_train = double(reshape(P_train, 7, 1, 1, M)); p_test = double(reshape(P_test, 7, 1, 1, N)); % 构建网络结构 layers = [ imageInputLayer([7, 1, 1]) % 输入层 convolution2dLayer([2, 1], 16) % 卷积层 batchNormalizationLayer % 批归一化层 reluLayer % relu激活层 maxPooling2dLayer([2, 1], 'Stride', 1) % 最大池化层 convolution2dLayer([2, 1], 32) % 卷积层 batchNormalizationLayer % 批归一化 reluLayer % relu激活层 maxPooling2dLayer([2, 1], 'Stride', 1) % 最大池化层 convolution2dLayer([2, 1], 64) % 卷积层 batchNormalizationLayer % 批归一化 reluLayer % relu激活层 maxPooling2dLayer([2, 1], 'Stride', 1) % 最大池化层 dropoutLayer(0.3) % Dropout层 fullyConnectedLayer(4) % 全连接层(类别数) softmaxLayer % 损失函数层 classificationLayer % 分类层 ]; % 设置训练参数 options = trainingOptions('adam', ... % Adam 梯度下降算法 'MaxEpochs', 500, ... % 最大训练次数为500 'InitialLearnRate', 1e-2, ... % 初始学习率为0.01 'L2Regularization', 1e-04, ... % L2正则化参数 'LearnRateSchedule', 'piecewise', ... % 学习率下降 'LearnRateDropFactor', 0.1, ... % 学习率下降因子为0.1 'LearnRateDropPeriod', 50, ... % 经过50次训练后,学习率减少到原来的0.1倍 'ValidationData', {p_test, t_test}, ... % 指定验证数据 'Plots', 'training-progress', ... % 画出曲线 'Verbose', false, ... % 不显示训练过程 'MiniBatchSize', 128); % 批量大小为128 % 训练模型 net = trainNetwork(p_train, t_train, layers, options); % 测试模型 Y_train = classify(net,p_train); Y_test = classify(net, p_test); % 记录结果 labels_all = categorical(T_test); scores_all = categorical(Y_test); % 获取所有类别 classes = unique(labels_all); % 计算混淆矩阵 confusion_mat = confusionmat(labels_all, scores_all, 'order', classes);end
5. 计算模型性能指标matlab% 计算各项指标(整体)accuracy = sum(diag(confusion_mat)) / sum(confusion_mat(:));precision = diag(confusion_mat) ./ sum(confusion_mat, 2);recall = diag(confusion_mat) ./ sum(confusion_mat, 1)';F1score = 2 * precision .* recall ./ (precision + recall);
% 输出结果disp('---------------------------------------------------------')fprintf('整体准确率: %f ', accuracy)fprintf('整体精确率: %f ', mean(precision))fprintf('整体召回率: %f ', mean(recall))fprintf('整体F1得分: %f ', mean(F1score))disp('---------------------------------------------------------')
% 输出混淆矩阵disp('混淆矩阵:')disp(confusion_mat)
6. 绘制ROC曲线和计算AUCmatlabY_test_encoded = dummyvar(Y_test);scores_all = double(Y_test_encoded);figure;total_auc = 0; % 存储总的AUC值
for i = 1:n_classes % 提取当前类别的标签和预测概率 labels = double(labels_all) == i; scores = scores_all(:, i); % 计算当前类别的AUC值和ROC曲线点 [X, Y, ~, AUC] = perfcurve(labels, scores, 1); % 累加AUC值 total_auc = total_auc + AUC; % 绘制ROC曲线 subplot(2, 2, i); plot(X, Y); xlabel('False Positive Rate'); ylabel('True Positive Rate'); title(['ROC Curve - Class ', num2str(i)]); legend(['AUC = ', num2str(AUC)]); grid on;end
% 计算微平均AUCmicro_average_auc = total_auc / n_classes;% 显示微平均AUCfprintf('Micro-average AUC: %f ', micro_average_auc);
7. 性能评估和可视化matlab% 训练集和测试集预测结果Y_train1 = double(transpose(Y_train));Y_test1 = double(transpose(Y_test));error1 = sum((Y_train1 == T_train)) / M * 100 ;error2 = sum((Y_test1 == T_test )) / N * 100 ;
% 绘制网络分析图analyzeNetwork(layers)
% 数据排序[T_train, index_1] = sort(T_train);[T_test , index_2] = sort(T_test );
Y_train = Y_train(index_1);Y_test = Y_test(index_2);
% 绘制混淆矩阵图figure;confusionchart(confusion_mat, classes);title('混淆矩阵');
% 绘制训练集预测结果对比图(线图)figuretrain_pred = double(transpose(Y_train));plot(1: M, T_train, 'r-*', 1: M, train_pred, 'b-o', 'LineWidth', 1)legend('真实值', '预测值')xlabel('预测样本')ylabel('预测结果')string = {'训练集预测结果对比'; ['准确率=' num2str(error1) '%']};title(string)xlim([1, M])grid
% 绘制测试集预测结果对比图(线图)figure;test_pred = double(transpose(Y_test));plot(1:N, T_test, 'r-*', 1:N, test_pred, 'b-o', 'LineWidth', 1);legend('真实值', '预测值');xlabel('预测样本');ylabel('预测结果');string = {'测试集预测结果对比'; ['准确率=' num2str(error2) '%']};title(string);xlim([1, N]);grid;
总结
本文介绍了如何使用MATLAB构建一个基于CNN的五折交叉验证多分类预测模型,并提供了详细的代码示例和结果可视化方法。该模型可以应用于各种多类别分类问题。
注意: 在实际应用中,您需要根据具体的数据集和问题调整模型参数和网络结构,以获得最佳性能。
原文地址: https://www.cveoy.top/t/topic/O8A 著作权归作者所有。请勿转载和采集!