w = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
x1 = [0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0];%"1" pattern #1
x2 = [0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1 1 1 0];%"1" pattern #2
x3 = [0 0 1 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0];%"1" pattern #3
x4 = [0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0];%"1" pattern #4
x5 = [0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0];%"1" pattern #5
x6 = [0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0];%"1" pattern #6
xone = [x1; x2; x3; x4; x5; x6];
z1 = [0 1 1 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 1 1 0];%"0" pattern #1
z2 = [0 0 1 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 0 1 0 0];%"0" pattern #2
z3 = [0 0 1 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 1 1 0];%"0" pattern #3
z4 = [0 0 1 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 1 1 0 0];%"0" pattern #4
z5 = [0 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 0 1 1 1 0];%"0" pattern #5
z6 = [1 1 1 1 1 1 0 0 0 1 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1];%"0" pattern #6
xzero = [z1; z2; z3; z4; z5; z6];
correct=0;
wrong=0;
d = [1 1 1 1 -1 -1 -1 -1];
b = 0;
alpha = 0.1;
% randomly sort the number from 1-6, choose the first 4 sets as the
% training sets and the last 2 sets as the test sets.
pick_index=randperm(6);
train_index=pick_index(1:4);
test_index=pick_index(5:6);
train=[xone(train_index,:);xzero(train_index,:)];
test=[xone(test_index,:);xzero(test_index,:)];
%learning
for item=1:100
for i=1:8
y = sign(train(i,:) * w' + b);
e = d(i) - y;
w = w + alpha * e * train(i,:);
b = b + alpha * e;
end
end
% testing
for j=1:4
ytest(j,1) = sign(test(j,:) * w' + b);
end
if ytest(1,1)==1
correct=correct+1;
else
wrong=wrong+1;
end
if ytest(2,1)==1
correct=correct+1;
else
wrong=wrong+1;
end
if ytest(3,1)==-1
correct=correct+1;
else
wrong=wrong+1;
end
if ytest(4,1)==-1
correct=correct+1;
else
wrong=wrong+1;
end
errorrate=wrong/(wrong+correct);
感知器 0与1的识别
最新推荐文章于 2021-03-20 03:43:12 发布