matlab经典实例,BP神经网络matlab实例(简单而经典)
时间: 2023-08-05 09:06:35 浏览: 92
好的,这是一个经典的BP神经网络的matlab实例,它可以用于二分类问题:
```matlab
clc;
clear;
close all;
% 生成数据
x = [0 0 1 1; 0 1 0 1];
y = [0 1 1 0];
% 绘制数据
figure;
hold on;
scatter(x(1,y==0),x(2,y==0),'bo');
scatter(x(1,y==1),x(2,y==1),'rx');
title('数据分布');
legend('类别0','类别1');
% 设置参数
inputSize = 2;
hiddenSize = 2;
outputSize = 1;
learningRate = 0.1;
epochs = 10000;
% 初始化权重和偏置
W1 = randn(hiddenSize,inputSize);
b1 = randn(hiddenSize,1);
W2 = randn(outputSize,hiddenSize);
b2 = randn(outputSize,1);
% 训练模型
for i = 1:epochs
% 前向传播
z1 = W1*x + b1;
a1 = sigmoid(z1);
z2 = W2*a1 + b2;
y_pred = sigmoid(z2);
% 计算损失
loss = -1/length(y)*(y*log(y_pred')'+(1-y)*log(1-y_pred)');
% 反向传播
delta2 = (y_pred-y).*sigmoidGradient(z2);
delta1 = W2'*delta2.*sigmoidGradient(z1);
% 更新权重和偏置
W2 = W2 - learningRate*delta2*a1';
b2 = b2 - learningRate*sum(delta2,2);
W1 = W1 - learningRate*delta1*x';
b1 = b1 - learningRate*sum(delta1,2);
% 打印损失
if mod(i,1000) == 0
fprintf('Epoch %d, Loss %f\n',i,loss);
end
end
% 测试模型
x_test = [0.2 0.8; 0.3 0.9];
y_test = [0 1];
z1_test = W1*x_test + b1;
a1_test = sigmoid(z1_test);
z2_test = W2*a1_test + b2;
y_pred_test = sigmoid(z2_test);
fprintf('测试集准确率: %f\n',sum(round(y_pred_test)==y_test)/length(y_test));
% 绘制决策边界
figure;
hold on;
scatter(x(1,y==0),x(2,y==0),'bo');
scatter(x(1,y==1),x(2,y==1),'rx');
[x1_grid,x2_grid] = meshgrid(0:0.01:1,0:0.01:1);
y_pred_grid = zeros(size(x1_grid));
for i = 1:size(x1_grid,1)
for j = 1:size(x1_grid,2)
z1_grid = W1*[x1_grid(i,j); x2_grid(i,j)] + b1;
a1_grid = sigmoid(z1_grid);
z2_grid = W2*a1_grid + b2;
y_pred_grid(i,j) = sigmoid(z2_grid);
end
end
contour(x1_grid,x2_grid,y_pred_grid,[0.5,0.5],'LineWidth',2);
title('决策边界');
legend('类别0','类别1','决策边界');
```
在运行上述代码后,你会得到一个二分类问题的模型和决策边界。同时,你可以尝试更改参数和数据,来进一步了解BP神经网络的应用。
阅读全文