Tuesday, 7 October 2014

Multilayer Perceptron in Python


In this article we will look at supervised learning algorithm called Multi-Layer Perceptron (MLP) and implementation of single hidden layer MLP


A perceptron is a unit that computes a single output from multiple real-valued inputs by forming a linear combination according to its input weights and then possibly putting the output through some nonlinear function called the activation function

Below is a figure illustrating the operation of perceptron

enter image description here
figure taken from

The output of perceptron can be expressed as

x is the input vector
(W,b) are the parameters of perceptron
f is the non linear function

Multi Layer Perceptron

The MLP network consists of input,output and hidden layers.Each hidden layer consists of numerous perceptron’s which are called hidden units

Below is figure illustrating a feed forward neural network architecture for Multi Layer perceptron

enter image description here(figure taken from)
A single-hidden layer MLP contains a array of perceptrons .

The output of hidden layer of MLP can be expressed as a function


where D is the size of input vector x
L is the size of the output vector
G is activation function.

In case the activation function G is a sigmoid function then a single-layer MLP consisting of just the output layer is equivalent to a logistic classifier


Each unit of input layer corresponds to element of input vector.

Each output unit of logistic classifier generate a prediction probability that input vector belong to a specified class.

Feed Forward Neural Network

Let us first consider the most classical case of a single hidden layer neural network
The number of inputs to hidden layer is (d) and number of outputs of hidden layer are (m)
The hidden layer performs mapping of vector of dimensionality d to vector of dimensionality m.

Each unit of hidden layer of a MLP can be parameterized by a weight matirx and bias vector (W,b) and a activation function (G).The output of a hidden layer is activation function applied to linear combination of input and weight vector.

Dimensionality of weight matrix and bias vector are determined by desired number of output units.
If the number of inputs to hidden layer/dimensionality of input is M and number of outputs is N then dimensionality of weight vector in NxM and that of bias vector is Nx1.

We can consider that hidden layer consists of N hidden units ,each of which accepts a M dimensional vector and produces a single output.

The output is the affine transformation of the input layer followed by the appplication of function f(x) ,which is typically a non linear function like sigmoid of inverse tan hyperbolic function.
The vector valued function h(x) is the output of the hidden layer.


The output layer of MLP is typically Logistic regresson classifier,if probabilistic outputs are desired for classification purposes in which case the activation function is the softmax regression function.

Single Hidden Layer Multi Layer Perceptron’s

Let ,
  • hi1 denote the input vector to the i-th layer
  • hi denote the output vector of the i-th layer.
  • h0=x is vector that represents input layer
  • hn=y is output layer which produces the desired prediction output.
  • f(x) denote the activation function
Thus we denote the output of each hidden layer as


Considering sigmoid activation function,gradient of fundtion wrt arguments can be written as

The computation associated with each hidden unit (i) of the layer can be denoted as

The output layer is a Logistic regression classifier.The output is a probabilistic output denoting the confident that input belongs to the predicted class.The cost function defined for the same is defined as negative log likelihood over the training data


The idea is to maximize py=P(Y=yix) as estimator of conditional probability of the class y given that input is x.This is the cost function for training algorithm.

Back-Propagation Algorithm

The Back-Propagation Algorithm is recursive gradient algorithm used to optimize the parameters MLP wrt to defined loss function.Thus our aim is that each layer of MLP the hidden units are computed so that cost function is maximized.

Like in logistic regression we compute the gradients of weights wrt to the cost function . The gradient of the cost function wrt all the weights in various hidden layers are computed.Standard gradient based optimization is performed to obtain the parameters that will minimize the likelihood function.

The output layer determines the cost function.Since we are using Logistic regression as output layer.The cost function is the softmax function.Let L denote the cost function.

There is nothing different we do in backpropagation algorithm that any other optimization techniue.The aim is to determine how the weights and biases change in the network

LWk,i,j and Lbk,i,j.

output layer


The above expression can be considered as the error in output.When y=yi the error is (1pi) and then yyi the error in prediction is pi.

hidden layer


Thus the idea is to start computing gradients from the bottom most layer.To compute the gradients of the cost function wrt parameters at the i-th layer we need to know the gradients of cost function wrt parameters at (i+1)th layer.

We start with gradient computation at the logistic classifier level.The propagate backwards,updating the parameters at each layer

Let us consider the case of other other hidden layers


The implementation of the above equation

    def linear_gradient(self,weights,error):   
            """ The function compues gradient of likelihood function wrt output of hidden layer
            :math:`\\begin{align} \\frac{\partial L }{\partial \mathbf{h}_{k-1,j}} \\end{align}`
            weights : ndarray,shape=(n_out,n_hidden)
                      weights of next hidden layer, :math:`\\begin{align} \mathbf{W}_{k,i,j}  \\end{align}`
            error   : ndarray,shape=(n_out,)
                      backpropagated error from next layer :math:`\\begin{align} \\frac{\partial L }{\partial \mathbf{a}_{k,i}} \\end{align}`
            out : ndarray,shape=(n_hidden,)                
                  compute the backpropagated error, :math:`\\begin{align} \\frac{\partial L }{\partial \mathbf{h}_{k-1,j}} \\end{align}`
            return numpy.dot(error,weights);

The gradients computation of parameters of hidden layers is as follows


This is implemented as below ,where the input
  • x represents output gradient hk,jak,j
  • y represents input activation hk2,j 
  • w represents error Lak1,i 
      def compute_error(self,x,w,y):      
        function computes the gradient of the likelyhood function wrt to parameters  of the hidden layer for single input

        x : ndarray,shape=(n_hidden,)
            `x` represents :math:`\\begin{align} \\frac{\partial \mathbf{h}_{k,j} }{\partial \mathbf{a}_{k,j}} \end{align}`,the gradient of activation function wrt to input
        w : ndarray,shape=(n_hidden,)
            `w` represents :math:`\\begin{align} \\frac{\partial L }{\partial \mathbf{h}_{k,i}}\end{align}` the gradient of the likelyhood fuction wrt output of hidden layer
        y : ndarray,shape=(n_in,)
            `y` represents :math:`\mathbf{h}_{k-2,j}` the input hidden layer
        res : ndarray,shape=(n_in+1,n_hidden)        
              :math:`\\begin{align} \\frac{\partial L }{\partial \mathbf{W}_{k-1,i,j}}  \\text{ and } \\frac{\partial L }{\partial \mathbf{W}_{k-1,i}} \end{align}`
        #gradient of likelyhood function wrt input activation
        #gradient of likelyhood function wrt weight matrix
        #code for L1 and L2 regularization 
        if self.Regularization==2:
        if self.Regularization==1:

        #stacking the parameters and preparing for returning            
        return res.T;

      def cost_gradients(self,weights,activation,error):        
        """ function to compute the gradient of log likelyhood function wrt the parameters of the hidden layer
        averaged over all the input samples.        
        weights : numpy,shape(n_out,n_hidden),
                  weight matrix of the next layer,W_{k,i,j} 
        activation: numpy,shape=(N,n_in)
                    input to the hidden layer \mathbf{h}_{k-2,j}
        error : numpy,shape=(n_out,) 
                , error of next  layer \frac{\partial L }{\partial \mathbf{a}_{k,i}}
        gW : ndarray,shape=(n_hidden,n_in+1)
             coefficient parameter matrix of next hidden layer,
             :math:`\\begin{align} \\frac{\partial L }{\partial \mathbf{W}_{k-1,i,j}}  \\text{ and } \\frac{\partial L }{\partial \mathbf{W}_{k-1,i}} \end{align}`
        e=[ self.compute_error(a,we,b) for a,b in izip(ag,activation)]
        return gW;

Once we have the gradients and have computed the new parameters,the function update is called to updated the new parameters in the model.

