ó
ýÍSc           @   s˝   d  Z  d Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l	 j
 Z d e f d     YZ d   Z d d d	 d
 d  Z e d k rš e   n  d S(   s  
This tutorial introduces logistic regression using Theano and stochastic
gradient descent.

Logistic regression is a probabilistic, linear classifier. It is parametrized
by a weight matrix :math:`W` and a bias vector :math:`b`. Classification is
done by projecting data points onto a set of hyperplanes, the distance to
which is used to determine a class membership probability.

Mathematically, this can be written as:

.. math::
  P(Y=i|x, W,b) &= softmax_i(W x + b) \
                &= rac {e^{W_i x + b_i}} {\sum_j e^{W_j x + b_j}}


The output of the model or prediction is then done by taking the argmax of
the vector whose i'th element is P(Y=i|x).

.. math::

  y_{pred} = argmax_i P(Y=i|x,W,b)


This tutorial presents a stochastic gradient descent optimization method
suitable for large datasets, and a conjugate gradient optimization method
that is suitable for smaller datasets.


References:

    - textbooks: "Pattern Recognition and Machine Learning" -
                 Christopher M. Bishop, section 4.3.2

s   restructedtext eni˙˙˙˙Nt   LogisticRegressionc           B   s)   e  Z d  Z d   Z d   Z d   Z RS(   s5  Multi-class Logistic Regression Class

    The logistic regression is fully described by a weight matrix :math:`W`
    and bias vector :math:`b`. Classification is done by projecting data
    points onto a set of hyperplanes, the distance to which is used to
    determine a class membership probability.
    c         C   sÔ   t  j d t j | | f d t  j j d d d t  |  _ t  j d t j | f d t  j j d d d t  |  _ t	 j
 j t	 j | |  j  |  j  |  _ t	 j |  j d d |  _ |  j |  j g |  _ d	 S(
   s   Initialize the parameters of the logistic regression

        :type input: theano.tensor.TensorType
        :param input: symbolic variable that describes the input of the
                      architecture (one minibatch)

        :type n_in: int
        :param n_in: number of input units, the dimension of the space in
                     which the datapoints lie

        :type n_out: int
        :param n_out: number of output units, the dimension of the space in
                      which the labels lie

        t   valuet   dtypet   namet   Wt   borrowt   bt   axisi   N(   t   theanot   sharedt   numpyt   zerost   configt   floatXt   TrueR   R   t   Tt   nnett   softmaxt   dott   p_y_given_xt   argmaxt   y_predt   params(   t   selft   inputt   n_int   n_out(    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt   __init__;   s    +c         C   s4   t  j t  j |  j  t  j | j d  | f  S(   s  Return the mean of the negative log-likelihood of the prediction
        of this model under a given target distribution.

        .. math::

            rac{1}{|\mathcal{D}|} \mathcal{L} (	heta=\{W,b\}, \mathcal{D}) =
            rac{1}{|\mathcal{D}|} \sum_{i=0}^{|\mathcal{D}|} \log(P(Y=y^{(i)}|x^{(i)}, W,b)) \
                \ell (	heta=\{W,b\}, \mathcal{D})

        :type y: theano.tensor.TensorType
        :param y: corresponds to a vector that gives for each example the
                  correct label

        Note: we use the mean instead of the sum so that
              the learning rate is less dependent on the batch size
        i    (   R   t   meant   logR   t   aranget   shape(   R   t   y(    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt   negative_log_likelihood_   s    c         C   sw   | j  |  j j  k r< t d d t j d |  j j f   n  | j j d  rj t j t j	 |  j |   St
    d S(   sQ  Return a float representing the number of errors in the minibatch
        over the total number of examples of the minibatch ; zero one
        loss over the size of the minibatch

        :type y: theano.tensor.TensorType
        :param y: corresponds to a vector that gives for each example the
                  correct label
        s+   y should have the same shape as self.y_predR    R   t   intN(   t   ndimR   t	   TypeErrort   targett   typeR   t
   startswithR   R   t   neqt   NotImplementedError(   R   R    (    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt   errors|   s    !(   t   __name__t
   __module__t   __doc__R   R!   R*   (    (    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyR    2   s   	$	c         C   sy  t  j j |   \ } } | d k r t  j j |   r t  j j t  j j t  d d d |   } t  j j |  s | d k r | }  q n  t  j j |   rŮ | d k rŮ d d l } d } d	 | GH| j | |   n  d
 GHt j	 |  d  } t
 j |  \ } } }	 | j   t d  }
 |
 |	  \ } } |
 |  \ } } |
 |  \ } } | | f | | f | | f g } | S(   sk    Loads the dataset

    :type dataset: string
    :param dataset: the path to the dataset (here MNIST)
    t    i    s   ..t   datas   mnist.pkl.gzi˙˙˙˙Ns>   http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gzs   Downloading data from %ss   ... loading datat   rbc         S   sv   |  \ } } t  j t j | d t  j j d | } t  j t j | d t  j j d | } | t j | d  f S(   sŠ   Function that loads the dataset into shared variables

        The reason we store our dataset in shared variables is to allow
        Theano to copy it into the GPU memory (when code is run on GPU).
        Since copying data into the GPU is slow, copying a minibatch everytime
        is needed (the default behaviour if the data is not in a shared
        variable) would lead to a large decrease in performance.
        R   R   t   int32(   R   R	   R
   t   asarrayR   R   R   t   cast(   t   data_xyR   t   data_xt   data_yt   shared_xt   shared_y(    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt   shared_datasetš   s    			(   t   ost   patht   splitt   isfilet   joint   __file__t   urllibt   urlretrievet   gzipt   opent   cPicklet   loadt   closeR   (   t   datasett   data_dirt	   data_filet   new_pathR@   t   origint   ft	   train_sett	   valid_sett   test_setR9   t
   test_set_xt
   test_set_yt   valid_set_xt   valid_set_yt   train_set_xt   train_set_yt   rval(    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt	   load_data   s*    +	
g¤p=
×ŁŔ?ič  s   mnist.pkl.gziX  c   +      C   s  t  |  } | d \ } } | d \ } } | d \ }	 }
 | j d t  j d | } | j d t  j d | } |	 j d t  j d | } d GHt j   } t j d  } t j d  } t d | d	 d  d d  } | j	 |  } t
 j d | g d | j |  d i |	 | | | d | !| 6|
 | | | d | !| 6 } t
 j d | g d | j |  d i | | | | d | !| 6| | | | d | !| 6 } t j d | d | j  } t j d | d | j  } | j | j |  | f | j | j |  | f g } t
 j d | g d | d | d i | | | | d | !| 6| | | | d | !| 6 } d GHd } d } d } t | | d  } d } t j } d } t j   }  t }! d }" x`|" | k  r&|! r&|" d }" x<t |  D].}# | |#  }$ |" d | |# }% |% d | d k r	g  t |  D] }& | |&  ^ q6}' t j |'  }( d |" |# d | |( d f GH|( | k  r	|( | | k  rŹt | |% |  } n  |( } g  t |  D] }& | |&  ^ qż}) t j |)  } d |" |# d | | d f GHq	n  | |% k rńt }! PqńqńWqÇWt j   }* d | d | d f GHd |" d |" |* |  f GHt j d t j j t  d d |* |  IJd S(!   s  
    Demonstrate stochastic gradient descent optimization of a log-linear
    model

    This is demonstrated on MNIST.

    :type learning_rate: float
    :param learning_rate: learning rate used (factor for the stochastic
                          gradient)

    :type n_epochs: int
    :param n_epochs: maximal number of epochs to run the optimizer

    :type dataset: string
    :param dataset: the path of the MNIST dataset file from
                 http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz

    i    i   i   R   s   ... building the modelt   xR    R   R   i   R   i
   t   inputst   outputst   givenst   costt   wrtt   updatess   ... training the modeli  g×Łp=
