2011-02-03 30 views
8

Tôi đang xem xét một mã từ Toronto perceptron MATLAB codethực hiện và ploting một Perceptron trong MATLAB

Mã này là

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

w = w_init; 
for iteration = 1 : 100 %<- in practice, use some stopping criterion! 
    for ii = 1 : size(X,2)   %cycle through training set 
    if sign(w'*X(:,ii)) ~= Y(ii) %wrong decision? 
     w = w + X(:,ii) * Y(ii); %then add (or subtract) this point to w 
    end 
    end 
    sum(sign(w'*X)~=Y)/size(X,2) %show misclassification rate 
end 

Vì vậy, tôi đang đọc làm thế nào để áp dụng chức năng này để dữ liệu ma trận X, và mục tiêu Y, nhưng, không biết cách sử dụng hàm này, tôi hiểu, nó trả về một vectơ có trọng số, do đó nó có thể phân loại.

Bạn có thể đưa ra một ví dụ và giải thích nó không ??

Tôi đã cố gắng

X=[0 0; 0 1; 1 1] 
Y=[1 0; 2 1] 
w=[1 1 1] 
Result = perceptron(X, Y, w) 

??? Error using ==> mtimes 
Inner matrix dimensions must agree. 

Error in ==> perceptron at 15 
      if sign(w'*X(:,ii)) ~= Y(ii) 

    Result = perceptron(X, Y, w') 

??? Error using ==> ne 
Matrix dimensions must agree. 

Error in ==> perceptron at 19 
     sum(sign(w'*X)~=Y)/size(X,2);  

Cảm ơn

Cảm ơn bạn đã anwers, tôi có thêm một, Nếu tôi thay đổi Y = [0, 1], những gì xảy ra với các thuật toán ?.

Vì vậy, Mọi dữ liệu đầu vào sẽ không làm việc với Y = [0,1] với mã này của Perceptron đúng ?,

-------------- --------------- CHỈNH SỬA ------------------------

Một câu hỏi nữa, nếu Tôi muốn vẽ đường dây chia 2 lớp, tôi biết chúng ta có thể nhận được rằng dòng giải phương trình tuyến tính hệ thống có liên quan đến trọng số, nhưng làm cách nào, tôi có thể làm gì ?, Tôi đang thử một cái gì đó như

% the initial weights 
w_init = [ 1 1 1]'; 
% the weights returned from perceptron  
wtag = perceptron(X,Y,w_init,15); 

% concatenate both 
Line = [wtag,w_init] 

% solve the linear system, am I correct doing this? 
rref(Line') 

% plot??? 

Trả lời

17

Trước tiên, bạn nên hiểu ý nghĩa của mỗi người trong số các đầu vào là gì:

  • X là ma trận đầu vào của các ví dụ, có kích thước M x N, trong đó M là kích thước của vectơ tính năng và N số lượng mẫu. Vì mô hình perceptron cho dự đoán là Y=w*X+b, bạn phải cung cấp thêm một chiều trong X là hằng số, thường được đặt thành 1, do đó, cụm từ b được "tích hợp sẵn" thành X. Trong ví dụ bên dưới cho X, tôi đặt mục nhập cuối cùng là X thành 1 trong tất cả các mẫu.
  • Y là phân loại chính xác cho mỗi mẫu từ X (phân loại bạn muốn perceptron học), do đó, nó phải là một vectơ hàng N chiều - một đầu ra cho mỗi ví dụ đầu vào. Vì perceptron là một phân loại nhị phân, nên chỉ có 2 giá trị có thể khác nhau. Nhìn vào mã, bạn thấy rằng nó kiểm tra dấu hiệu của dự đoán, cho bạn biết rằng các giá trị được phép là Y phải là -1,+1 (và không phải là 0,1 chẳng hạn).
  • w là vectơ trọng lượng bạn đang cố gắng tìm hiểu.

Vì vậy, hãy cố gắng gọi hàm với:

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

EDIT

Sử dụng đoạn mã sau để gọi alg perceptron và xem kết quả đồ họa:

% 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') 
+0

Phản hồi tốt đẹp !! – qdjm

+1

Cảm ơn bạn rất nhiều, tôi thực sự hiểu ví dụ của bạn, nhưng có thêm một câu hỏi: Bạn sẽ làm gì nếu lớp 1 có nhiều ví dụ hơn lớp 0 ?? trong ví dụ bạn cung cấp có cùng số ví dụ cho cả hai lớp, X1 và X2 – cMinor

+0

Điều này có đúng không, tôi không thể kiểm tra ngay bây giờ: X1 = [rand (1,100); rand (1,100);)]; % class '+1' X2 = [rand (1.300), 1 + rand (1.300); cái (1.300)]; % class '-1' X = [X1, X2]; % lớp đầu ra [-1, + 1]; Y = [- những người (1,100), những người (1.300)]; % vectơ weigth init w = [.5 .5 .5] '; wtag = perceptron (X, Y, w); – cMinor

1

thử điều này:

perceptron([1 2 1 2], [1 0 1 0], 0.5); 
+4

Ví dụ của bạn sẽ không hoạt động vì thuật toán giả định giá trị đầu ra của [-1, + 1] chứ không phải [0,1]. Vector 'w' sẽ không được cập nhật. –

+3

Ngoài ra, đầu vào phải ít nhất là kích thước 2, nếu không bạn giả định rằng 'b = 0' trong' y = a * x + b' –

10

Nếu bạn quan tâm, đây là một bản demo perceptron nhỏ được viết theo cách khá hướng dẫn:

function perceptronDemo 
%PERCEPTRONDEMO 
% 
% A simple demonstration of the perceptron algorithm for training 
% a linear classifier, made as readable as possible for tutorial 
% purposes. It is derived from the treatment of linear learning 
% machines presented in Chapter 2 of "An Introduction to Support 
% Vector Machines" by Nello Cristianini and John Shawe-Taylor. 
% 
% 

    Data = createTrainingData; 
    Model = trainPerceptron(Data); 

end 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
function Model = trainPerceptron(Data) 
%TRAINPERCEPTRON 

    DOWN = 1; 
    ACROSS = 2; 

    assert(isequal(unique(Data.labels), [-1; +1]), ... 
     'Labels must be -1 or +1'); 

    % --------------------------------------------------------------------- 
    % Normalise the data by calculating z-scores 
    % 
    % This makes plotting easier, but is not needed by the algorithm. 
    % 

    sampleMean = mean(Data.samples); 
    sampleStdDev = std( Data.samples); 
    Data.samples = bsxfun(@minus, Data.samples, sampleMean ); 
    Data.samples = bsxfun(@rdivide, Data.samples, sampleStdDev); 

    % --------------------------------------------------------------------- 
    % Calculate the squared radius of the smallest ball that encloses the 
    % data and is centred on the origin. This is used to provide an 
    % appropriate range and step size when updating the threshold (bias) 
    % parameter. 
    % 

    sampleSize = size(Data.samples, DOWN); 
    maxNorm = realmin; 
    for iObservation = 1:sampleSize 
     observationNorm = norm(Data.samples(iObservation,:)); 
     if observationNorm > maxNorm 
      maxNorm = observationNorm; 
     end 
    end 
    enclosingBallRadius  = maxNorm; 
    enclosingBallRadiusSquared = enclosingBallRadius .^ 2; 

    % --------------------------------------------------------------------- 
    % Define the starting weight vector and bias. These should be zeros, 
    % as the algorithm omits a learning rate, and it is suggested in 
    % Cristianini & Shawe-Taylor that learning rate may only be omitted 
    % safely when the starting weight vector and bias are zero. 
    % 

    Model.weights = [0.0 0.0]; 
    Model.bias = 0.0; 

    % --------------------------------------------------------------------- 
    % Run the perceptron training algorithm 
    % 
    % To prevent program running forever when nonseparable data are 
    % provided, limit the number of steps in the outer loop. 
    % 

    maxNumSteps = 1000; 

    for iStep = 1:maxNumSteps 

     isAnyObsMisclassified = false; 

     for iObservation = 1:sampleSize; 

      inputObservation = Data.samples(iObservation, :); 
      desiredLabel  = Data.labels( iObservation ); % +1 or -1 

      perceptronOutput = sum(Model.weights .* inputObservation, ACROSS) + Model.bias; 
      margin   = desiredLabel * perceptronOutput; 

      isCorrectLabel = margin > 0; 

      % ------------------------------------------------------------- 
      % If the model misclassifies the observation, update the 
      % weights and the bias. 
      % 

      if ~isCorrectLabel 

       isAnyObsMisclassified = true; 

       weightCorrection = desiredLabel * inputObservation; 
       Model.weights = Model.weights + weightCorrection; 

       biasCorrection = desiredLabel .* enclosingBallRadiusSquared; 
       Model.bias  = Model.bias + biasCorrection; 

       displayPerceptronState(Data, Model); 

      end % if this observation misclassified. 

     end % loop over observations 

     if ~isAnyObsMisclassified 
      disp('Done!'); 
      break; 
     end 

    end % outer loop 

end % TRAINPERCEPTRON 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
function Data = createTrainingData 
%CREATETRAININGDATA 
% 
% Return a structure containing training data suitable for linear 
% classification. 
% 

    sampleAsize = 1024; 
    sampleBsize = 1024; 

    sampleAmean = [ 5.5 5.0 ]; 
    sampleAstdDev = [ 0.5 1.0 ]; 

    sampleBmean = [ 2.5 3.0 ]; 
    sampleBstdDev = [ 0.3 0.7 ]; 

    Data.samples = [ normallyDistributedSample(sampleAsize, sampleAmean, sampleAstdDev); ... 
         normallyDistributedSample(sampleBsize, sampleBmean, sampleBstdDev) ]; 

    Data.labels = [ ones(sampleAsize,1); ... 
         -ones(sampleBsize,1) ]; 

    % --------------------------------------------------------------------- 
    % Randomly permute samples & class labels. 
    % 
    % This is not really necessary, but done to illustrate that the order 
    % in which observations are evaluated does not matter. 
    % 

    randomOrder = randperm(sampleAsize + sampleBsize); 
    Data.samples = Data.samples(randomOrder, :); 
    Data.labels = Data.labels( randomOrder, :); 

end % CREATETRAININGDATA 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
function samples = normallyDistributedSample(sampleSize, sampleMean, sampleStdDev) 
%NORMALDISTRIBUTIONSAMPLE 
% 
% Draw a sample from a normal distribution with specified mean and 
% standard deviation. 
% 

    assert( isequal(size(sampleMean), size(sampleStdDev)) ... 
      && 1 == size(sampleMean, 1),       ... 
     'Sample mean and standard deviation must be row vectors of equal length.'); 

    numFeatures = numel(sampleMean); 
    samples  = randn(sampleSize, numFeatures); 
    samples  = bsxfun(@times, samples, sampleStdDev); 
    samples  = bsxfun(@plus, samples, sampleMean ); 

end % NORMALDISTRIBUTIONSAMPLE 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
function displayPerceptronState(Data, Model) 
%DISPLAYPERCEPTRONSTATE 

    hFig = figure(1); 
    clf; 
    set(hFig,      ... 
     'NumberTitle', 'off',   ... 
     'Name',   mfilename, ... 
     'MenuBar',  'none',  ... 
     'Color',  [1.0 1.0 1.0]); 

    displayXmin = -4; 
    displayXmax = 4; 
    displayYmin = -4; 
    displayYmax = 4; 

    hAx = subplot(1, 1, 1); 
    axis('equal'); 
    set(hAx,         ... 
     'Box',  'on',      ... 
     'NextPlot', 'add',      ... 
     'xgrid', 'on',      ... 
     'ygrid', 'on',      ... 
     'xlim',  [displayXmin displayXmax], ... % Bounds suitable for Z-scored data 
     'ylim',  [displayYmin displayYmax] ); 
    xlabel('x_1'); 
    ylabel('x_2'); 

    % --------------------------------------------------------------------- 
    % Plot data points from the two classes 
    % 

    isPositiveClass = Data.labels > 0; 
    isNegativeClass = Data.labels <= 0; 

    plot(hAx, Data.samples(isPositiveClass,1), Data.samples(isPositiveClass,2), 'b+'); 
    plot(hAx, Data.samples(isNegativeClass,1), Data.samples(isNegativeClass,2), 'rx'); 

    % --------------------------------------------------------------------- 
    % Display parameters for separating hyperplane in title 
    % 

    xWeight = Model.weights(1); 
    yWeight = Model.weights(2); 
    bias  = Model.bias; 

    szTitle = sprintf('Linear classifier parameters: %0.2f x_1 + %0.2f x_2 + %0.2f = 0', xWeight, yWeight, bias); 
    title(szTitle); 

    % --------------------------------------------------------------------- 
    % Plot separating hyperplane 
    % 

    y1 = ((xWeight*displayXmin) + bias) ./ -yWeight; 
    y2 = ((xWeight*displayXmax) + bias) ./ -yWeight; 

    plot(hAx, [displayXmin; displayXmax], [y1, y2], 'k-', 'linewidth', 2); 

    pause(0.1); 

end % DISPLAYPERCEPTRONSTATE 
Các vấn đề liên quan