This function is called by the Optimizer module that performs SGD based optimizations,all the optimization parameters like learning rate are handled by the optimizer methods.

        def update_parameters(self,params):
        """ function to updated the learn parameters to the model
        grads : ndarray,shape=(n_hidden,n_in+1)        
                coefficient parameter matrix                

Implementation Details

The class HiddenLayer encapsulates all the methods for prediction,classification,training,gradient computation and error propagation that are required

The important attributes of the HiddenLayer class are


    `out` : array-like ,shape=(n_out,)
             The output of hidden layer 
    `params` : array-like ,shape=(n_out,n_in+1)
               contains the parameters in a flattened structure
    `W,b` : array-like,shape=(n_out,n_int),shape=(n_out,1)
             weight matrix and bias vector characterizing the hidden layer
     `activation` : input activation
                    the non linear activation function that is applied after performing
                    affine transformation over input vector.
    >> hidden_layer=HiddenLayer(n_in=n_in, n_out=n_hidden_units,activation=sigmoid_stable)
    >> y=hidden_layer.compute(input);
    in the below functions docstring 
    n_hidden denotes the number of output units of present hidden layer
    n_out denotes the number of output units of next hidden layer
    n_in denotes the size of input vector to present hidden layer

    def compute(self,input):
        """function computes the output of the hidden layer for input matrix
        input   :   ndarray,shape=(n_samples,n_in)
                    :math:`h_{i-1}(x)` is the input data

        output  : ndarray ,shape=(N,n_out)
                    :math:`f(b_k + w_k^T h_{i-1}(x))` ,target values
        #performs affine transformation over input vector        
        #applies non linear activation function over computed linear transformation
        return self.output;

A class MLP encapsulates all the methods for prediction,classification,training,forward and back propagation,saving and loading models etc.

Below 3 important functions are displayed.The learn function is called at every optimizer loop.
This calls the forward and backward iteration methods and updated the parameters of each hidden layer
the forward iteration simply computes the output of network and while propagate_backward fuctions
is responsible for passing suitable inputs and weights to each hidden layer so that it can execute the backward algorithm loop

   def learn(self,update):
        """ the main function that performs learning,computing gradients and updating parameters 
            this is called by the optimizer module for each iteration
        update - python function
                 this represents the update function that performs the gradient descent iteration
        #set the training data
        #set the update function
        #execute the forward iteration loop
        #set the input for output layer
        #set the input for the output logistic regression layer
        #gradient computation and parameter updation of output layer
        #initialize the gradiients and weights for backward error propagation
        #perform the backward iteration over the hidden layers
        if self.n_hidden_layers >0:   
        return [None,None]; 

      def propagate_backward(self,error,weights,input):                 
        """ the function that executes the backward propagation loop on hidden layers
        error : numpy array,shape=(n_out,)
                average prediction error over all the input samples in output layer
                :math:`\\begin{align}\frac{\partial L  }{\partial \mathbf{a}_{k,i}} \\end{align}`

        weight : numpy array,shape=(n_out,n_hidden)        
                 parameter weight matrix of the output layer
        input : ndarray,shape=(n_samples,n_in)
                input training data

        #input matrix for the hidden layer    
        for i in range(self.n_hidden_layers):                        
            for k in range(1):
                """ computing the derivative of the parameters of the hidden layers"""
                # computing the gradient of likelyhood function wrt the parameters of the hidden layer 
                #update the parameter of hidden layer
                """ update the parameters """
            #set the weights ,inputs and error required for the back propagation algorithm
            #for the next layer

   def propagate_forward(self,input):
       """the function that performs forward iteration to compute the output
       input : ndarray,shape=(n_samples,n_in)
               input training data

Selecting the parameters of the model

As mentioned earlier that MLP consits of input,hidden and output layers.There is not fixed rule to determine the number of hidden units.The parameters are application specific and best parameters are often arrived at by emperical testing process.Less number of hidden units leads to increased generalization and training error while having a large number of training units leads to issues of with training of large number of parameters and significantly large training time.

Issues with MLP

One of the issues observed in MLP training is the slow nature of learning.The below figure illustrates the nature of learning process when a small learning parameter or improper regularization constant is chosen.Various adaptive methods can be implemented which can improve the performance ,but slow convergence and large learning times is an issue with Neural networks based learning algorithms.
enter image description here


The important files related to MLP are

The files used in the current article can be downloaded from below link
- Github Release

The dataset and model file can be found under the models and data repository
  • MLP.pyvision - model file
  • mnist.pkl.gz - data file

Make suitable changes to the path in MLP.py file before running the code.