%用单层感知器实现逻辑"与"
%"或"逻辑也可以采取同样的方法得到
%异或、同或此方法无解,调教不出来
%权值初始化:任意
%学习方式:有导师
%变换函数:二进制
%清理环境
clear;
close all;
clc;
%设置参数
fun_handle = @sgn; %变换函数的句柄
%四个样本
X = [ -1,0,0;-1,0,1;-1,1,0;-1,1,1];%样本值
d = [ 0,0,0,1 ]; %导师信号
eta = 0.1;%学习率
T = 0.1; %阈值初始值
W = rand(1,3); %权值向量初始值
W(1) = T;
W1 = []; %用于存放历次迭代调教调整后的权值w1
W2 = []; %用于存放历次迭代调教调整后的权值w2
deviation= []; %用于存放历次调教调整后的误差值
k = 0;%全样本迭代调教次数
%迭代调教直到误差为0
while(1)
s = 0;
for j = 1:length(d)
net_j = W*X(:,j);
o_j = fun_handle(net_j,1);
W = W + eta*(d(j)-o_j)*X(:,j)';
s = s + abs(d(j)-o_j);
end
deviation = [ deviation s];
k = k + 1;
W1 = [ W1 W(2)];
W2 = [ W2 W(3)];
if( s == 0)
break;
end
end
%绘图:画出调教过程中相关量的变化
figure(1);
subplot(3,1,1);
x = 1:k;
plot(x,deviation,'b-');
xlabel('迭代次数');
ylabel('误差');
title('误差的收敛曲线');
subplot(3,1,2);
plot(x,W1,'r-');
xlabel('迭代次数');
ylabel('W_1');
title('权值W_1的变化过程');
subplot(3,1,2);
plot(x,W2,'r-');
xlabel('迭代次数');
ylabel('W_2');
title('权值W_2的变化过程');
figure(2);
x1 = -1:4;
x2 = (W(1)-W(2)*x1)/W(3);
plot(x1,x2,'b--');
xlabel('x_1');
ylabel('x_2');
grid on;
hold on;
title('样本分布及分界线');
x = [0 0 1 1];
y = [0 1 0 1];
plot(x(1:3),y(1:3),'bo'); %直线下方
plot(x(4),y(4),'b*'); %直线上方
%打印:调教终值
display(["the final deviation",num2str(s)]);
display(['the epoch is:',num2str(k)]);
display(['the final W is ',num2str(W(2)),' ',num2str(W(3))]);
display(['the final T is:',num2str(W(1))]);
%sgn.m
function [ output ] = sgn( x , type )
%神经元变换函数-阈值型变换函数
%x:自变量值
%type:函数类型
%type == 1 单极性符号函数
%type ~= 1 双极性符号函数
if( type == 1)
output = ( x>=0);
else %双极性
if( x >= 0 )
output = 1;
else
output = -1;
end
end
end
运行效果: