Implementing and ploting a perceptron in MATLAB

前端 未结 3 506
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 11:29

I´m reviewing a code from Toronto perceptron MATLAB code

The code is

function [w] = perceptron(X,Y,w_init)

w = w_init;
for iteration = 1 : 100  %&l         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 12:08

    You should first understand what is the meaning of each of the inputs:

    • X is the input matrix of examples, of size M x N, where M is the dimension of the feature vector, and N the number of samples. Since the perceptron model for prediction is Y=w*X+b, you have to supply one extra dimension in X which is constant, usually set to 1, so the b term is "built-in" into X. In the example below for X, I set the last entry of X to be 1 in all samples.
    • Y is the correct classification for each sample from X (the classification you want the perceptron to learn), so it should be a N dimensional row vector - one output for each input example. Since the perceptron is a binary classifier, it should have only 2 distinct possible values. Looking in the code, you see that it checks for the sign of the prediction, which tells you that the allowed values of Y should be -1,+1 (and not 0,1 for example).
    • w is the weight vector you are trying to learn.

    So, try to call the function with:

    X=[0 0; 0 1; 1 1];
    Y=[1 -1];
    w=[.5; .5; .5];
    

    EDIT

    Use the following code to call the perceptron alg and see the results graphically:

    % input samples
    X1=[rand(1,100);rand(1,100);ones(1,100)];   % class '+1'
    X2=[rand(1,100);1+rand(1,100);ones(1,100)]; % class '-1'
    X=[X1,X2];
    
    % output class [-1,+1];
    Y=[-ones(1,100),ones(1,100)];
    
    % init weigth vector
    w=[.5 .5 .5]';
    
    % call perceptron
    wtag=perceptron(X,Y,w);
    % predict
    ytag=wtag'*X;
    
    
    % plot prediction over origianl data
    figure;hold on
    plot(X1(1,:),X1(2,:),'b.')
    plot(X2(1,:),X2(2,:),'r.')
    
    plot(X(1,ytag<0),X(2,ytag<0),'bo')
    plot(X(1,ytag>0),X(2,ytag>0),'ro')
    legend('class -1','class +1','pred -1','pred +1')
    

提交回复
热议问题