Designing A Custom Neural Network In MATLAB

The MATLAB Neural Network toolbox ships with numerous predefined and canonical neural nets, however sometimes you may need to create a custom net with just the right connections, biases and hidden layers to suite your particular problem domain. To achieve this goal we can use the matlab network object. The  network object allows granular design of neural networks by exposing all properties of the net that we are designing. The preceding code demonstrates how to build a simple neural to learn the truth table for Logical AND.

First lets look at the Logical AND truth table:

p q p ∧ q
T T T
T F F
F T F
F F F

Open a new edit window in MATLAB and enter the following code:

    1. This creates an empty network object and assigns it to the net variable, sets up the number of inputs and uses cell array syntax to index into its properties.
      %% Design Custom Neural Network
      net = network;                                  % create network
      net.numInputs = 2;                              % set number of inputs
      net.inputs{1}.size = 1;                         % assign 2 to input size
      net.inputs{2}.size = 1;
      net.numLayers = 1;                              % add 1 layer to network
      net.layers{1}.size = 1;                         % assign number of neurons in layer
      net.inputConnect(1) = 1;                        % connet input to layer 1
      net.inputConnect(2) = 1;
      net.biasConnect(1) = 1;                         % connect bias to layer 1
      net.biases{1}.learnFcn = 'learnp';              % set bias learning function
      net.biases{1}.initFcn = 'initzero';             % set bias init function
      
      net.outputConnect(1) = 1;
      
      net.layers{1}.transferFcn = 'hardlim';          % set layer transfer function [hard limit]
      net.inputWeights{1}.initFcn = 'initzero';       % set input wieghts init function
      net.inputWeights{1}.learnFcn = 'learnp';        % set input weight learning function
      net.inputWeights{2}.learnFcn = 'learnp';
      net.inputWeights{2}.initFcn = 'initzero';
      
      net.initFcn = 'initlay';                        % set network init function
      net.trainFcn = 'trainc';                        % set network training function
      net.performFcn = 'mae';                         % set network perf evaluation function
      
      view(net)
      net = train(net,[0 0 1 1;0 1 0 1],[0 0 0 1]) ;  % train network
      
    2. Custom Network Diagram:
    3. Test Network
      In the command window type

      net([1;1])
      

      This should output a 1 to the command window indicating 1 AND 1 = 1

Advertisements