Single layer neural network [closed]

拟墨画扇 提交于 2019-11-29 20:02:11
Amro

I can spot a few problems with the code. The main issue is that the target is multi-class (not binary), so you need to either use 3 output nodes one for each class (called 1-of-N encoding), or use a single output node with a different activation function (something capable of more than just binary output -1/1 or 0/1)

In the solution below, the perceptron has the following structure:

%# load your data
input = [
    0.832 64.643
    0.818 78.843
    1.776 45.049
    0.597 88.302
    1.412 63.458
];
target = [
    0 0 1
    0 0 1
    0 1 0
    0 0 1
    0 0 1
];

%# parameters of the learning algorithm
LEARNING_RATE = 0.1;
MAX_ITERATIONS = 100;
MIN_ERROR = 1e-4;

[numInst numDims] = size(input);
numClasses = size(target,2);

%# three output nodes connected to two-dimensional input nodes + biases
weights = randn(numClasses, numDims+1);

isDone = false;               %# termination flag
iter = 0;                     %# iterations counter
while ~isDone
    iter = iter + 1;

    %# for each instance
    err = zeros(numInst,numClasses);
    for i=1:numInst
        %# compute output: Y = W*X + b, then apply threshold activation
        output = ( weights * [input(i,:)';1] >= 0 );                       %#'

        %# error: err = T - Y
        err(i,:) = target(i,:)' - output;                                  %#'

        %# update weights (delta rule): delta(W) = alpha*(T-Y)*X
        weights = weights + LEARNING_RATE * err(i,:)' * [input(i,:) 1];    %#'
    end

    %# Root mean squared error
    rmse = sqrt(sum(err.^2,1)/numInst);
    fprintf(['Iteration %d: ' repmat('%f ',1,numClasses) '\n'], iter, rmse);

    %# termination criteria
    if ( iter >= MAX_ITERATIONS || all(rmse < MIN_ERROR) )
        isDone = true;
    end
end

%# plot points and one-against-all decision boundaries
[~,group] = max(target,[],2);                     %# actual class of instances
gscatter(input(:,1), input(:,2), group), hold on
xLimits = get(gca,'xlim'); yLimits = get(gca,'ylim');
for i=1:numClasses
    ezplot(sprintf('%f*x + %f*y + %f', weights(i,:)), xLimits, yLimits)
end
title('Perceptron decision boundaries')
hold off

The results of training over the five sample you provided:

Iteration 1: 0.447214 0.632456 0.632456 
Iteration 2: 0.000000 0.447214 0.447214 
...
Iteration 49: 0.000000 0.447214 0.447214 
Iteration 50: 0.000000 0.632456 0.000000 
Iteration 51: 0.000000 0.447214 0.000000 
Iteration 52: 0.000000 0.000000 0.000000 

Note that the data used in the example above only contains 5 samples. You would get more meaningful results if you had more training instances in each class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!