Step 4:
clear;
clc;
close all;
X=[0 0 %input matrix
0 1
1 0
1 1];
D=[0 %correct output matrix
1
1
0];X=X';
D=D';
net = feedforwardnet(10); % Create the network
%The
next few lines serve one purpose, to force the training to go through
enough epochs to properly trian the network (we don't want it to stop
training too early)
net.trainparam.goal =0; % This is our ideal
goal, which means that we'd like the error to be zero (this may not
happen, but it's a goal).
net.divideparam.valratio = 0; %This
means don't set aside part of the trianing data for "validation". The
data set is already too small (only 4 trials, or rows, of training).
net.divideparam.trainratio =1; %This means use all the training data (the four rows) for training
net.divideparam.testratio =0; %This means don't set aside any of the training data for an independent test
net.trainparam.min_grad
= 1e-100; %This means that stop training if the slope of the error
gradient is near zero (you've almost reached the bottom of the error
mountain so you're at the flat part of the path (near the minimum of
the error function).
net.trainparam.showwindow=0; % Don't show the training window when running the program
net = train(net,X,D) % Train the network using the data in X and D
Pick
a sample (or trial) to see how the network does. Each trial or
sample is one row of the X variable, so you would have to enter two
values: One for the first input node and one for the second input node
(as shown in the figure).
X1=input('Enter the value of the first input node = ');
X2=input('Enter the value of the second input node = ');
y
= net([X1 X2]') ; % y is the output of the trained network given
an input sample trial. In this case the input values at the two input
nodes are X1 and X2 (note the transpose symbol).
y=round(y); % Forcing the
output number to be either 1 or 0 since usually the network returns a
value that is a fraction (for example, 0.97 instead of 1).
disp(['For input values of ',num2str(X1),' and ',num2str(X2),' the network output is ',num2str(y)]);
You
can save and test this program in matlab (for example, save it as
trainandtestXOR and run it in the command window). Click here to see the completed Matlab program.