单个感知器不会聚

时间:2017-10-18 14:59:59

标签: matlab machine-learning

我在matlab中编写一个简单的感知器,但它没有收敛,我无法弄清楚原因。

目标是对2D点进行二元分类。

%P1 Generate a dataset of two-dimensional points, and choose a random line in
%the plane as your target function f, where one side of the line maps to +1 and
%the other side to -1. Let the inputs xn 2 R2 be random points in the plane,
%and evaluate the target function f on each xn to get the corresponding output
%yn = f(xn).

clear all;
clc
clear

n = 20;
inputSize = 2; %number of inputs 
dataset = generateRandom2DPointsDataset(n)';
[f , m , b] = targetFunction();
signs = classify(dataset,m,b);
weights=ones(1,2)*0.1;
threshold = 0;
fprintf('weights before:%d,%d\n',weights);
mistakes = 1;
numIterations = 0;


figure;
plotpv(dataset',(signs+1)/2);%mapping signs from -1:1 to 0:1 in order to use plotpv
hold on;
line(f(1,:),f(2,:));
pause(1)

while true
    mistakes = 0;
    for i = 1:n   
        if dataset(i,:)*weights' > threshold
            result = 1;
        else
            result = -1;
        end

        error = signs(i) - result;
        if error ~= 0
            mistakes = mistakes + 1;
            for j = 1:inputSize
                weights(j) = weights(j) + error*dataset(i,j);
            end
        end  

        numIterations = numIterations + 1

    end

    if mistakes == 0
        break

    end


end
fprintf('weights after:%d,%d\n',weights);
由于plotpv工作正常,随机点和符号都很好 enter image description here

代码基于http://es.mathworks.com/matlabcentral/fileexchange/32949-a-perceptron-learns-to-perform-a-binary-nand-function?focused=5200056&tab=function

当我暂停无限循环时,这是我的vairables的状态: enter image description here

我无法理解为什么它没有收敛。

附加代码(很好,只是为了避免答案要求)

function [f,m,b] = targetFunction()

    f = rand(2,2);
    f(1,1) = 0;
    f(1,2) = 1;

    m = (f(2,2) - f(2,1)); 
    b = f(2,1);  
end


function dataset = generateRandom2DPointsDataset(n)

    dataset = rand(2,n);

end

function values = classify(dataset,m,b)

    for i=1:size(dataset,1)

         y = m*dataset(i,1) + b;
         if dataset(i,2) >= y, values(i) = 1;
         else values(i) = -1; 
         end

    end

end

0 个答案:

没有答案