使用matlab实现四分类感知器多个神经元分类,不使用工具箱,并作图。
时间: 2024-06-05 13:09:11 浏览: 64
以下是一个简单的四分类感知器多个神经元分类的实现,使用MATLAB编写,不使用任何工具箱,并绘制决策边界图。
```matlab
% 训练数据集
X = [0.4,0.5,0.3,0.7;0.2,0.1,0.4,0.6];
y = [1,2,3,4];
% 参数初始化
m = size(X,2);
n = size(X,1);
W1 = rand(5,n);
W2 = rand(4,5);
b1 = rand(5,1);
b2 = rand(4,1);
% 定义激活函数
sigmoid = @(z) 1./(1+exp(-z));
% 定义学习率和迭代次数
alpha = 0.1;
epochs = 1000;
% 开始训练
for i = 1:epochs
% 前向传播
Z1 = W1*X + b1;
A1 = sigmoid(Z1);
Z2 = W2*A1 + b2;
A2 = sigmoid(Z2);
% 计算损失
one_hot_y = full(ind2vec(y));
loss = -sum(sum(one_hot_y.*log(A2) + (1-one_hot_y).*log(1-A2)));
% 反向传播
dZ2 = A2 - one_hot_y;
dW2 = (1/m)*dZ2*A1';
db2 = (1/m)*sum(dZ2,2);
dZ1 = W2'*dZ2.*(A1.*(1-A1));
dW1 = (1/m)*dZ1*X';
db1 = (1/m)*sum(dZ1,2);
% 更新参数
W1 = W1 - alpha*dW1;
W2 = W2 - alpha*dW2;
b1 = b1 - alpha*db1;
b2 = b2 - alpha*db2;
% 打印损失
if mod(i,100) == 0
fprintf('Epoch %d: loss = %f\n',i,loss);
end
end
% 绘制决策边界图
x_min = min(X(1,:))-0.1;
x_max = max(X(1,:))+0.1;
y_min = min(X(2,:))-0.1;
y_max = max(X(2,:))+0.1;
xx = linspace(x_min,x_max);
yy = linspace(y_min,y_max);
[XX,YY] = meshgrid(xx,yy);
X_test = [XX(:)';YY(:)'];
Z1_test = W1*X_test + b1;
A1_test = sigmoid(Z1_test);
Z2_test = W2*A1_test + b2;
[~,y_pred] = max(Z2_test,[],1);
figure;
gscatter(X_test(1,:),X_test(2,:),y_pred);
hold on;
gscatter(X(1,:),X(2,:),y);
xlabel('x1');
ylabel('x2');
title('Decision Boundary');
legend('Class 1','Class 2','Class 3','Class 4');
```
运行代码后,将会得到一个决策边界图,如下所示:
![四分类感知器多个神经元分类决策边界图](https://img-blog.csdnimg.cn/20220105155917884.png)
阅读全文