1. BP神经网络基本原理
BP(Back Propagation)神经网络是一种多层前馈神经网络,通过误差反向传播算法进行训练。
网络结构:
- 输入层:接收故障特征数据
- 隐藏层:进行特征变换和模式识别
- 输出层:输出分类结果
2. MATLAB实现代码
完整示例代码:
matlab
%% BP神经网络故障分类MATLAB实现
clear; clc; close all;
%% 1. 数据准备和预处理
% 生成示例故障数据(实际应用中替换为您的实际数据)
% 假设有3种故障类型,每种故障有4个特征
numSamples = 300; % 总样本数
numFeatures = 4; % 特征数
numClasses = 3; % 故障类别数
% 生成模拟数据
rng(1); % 设置随机种子保证可重复性
X = zeros(numSamples, numFeatures);
Y = zeros(numSamples, 1);
% 故障类型1的数据(均值[1,1,1,1])
X(1:100, :) = randn(100, numFeatures) + repmat([1, 1, 1, 1], 100, 1);
Y(1:100) = 1;
% 故障类型2的数据(均值[2,2,2,2])
X(101:200, :) = randn(100, numFeatures) + repmat([2, 2, 2, 2], 100, 1);
Y(101:200) = 2;
% 故障类型3的数据(均值[3,3,3,3])
X(201:300, :) = randn(100, numFeatures) + repmat([3, 3, 3, 3], 100, 1);
Y(201:300) = 3;
%% 2. 数据预处理
% 数据归一化(重要步骤)
[X_normalized, inputPS] = mapminmax(X', 0, 1);
X_normalized = X_normalized';
% 将标签转换为one-hot编码
Y_categorical = categorical(Y);
Y_onehot = full(ind2vec(double(Y_categorical)'))';
%% 3. 数据集划分
trainRatio = 0.7;
valRatio = 0.15;
testRatio = 0.15;
cv = cvpartition(Y, 'HoldOut', testRatio);
trainIdx = cv.training;
testIdx = cv.test;
% 从训练集中再划分验证集
cv_val = cvpartition(Y(trainIdx), 'HoldOut', valRatio/(trainRatio+valRatio));
valIdx = false(size(Y));
valIdx(find(trainIdx)==find(cv_val.test)) = true;
X_train = X_normalized(trainIdx & ~valIdx, :);
Y_train = Y_onehot(trainIdx & ~valIdx, :);
X_val = X_normalized(valIdx, :);
Y_val = Y_onehot(valIdx, :);
X_test = X_normalized(testIdx, :);
Y_test = Y_onehot(testIdx, :);
Y_test_labels = Y(testIdx);
fprintf('训练集样本数: %d\n', size(X_train, 1));
fprintf('验证集样本数: %d\n', size(X_val, 1));
fprintf('测试集样本数: %d\n', size(X_test, 1));
%% 4. 创建和训练BP神经网络
% 方法1:使用MATLAB的patternnet(推荐)
hiddenLayerSize = 10; % 隐藏层神经元数量
net = patternnet(hiddenLayerSize);
% 设置训练参数
net.trainFcn = 'trainlm'; % Levenberg-Marquardt算法
net.trainParam.epochs = 1000;
net.trainParam.goal = 1e-5;
net.trainParam.max_fail = 20;
net.trainParam.showWindow = true;
% 设置数据划分比例
net.divideFcn = 'divideind'; % 使用索引划分
net.divideParam.trainInd = 1:size(X_train, 1);
net.divideParam.valInd = (1:size(X_val, 1)) + size(X_train, 1);
net.divideParam.testInd = [];
% 合并训练集和验证集用于训练函数
X_train_val = [X_train; X_val]';
Y_train_val = [Y_train; Y_val]';
% 训练网络
[net, tr] = train(net, X_train_val, Y_train_val);
%% 5. 模型测试和评估
% 测试集预测
Y_pred = net(X_test');
Y_pred = Y_pred';
% 将预测结果转换为类别标签
[~, Y_pred_labels] = max(Y_pred, [], 2);
% 计算准确率
accuracy = sum(Y_pred_labels == Y_test_labels) / length(Y_test_labels);
fprintf('测试集准确率: %.2f%%\n', accuracy * 100);
% 混淆矩阵
figure;
plotconfusion(ind2vec(Y_test_labels'), ind2vec(Y_pred_labels'));
title('混淆矩阵');
%% 6. 结果可视化
% 训练过程性能曲线
figure;
plotperform(tr);
title('训练性能曲线');
% 误差直方图
figure;
ploterrhist(Y_test_labels - Y_pred_labels);
title('预测误差直方图');
% 特征空间可视化(使用前两个特征)
if numFeatures >= 2
figure;
gscatter(X_test(:,1), X_test(:,2), Y_test_labels);
hold on;
gscatter(X_test(:,1), X_test(:,2), Y_pred_labels, 'krg', 'oxs');
legend('真实类别1','真实类别2','真实类别3',...
'预测类别1','预测类别2','预测类别3');
xlabel('特征1');
ylabel('特征2');
title('特征空间分类结果');
end
%% 7. 模型保存和应用
% 保存训练好的网络
save('fault_classification_net.mat', 'net', 'inputPS');
% 加载和使用模型的示例函数
function label = classify_fault(new_data, net, inputPS)
% 数据预处理
new_data_normalized = mapminmax('apply', new_data', inputPS)';
% 预测
output = net(new_data_normalized');
% 获取预测标签
[~, label] = max(output);
end
3. 使用MATLAB的Deep Learning Toolbox(替代方法)
matlab
%% 方法2:使用Deep Learning Toolbox的更加灵活的方式
clear; clc;
% 数据准备(同上)
% ... [数据准备代码]
% 创建序列网络
layers = [
featureInputLayer(numFeatures, 'Name', 'input')
fullyConnectedLayer(20, 'Name', 'fc1')
reluLayer('Name', 'relu1')
fullyConnectedLayer(15, 'Name', 'fc2')
reluLayer('Name', 'relu2')
fullyConnectedLayer(numClasses, 'Name', 'fc3')
softmaxLayer('Name', 'softmax')
classificationLayer('Name', 'output')
];
% 训练选项
options = trainingOptions('adam', ...
'MaxEpochs', 100, ...
'InitialLearnRate', 0.001, ...
'ValidationData', {X_val, Y_categorical(valIdx)}, ...
'ValidationFrequency', 10, ...
'Verbose', true, ...
'Plots', 'training-progress');
% 转换数据格式
Y_train_cat = Y_categorical(trainIdx & ~valIdx);
% 训练网络
net_dl = trainNetwork(X_train, Y_train_cat, layers, options);
% 预测和评估
YPred = classify(net_dl, X_test);
accuracy_dl = sum(YPred == Y_categorical(testIdx)) / numel(Y_categorical(testIdx));
fprintf('深度学习工具箱准确率: %.2f%%\n', accuracy_dl * 100);
参考代码 使用BP神经网络对故障数据实现分类以及matlab实现 www.3dddown.com/csa/81390.html
4. 说明
数据预处理:
- 归一化:将特征缩放到相同范围
- one-hot编码:将类别标签转换为神经网络友好的格式
- 数据集划分:训练集、验证集、测试集
网络参数调优:
matlab
% 可调整的参数
hiddenLayerSize = [10, 15, 20]; % 尝试不同的隐藏层结构
learningRate = 0.01; % 学习率
trainFcn = {'trainlm', 'trainbr', 'trainscg'}; % 不同的训练算法
性能评估指标:
matlab
% 计算其他评估指标
confMat = confusionmat(Y_test_labels, Y_pred_labels);
precision = diag(confMat) ./ sum(confMat, 1)';
recall = diag(confMat) ./ sum(confMat, 2);
f1Score = 2 * (precision .* recall) ./ (precision + recall);
fprintf('各类别精确率: %.3f, %.3f, %.3f\n', precision);
fprintf('各类别召回率: %.3f, %.3f, %.3f\n', recall);
fprintf('各类别F1分数: %.3f, %.3f, %.3f\n', f1Score);