×ď?g        s1   epoch %i, minibatch %i/%i, validation error %f %%g      Y@s>        epoch %i, minibatch %i/%i, test error of best model %f %%sU   Optimization complete with best validation score of %f %%,with test performance %f %%s.   The code run for %d epochs, with %f epochs/secg      đ?s   The code for file s    ran for %.1fsNi  (    RW   t	   get_valueR   R   R   t   lscalart   matrixt   ivectorR    R!   R   t   functionR*   t   gradR   R   t   mint   NoneR
   t   inft   timet   clockt   Falset   xrangeR   t   maxt   syst   stderrR:   R;   R<   R?   (+   t   learning_ratet   n_epochsRG   t
   batch_sizet   datasetsRT   RU   RR   RS   RP   RQ   t   n_train_batchest   n_valid_batchest   n_test_batchest   indexRX   R    t
   classifierR\   t
   test_modelt   validate_modelt   g_Wt   g_bR^   t   train_modelt   patiencet   patience_increaset   improvement_thresholdt   validation_frequencyt   best_paramst   best_validation_losst
   test_scoret
   start_timet   done_loopingt   epocht   minibatch_indext   minibatch_avg_costt   itert   it   validation_lossest   this_validation_losst   test_lossest   end_time(    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt   sgd_optimization_mnistŰ   s       	
"
"t   __main__(   R-   t   __docformat__RD   RB   R:   Rm   Rh   R
   R   t   theano.tensort   tensorR   t   objectR    RW   R   R+   (    (    (    sK   /net/nas-lsis-3/SABIOD/METHODES/NICOLAS/CNN2D_LIFEBIRD/CODE/logistic_sgd.pyt   <module>#   s    a	H