
\c           @   s  d  Z  d d l Z d d l m Z m Z d d l m Z d d l Z d d l	 m
 Z
 m Z m Z d d l	 m Z d d	 l m Z m Z m Z d d
 l m Z m Z d d l m Z d d l m Z d d l m Z d d l m Z m Z d d l m Z d d l m Z m  Z  m! Z! d d l" m# Z# d d l$ m% Z% d d l& m' Z' d d l( m) Z) m* Z* d d l( m+ Z+ d d g Z, d   Z- d e j. e e
  f d     YZ/ d e/ e f d     YZ0 d e/ e f d     YZ1 d S(   s   Multi-layer Perceptron
iN(   t   ABCMetat   abstractmethod(   t   fmin_l_bfgs_bi   (   t   BaseEstimatort   ClassifierMixint   RegressorMixin(   t   is_classifieri   (   t   ACTIVATIONSt   DERIVATIVESt   LOSS_FUNCTIONS(   t   SGDOptimizert   AdamOptimizer(   t   train_test_split(   t   six(   t   LabelBinarizer(   t   gen_batchest   check_random_state(   t   shuffle(   t   check_arrayt	   check_X_yt   column_or_1d(   t   ConvergenceWarning(   t   safe_sparse_dot(   t   check_is_fitted(   t   _check_partial_fit_first_callt   unique_labels(   t   type_of_targett   sgdt   adamc         C   s*   t  j g  |  | D] } | j   ^ q  S(   s)   Pack the parameters into a single vector.(   t   npt   hstackt   ravel(   t   coefs_t   intercepts_t   l(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _pack#   s    t   BaseMultilayerPerceptronc           B   s   e  Z d  Z e d    Z d   Z d   Z d   Z d   Z d   Z	 d   Z
 d   Z e d	  Z d
   Z d   Z d   Z d   Z d   Z e d    Z d   Z d   Z RS(   s   Base class for MLP classification and regression.

    Warning: This class should not be used directly.
    Use derived classes instead.

    .. versionadded:: 0.18
    c         C   s   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _ |
 |  _ | |  _	 | |  _
 | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ d  S(   N(   t
   activationt   solvert   alphat
   batch_sizet   learning_ratet   learning_rate_initt   power_tt   max_itert   losst   hidden_layer_sizesR   t   random_statet   tolt   verboset
   warm_startt   momentumt   nesterovs_momentumt   early_stoppingt   validation_fractiont   beta_1t   beta_2t   epsilont   n_iter_no_change(   t   selfR.   R%   R&   R'   R(   R)   R*   R+   R,   R-   R   R/   R0   R1   R2   R3   R4   R5   R6   R7   R8   R9   R:   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   __init__1   s.    																						c         C   s   xx t  |  j d  D]c } |  j | \ } } } t j | | | !|  |  j | <|  j | \ } } | | | !|  j | <q Wd S(   s?   Extract the coefficients and intercepts from packed_parameters.i   N(   t   ranget	   n_layers_t   _coef_indptrR   t   reshapeR    t   _intercept_indptrR!   (   R;   t   packed_parameterst   it   startt   endt   shape(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _unpackP   s
     c         C   s   t  |  j } x t |  j d  D]y } t | | |  j |  | | d <| | d c |  j | 7<| d |  j d k r! | | | d  | | d <q! q! Wt  |  j } | | | d  | | d <| S(   s,  Perform a forward pass on the network by computing the values
        of the neurons in the hidden layers and the output layer.

        Parameters
        ----------
        activations : list, length = n_layers - 1
            The ith element of the list holds the values of the ith layer.
        i   (   R   R%   R=   R>   R   R    R!   t   out_activation_(   R;   t   activationst   hidden_activationRC   t   output_activation(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _forward_passY   s    	
#c         C   sp   t  | | j | |  | | <| | c |  j |  j | 7<| | c | :<t j | | d  | | <| | f S(   s   Compute the gradient of loss with respect to coefs and intercept for
        specified layer.

        This function does backpropagation for the specified one layer.
        i    (   R   t   TR'   R    R   t   mean(   R;   t   layert	   n_samplesRI   t   deltast
   coef_gradst   intercept_grads(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _compute_loss_grads   s    c   
      C   s\   |  j  |  |  j | | | | | |  \ } } } |  j d 7_ t | |  }	 | |	 f S(   sT  Compute the MLP loss function and its corresponding derivatives
        with respect to the different parameters given in the initialization.

        Returned gradients are packed in a single vector so it can be used
        in lbfgs

        Parameters
        ----------
        packed_coef_inter : array-like
            A vector comprising the flattened coefficients and intercepts.

        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        y : array-like, shape (n_samples,)
            The target values.

        activations : list, length = n_layers - 1
            The ith element of the list holds the values of the ith layer.

        deltas : list, length = n_layers - 1
            The ith element of the list holds the difference between the
            activations of the i + 1 layer and the backpropagated error.
            More specifically, deltas are gradients of loss with respect to z
            in each layer, where z = wx + b is the value of a particular layer
            before passing through the activation function

        coef_grads : list, length = n_layers - 1
            The ith element contains the amount of change used to update the
            coefficient parameters of the ith layer in an iteration.

        intercept_grads : list, length = n_layers - 1
            The ith element contains the amount of change used to update the
            intercept parameters of the ith layer in an iteration.

        Returns
        -------
        loss : float
        grad : array-like, shape (number of nodes of all layers,)
        i   (   RG   t	   _backpropt   n_iter_R#   (
   R;   t   packed_coef_intert   Xt   yRI   RQ   RR   RS   R-   t   grad(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _loss_grad_lbfgs   s    *!c         C   s  | j  d } |  j |  } |  j } | d k rI |  j d k rI d } n  t | | | d  }	 t j t j g  |  j D]$ }
 t j	 |
 j
   |
 j
    ^ qv   } |	 d |  j | | 7}	 |  j d } | d | | | <|  j | | | | | |  \ } } x t |  j d d d  D]y } t | | |  j | j  | | d <t |  j } | | | | | d  |  j | d | | | | |  \ } } qW|	 | | f S(	   s  Compute the MLP loss function and its corresponding derivatives
        with respect to each parameter: weights and bias vectors.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        y : array-like, shape (n_samples,)
            The target values.

        activations : list, length = n_layers - 1
             The ith element of the list holds the values of the ith layer.

        deltas : list, length = n_layers - 1
            The ith element of the list holds the difference between the
            activations of the i + 1 layer and the backpropagated error.
            More specifically, deltas are gradients of loss with respect to z
            in each layer, where z = wx + b is the value of a particular layer
            before passing through the activation function

        coef_grads : list, length = n_layers - 1
            The ith element contains the amount of change used to update the
            coefficient parameters of the ith layer in an iteration.

        intercept_grads : list, length = n_layers - 1
            The ith element contains the amount of change used to update the
            intercept parameters of the ith layer in an iteration.

        Returns
        -------
        loss : float
        coef_grads : list, length = n_layers - 1
        intercept_grads : list, length = n_layers - 1
        i    t   log_losst   logistict   binary_log_lossig      ?i   i   (   RF   RL   R-   RH   R	   R   t   sumt   arrayR    t   dotR   R'   R>   RT   R=   R   RM   R   R%   (   R;   RX   RY   RI   RQ   RR   RS   RP   t   loss_func_nameR-   t   st   valuest   lastRC   t   inplace_derivative(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyRU      s*    %		@ %c         C   s:  d |  _  d |  _ | j d |  _ t |  |  _ t |   sI d |  _ n' |  j j	 d k rg d |  _ n	 d |  _ g  |  _
 g  |  _ x_ t |  j d  D]J } |  j | | | | d  \ } } |  j
 j |  |  j j |  q W|  j t k r6g  |  _ d |  _ |  j r'g  |  _ t j |  _ q6t j |  _ n  d  S(   Ni    i   t   identityt
   multiclasst   softmaxR]   (   RV   t   t_RF   t
   n_outputs_t   lenR>   R   RH   t   _label_binarizert   y_type_R    R!   R=   t
   _init_coeft   appendR&   t   _STOCHASTIC_SOLVERSt   loss_curve_t   _no_improvement_countR5   t   validation_scores_R   t   inft   best_validation_score_t
   best_loss_(   R;   RY   t   layer_unitsRC   t	   coef_initt   intercept_init(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _initialize  s.    									c         C   sw   d } |  j  d k r d } n  t j | | |  } |  j j | | | | f  } |  j j | | |  } | | f S(   Ng      @R]   g       @(   R%   R   t   sqrtt   _random_statet   uniform(   R;   t   fan_int   fan_outt   factort
   init_boundRy   Rz   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyRo   (  s    		c      	      s  |  j  } t | d  s$ | g } n  t |  } |  j   t j t j |  d k  rk t d |   n  |  j | | |  \ } } | j	 \ } } | j
 d k r | j d  } n  | j	 d |  _ | g | |  j g } t |  j  |  _ t |  d  s|  j r#| r#|  j | |  n  |  j d k r;|   ng |  j d k r\t d	 |    nF |  j d k  sz|  j | k rt j d
  n  t j |  j d |    | g } | j   f d   | d D  g  | D] }	 t j |	  ^ q}
 g  t | d  | d  D]! \ } } t j | | f  ^ q} g  | d D] } t j |  ^ q8} |  j t k r|  j | | | |
 | | | |  n1 |  j d k r|  j | | | |
 | | |  n  |  S(   Nt   __iter__i    s'   hidden_layer_sizes must be > 0, got %s.i   iR    t   lbfgst   autoi   sR   Got `batch_size` less than 1 or larger than sample size. It is going to be clippedc         3   s$   |  ] } t  j   | f  Vq d  S(   N(   R   t   empty(   t   .0t	   n_fan_out(   R(   (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pys	   <genexpr>e  s   (   ii   (   R.   t   hasattrt   listt   _validate_hyperparametersR   t   anyR`   t
   ValueErrort   _validate_inputRF   t   ndimR@   Rk   R   R/   R}   R2   R{   R&   R(   t   mint   warningst   warnt   clipt   extendt
   empty_liket   zipR   Rq   t   _fit_stochastict
   _fit_lbfgs(   R;   RX   RY   t   incrementalR.   RP   t
   n_featuresRx   RI   t   a_layerRQ   t	   n_fan_in_t
   n_fan_out_RR   RS   (    (   R(   sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _fit7  sT    	

		"
2#c         C   s  t  |  j t  s( t d |  j   n  |  j d k rM t d |  j   n  |  j d k  rr t d |  j   n  |  j d k r |  j d k r t d	 |  j   n  |  j d
 k s |  j d k  r t d |  j   n  t  |  j	 t  st d |  j	   n  t  |  j
 t  s*t d |  j
   n  |  j d k  sH|  j d
 k r^t d |  j   n  |  j d k  s||  j d
 k rt d |  j   n  |  j d k  s|  j d
 k rt d |  j   n  |  j d k rt d |  j   n  |  j d k rt d |  j   n  d } |  j | k rAt d |  j | f   n  |  j d k rft d |  j   n  t d g } |  j | k rt d |  j d j |  f   n  d  S(   Ns-   shuffle must be either True or False, got %s.i    s   max_iter must be > 0, got %s.g        s   alpha must be >= 0, got %s.t   constantt
   invscalingt   adaptives'   learning_rate_init must be > 0, got %s.i   s&   momentum must be >= 0 and <= 1, got %ss8   nesterovs_momentum must be either True or False, got %s.s4   early_stopping must be either True or False, got %s.s0   validation_fraction must be >= 0 and < 1, got %ss#   beta_1 must be >= 0 and < 1, got %ss#   beta_2 must be >= 0 and < 1, got %ss   epsilon must be > 0, got %s.s%   n_iter_no_change must be > 0, got %s.Rg   R]   t   tanht   relusC   The activation '%s' is not supported. Supported activations are %s.s#   learning rate %s is not supported. R   s4   The solver %s is not supported.  Expected one of: %ss   , (   R   R   R   (   Rg   R]   R   R   (   R   R   R   (   t
   isinstanceR   t   boolR   R,   R'   R)   R*   R3   R4   R5   R6   R7   R8   R9   R:   R%   Rq   R&   t   join(   R;   t   supported_activationst   supported_solvers(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR   {  s\    c         C   su  g  |  _  g  |  _ d } xg t |  j d  D]R }	 | |	 | |	 d }
 } | |
 | } |  j  j | | |
 | f f  | } q, WxI t |  j d  D]4 }	 | | |	 d } |  j j | | f  | } q Wt |  j |  j  } |  j t	 k s|  j d k r
d } n d } t
 d | d |  j d |  j d | d |  j d	 | | | | | | f  \ } |  _ } |  j |  d  S(
   Ni    i   it   x0t   funct   maxfunt   iprintt   pgtolt   args(   R?   RA   R=   R>   Rp   R#   R    R!   R1   t   TrueR   R[   R,   R0   t   loss_RG   (   R;   RX   RY   RI   RQ   RR   RS   Rx   RD   RC   t   n_fan_inR   RE   RW   R   t   optimal_parameterst   d(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s2    		

					'c	      	   C   s  | s t  |  d  r |  j |  j }	 |  j d k rf t |	 |  j |  j |  j |  j |  j	  |  _
 q |  j d k r t |	 |  j |  j |  j |  j  |  _
 q n  |  j o | }
 |
 r	t | | d |  j d |  j \ } } } } t |   r|  j j |  } qn d  } d  } | j d } |  j d k rCt d |  } n t j |  j d	 |  } yxt |  j  D]} t | | d |  j \ } } d
 } x t | |  D]u } | | | d <|  j  | | | | | | | |  \ } } } | | | j! | j" 7} | | } |  j
 j# |  qW|  j$ d	 7_$ | | j d |  _% |  j& | 7_& |  j' j( |  j%  |  j) rd |  j$ |  j% f GHn  |  j* |
 | |  |  j
 j+ |  j&  |  j, |  j- k r"|
 rd |  j. |  j- f } n d |  j. |  j- f } |  j
 j/ | |  j)  } | rPq"d |  _, n  | r,Pn  |  j$ |  j k rnt0 j1 d |  j t2  qnqnWWn t3 k
 r}t0 j1 d  n X|
 r|  j4 |  _ |  j5 |  _ n  d  S(   Nt
   _optimizerR   R   R/   t	   test_sizei    R   i   i   g        s   Iteration %d, loss = %.8fsL   Validation score did not improve more than tol=%f for %d consecutive epochs.sI   Training loss did not improve more than tol=%f for %d consecutive epochs.s`   Stochastic Optimizer: Maximum iterations (%d) reached and the optimization hasn't converged yet.s   Training interrupted by user.(6   R   R    R!   R&   R
   R*   R)   R3   R4   R+   R   R   R7   R8   R9   R5   R   R}   R6   R   Rm   t   inverse_transformt   NoneRF   R(   R   R   R   R=   R,   R   R   RU   t   stopRD   t   update_paramsRV   R   Rj   Rr   Rp   R1   t   _update_no_improvement_countt   iteration_endsRs   R:   R0   t   trigger_stoppingR   R   R   t   KeyboardInterruptt   _best_coefst   _best_intercepts(   R;   RX   RY   RI   RQ   RR   RS   Rx   R   t   paramsR5   t   X_valt   y_valRP   R(   t   itt   accumulated_losst   batch_slicet
   batch_losst   gradst   msgt   is_stopping(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s    
			c         C   sI  | r |  j  j |  j | |   |  j r> d |  j  d GHn  |  j  d } | |  j |  j k  rs |  j d 7_ n	 d |  _ | |  j k rE| |  _ g  |  j D] } | j   ^ q |  _	 g  |  j
 D] } | j   ^ q |  _ qEna |  j d |  j |  j k r|  j d 7_ n	 d |  _ |  j d |  j k  rE|  j d |  _ n  d  S(   Ns   Validation score: %fii   i    (   Rt   Rp   t   scoreR1   Rv   R0   Rs   R    t   copyR   R!   R   Rr   Rw   (   R;   R5   R   R   t   last_valid_scoret   cRC   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR   ;  s&    				%(	c         C   s   |  j  | | d t S(   s  Fit the model to data matrix X and target(s) y.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            The input data.

        y : array-like, shape (n_samples,) or (n_samples, n_outputs)
            The target values (class labels in classification, real numbers in
            regression).

        Returns
        -------
        self : returns a trained MLP model.
        R   (   R   t   False(   R;   RX   RY   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   fitZ  s    c         C   s,   |  j  t k r% t d |  j    n  |  j S(   sh  Update the model with a single iteration over the given data.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        y : array-like, shape (n_samples,)
            The target values.

        Returns
        -------
        self : returns a trained MLP model.
        sN   partial_fit is only available for stochastic optimizers. %s is not stochastic.(   R&   Rq   t   AttributeErrort   _partial_fit(   R;   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   partial_fitl  s    c         C   s   |  j  | | d t S(   NR   (   R   R   (   R;   RX   RY   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s    c         C   s   t  | d d d d g } |  j } t | d  s? | g } n  t |  } | j d g | |  j g } | g } xF t |  j d  D]1 } | j t	 j
 | j d | | d f   q W|  j |  | d } | S(	   sk  Predict using the trained model

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        Returns
        -------
        y_pred : array-like, shape (n_samples,) or (n_samples, n_outputs)
            The decision function of the samples for each class in the model.
        t   accept_sparset   csrt   csct   cooR   i   i    i(   R   R.   R   R   RF   Rk   R=   R>   Rp   R   R   RL   (   R;   RX   R.   Rx   RI   RC   t   y_pred(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   _predict  s    		
(   t   __name__t
   __module__t   __doc__R   R<   RG   RL   RT   R[   RU   R{   Ro   R   R   R   R   R   R   R   t   propertyR   R   R   (    (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR$   (   s$   					1	M	'	D	3	(	e			t   MLPClassifierc           B   s   e  Z d  Z d d d d d d d d d	 e d d e e d
 e e d d
 d d d d  Z d   Z d   Z d   Z	 e
 d    Z d d  Z d   Z d   Z RS(   s  Multi-layer Perceptron classifier.

    This model optimizes the log-loss function using LBFGS or stochastic
    gradient descent.

    .. versionadded:: 0.18

    Parameters
    ----------
    hidden_layer_sizes : tuple, length = n_layers - 2, default (100,)
        The ith element represents the number of neurons in the ith
        hidden layer.

    activation : {'identity', 'logistic', 'tanh', 'relu'}, default 'relu'
        Activation function for the hidden layer.

        - 'identity', no-op activation, useful to implement linear bottleneck,
          returns f(x) = x

        - 'logistic', the logistic sigmoid function,
          returns f(x) = 1 / (1 + exp(-x)).

        - 'tanh', the hyperbolic tan function,
          returns f(x) = tanh(x).

        - 'relu', the rectified linear unit function,
          returns f(x) = max(0, x)

    solver : {'lbfgs', 'sgd', 'adam'}, default 'adam'
        The solver for weight optimization.

        - 'lbfgs' is an optimizer in the family of quasi-Newton methods.

        - 'sgd' refers to stochastic gradient descent.

        - 'adam' refers to a stochastic gradient-based optimizer proposed
          by Kingma, Diederik, and Jimmy Ba

        Note: The default solver 'adam' works pretty well on relatively
        large datasets (with thousands of training samples or more) in terms of
        both training time and validation score.
        For small datasets, however, 'lbfgs' can converge faster and perform
        better.

    alpha : float, optional, default 0.0001
        L2 penalty (regularization term) parameter.

    batch_size : int, optional, default 'auto'
        Size of minibatches for stochastic optimizers.
        If the solver is 'lbfgs', the classifier will not use minibatch.
        When set to "auto", `batch_size=min(200, n_samples)`

    learning_rate : {'constant', 'invscaling', 'adaptive'}, default 'constant'
        Learning rate schedule for weight updates.

        - 'constant' is a constant learning rate given by
          'learning_rate_init'.

        - 'invscaling' gradually decreases the learning rate at each
          time step 't' using an inverse scaling exponent of 'power_t'.
          effective_learning_rate = learning_rate_init / pow(t, power_t)

        - 'adaptive' keeps the learning rate constant to
          'learning_rate_init' as long as training loss keeps decreasing.
          Each time two consecutive epochs fail to decrease training loss by at
          least tol, or fail to increase validation score by at least tol if
          'early_stopping' is on, the current learning rate is divided by 5.

        Only used when ``solver='sgd'``.

    learning_rate_init : double, optional, default 0.001
        The initial learning rate used. It controls the step-size
        in updating the weights. Only used when solver='sgd' or 'adam'.

    power_t : double, optional, default 0.5
        The exponent for inverse scaling learning rate.
        It is used in updating effective learning rate when the learning_rate
        is set to 'invscaling'. Only used when solver='sgd'.

    max_iter : int, optional, default 200
        Maximum number of iterations. The solver iterates until convergence
        (determined by 'tol') or this number of iterations. For stochastic
        solvers ('sgd', 'adam'), note that this determines the number of epochs
        (how many times each data point will be used), not the number of
        gradient steps.

    shuffle : bool, optional, default True
        Whether to shuffle samples in each iteration. Only used when
        solver='sgd' or 'adam'.

    random_state : int, RandomState instance or None, optional, default None
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    tol : float, optional, default 1e-4
        Tolerance for the optimization. When the loss or score is not improving
        by at least ``tol`` for ``n_iter_no_change`` consecutive iterations,
        unless ``learning_rate`` is set to 'adaptive', convergence is
        considered to be reached and training stops.

    verbose : bool, optional, default False
        Whether to print progress messages to stdout.

    warm_start : bool, optional, default False
        When set to True, reuse the solution of the previous
        call to fit as initialization, otherwise, just erase the
        previous solution. See :term:`the Glossary <warm_start>`.

    momentum : float, default 0.9
        Momentum for gradient descent update. Should be between 0 and 1. Only
        used when solver='sgd'.

    nesterovs_momentum : boolean, default True
        Whether to use Nesterov's momentum. Only used when solver='sgd' and
        momentum > 0.

    early_stopping : bool, default False
        Whether to use early stopping to terminate training when validation
        score is not improving. If set to true, it will automatically set
        aside 10% of training data as validation and terminate training when
        validation score is not improving by at least tol for
        ``n_iter_no_change`` consecutive epochs.
        Only effective when solver='sgd' or 'adam'

    validation_fraction : float, optional, default 0.1
        The proportion of training data to set aside as validation set for
        early stopping. Must be between 0 and 1.
        Only used if early_stopping is True

    beta_1 : float, optional, default 0.9
        Exponential decay rate for estimates of first moment vector in adam,
        should be in [0, 1). Only used when solver='adam'

    beta_2 : float, optional, default 0.999
        Exponential decay rate for estimates of second moment vector in adam,
        should be in [0, 1). Only used when solver='adam'

    epsilon : float, optional, default 1e-8
        Value for numerical stability in adam. Only used when solver='adam'

    n_iter_no_change : int, optional, default 10
        Maximum number of epochs to not meet ``tol`` improvement.
        Only effective when solver='sgd' or 'adam'

        .. versionadded:: 0.20

    Attributes
    ----------
    classes_ : array or list of array of shape (n_classes,)
        Class labels for each output.

    loss_ : float
        The current loss computed with the loss function.

    coefs_ : list, length n_layers - 1
        The ith element in the list represents the weight matrix corresponding
        to layer i.

    intercepts_ : list, length n_layers - 1
        The ith element in the list represents the bias vector corresponding to
        layer i + 1.

    n_iter_ : int,
        The number of iterations the solver has ran.

    n_layers_ : int
        Number of layers.

    n_outputs_ : int
        Number of outputs.

    out_activation_ : string
        Name of the output activation function.

    Notes
    -----
    MLPClassifier trains iteratively since at each time step
    the partial derivatives of the loss function with respect to the model
    parameters are computed to update the parameters.

    It can also have a regularization term added to the loss function
    that shrinks model parameters to prevent overfitting.

    This implementation works with data represented as dense numpy arrays or
    sparse scipy arrays of floating point values.

    References
    ----------
    Hinton, Geoffrey E.
        "Connectionist learning procedures." Artificial intelligence 40.1
        (1989): 185-234.

    Glorot, Xavier, and Yoshua Bengio. "Understanding the difficulty of
        training deep feedforward neural networks." International Conference
        on Artificial Intelligence and Statistics. 2010.

    He, Kaiming, et al. "Delving deep into rectifiers: Surpassing human-level
        performance on imagenet classification." arXiv preprint
        arXiv:1502.01852 (2015).

    Kingma, Diederik, and Jimmy Ba. "Adam: A method for stochastic
        optimization." arXiv preprint arXiv:1412.6980 (2014).
    id   R   R   g-C6?R   R   gMbP?g      ?i   g?g?g+?g:0yE>i
   c      /   C   s   t  t |   } | j d | d | d | d | d | d | d | d | d	 |	 d
 d d |
 d | d | d | d | d | d | d | d | d | d | d | d |  d  S(   NR.   R%   R&   R'   R(   R)   R*   R+   R,   R-   R\   R   R/   R0   R1   R2   R3   R4   R5   R6   R7   R8   R9   R:   (   t   superR   R<   (   R;   R.   R%   R&   R'   R(   R)   R*   R+   R,   R   R/   R0   R1   R2   R3   R4   R5   R6   R7   R8   R9   R:   t   sup(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR<   x  s    
c         C   sI  t  | | d d d d g d t \ } } | j d k ra | j d d k ra t | d t } n  | s t   |  _ |  j j |  |  j j |  _ n |  j	 r t
 |  } t |  t |  j  k r-t d	 |  j | f   q-nI t
 |  } t t j | |  j d
 t  r-t d |  j | f   n  |  j j |  } | | f S(   NR   R   R   R   t   multi_outputi   i   R   sx   warm_start can only be used where `y` has the same classes as in the previous call to fit. Previously got %s, `y` has %st   assume_uniquesK   `y` has classes not in `self.classes_`. `self.classes_` has %s. 'y' has %s.(   R   R   R   RF   R   R   Rm   R   t   classes_R2   R   t   setR   Rl   R   t	   setdiff1dt	   transform(   R;   RX   RY   R   t   classes(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s&    "	!c         C   sJ   t  |  d  |  j |  } |  j d k r: | j   } n  |  j j |  S(   sO  Predict using the multi-layer perceptron classifier

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        Returns
        -------
        y : array-like, shape (n_samples,) or (n_samples, n_classes)
            The predicted classes.
        R    i   (   R   R   Rk   R   Rm   R   (   R;   RX   R   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   predict  s
    c         C   s(   |  j  | | d |  j o$ t |  d  S(   s  Fit the model to data matrix X and target(s) y.

        Parameters
        ----------
        X : array-like or sparse matrix, shape (n_samples, n_features)
            The input data.

        y : array-like, shape (n_samples,) or (n_samples, n_outputs)
            The target values (class labels in classification, real numbers in
            regression).

        Returns
        -------
        self : returns a trained MLP model.
        R   R   (   R   R2   R   (   R;   RX   RY   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s    c         C   s,   |  j  t k r% t d |  j    n  |  j S(   s  Update the model with a single iteration over the given data.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        y : array-like, shape (n_samples,)
            The target values.

        classes : array, shape (n_classes), default None
            Classes across all calls to partial_fit.
            Can be obtained via `np.unique(y_all)`, where y_all is the
            target vector of the entire dataset.
            This argument is required for the first call to partial_fit
            and can be omitted in the subsequent calls.
            Note that y doesn't need to contain all labels in `classes`.

        Returns
        -------
        self : returns a trained MLP model.
        sL   partial_fit is only available for stochastic optimizer. %s is not stochastic(   R&   Rq   R   R   (   R;   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s    c         C   ss   t  |  |  rV t   |  _ t |  j d  rC |  j j |  qV |  j j |  n  t t |   j | |  |  S(   Nt
   multilabel(	   R   R   Rm   R   t
   startswithR   R   R   R   (   R;   RX   RY   R   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s    c         C   s"   |  j  |  } t j | d | S(   s  Return the log of probability estimates.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            The input data.

        Returns
        -------
        log_y_prob : array-like, shape (n_samples, n_classes)
            The predicted log-probability of the sample for each class
            in the model, where classes are ordered as they are in
            `self.classes_`. Equivalent to log(predict_proba(X))
        t   out(   t   predict_probaR   t   log(   R;   RX   t   y_prob(    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   predict_log_proba  s    c         C   sk   t  |  d  |  j |  } |  j d k r: | j   } n  | j d k rc t j d | | g  j S| Sd S(   s  Probability estimates.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        Returns
        -------
        y_prob : array-like, shape (n_samples, n_classes)
            The predicted probability of the sample for each class in the
            model, where classes are ordered as they are in `self.classes_`.
        R    i   N(   R   R   Rk   R   R   R   t   vstackRM   (   R;   RX   R   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s    (   id   N(   R   R   R   R   R   R   R<   R   R   R   R   R   R   R   R   (    (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s"   								t   MLPRegressorc           B   sk   e  Z d  Z d d d d d d d d d	 e d d e e d
 e e d d
 d d d d  Z d   Z d   Z RS(   sZ  Multi-layer Perceptron regressor.

    This model optimizes the squared-loss using LBFGS or stochastic gradient
    descent.

    .. versionadded:: 0.18

    Parameters
    ----------
    hidden_layer_sizes : tuple, length = n_layers - 2, default (100,)
        The ith element represents the number of neurons in the ith
        hidden layer.

    activation : {'identity', 'logistic', 'tanh', 'relu'}, default 'relu'
        Activation function for the hidden layer.

        - 'identity', no-op activation, useful to implement linear bottleneck,
          returns f(x) = x

        - 'logistic', the logistic sigmoid function,
          returns f(x) = 1 / (1 + exp(-x)).

        - 'tanh', the hyperbolic tan function,
          returns f(x) = tanh(x).

        - 'relu', the rectified linear unit function,
          returns f(x) = max(0, x)

    solver : {'lbfgs', 'sgd', 'adam'}, default 'adam'
        The solver for weight optimization.

        - 'lbfgs' is an optimizer in the family of quasi-Newton methods.

        - 'sgd' refers to stochastic gradient descent.

        - 'adam' refers to a stochastic gradient-based optimizer proposed by
          Kingma, Diederik, and Jimmy Ba

        Note: The default solver 'adam' works pretty well on relatively
        large datasets (with thousands of training samples or more) in terms of
        both training time and validation score.
        For small datasets, however, 'lbfgs' can converge faster and perform
        better.

    alpha : float, optional, default 0.0001
        L2 penalty (regularization term) parameter.

    batch_size : int, optional, default 'auto'
        Size of minibatches for stochastic optimizers.
        If the solver is 'lbfgs', the classifier will not use minibatch.
        When set to "auto", `batch_size=min(200, n_samples)`

    learning_rate : {'constant', 'invscaling', 'adaptive'}, default 'constant'
        Learning rate schedule for weight updates.

        - 'constant' is a constant learning rate given by
          'learning_rate_init'.

        - 'invscaling' gradually decreases the learning rate ``learning_rate_``
          at each time step 't' using an inverse scaling exponent of 'power_t'.
          effective_learning_rate = learning_rate_init / pow(t, power_t)

        - 'adaptive' keeps the learning rate constant to
          'learning_rate_init' as long as training loss keeps decreasing.
          Each time two consecutive epochs fail to decrease training loss by at
          least tol, or fail to increase validation score by at least tol if
          'early_stopping' is on, the current learning rate is divided by 5.

        Only used when solver='sgd'.

    learning_rate_init : double, optional, default 0.001
        The initial learning rate used. It controls the step-size
        in updating the weights. Only used when solver='sgd' or 'adam'.

    power_t : double, optional, default 0.5
        The exponent for inverse scaling learning rate.
        It is used in updating effective learning rate when the learning_rate
        is set to 'invscaling'. Only used when solver='sgd'.

    max_iter : int, optional, default 200
        Maximum number of iterations. The solver iterates until convergence
        (determined by 'tol') or this number of iterations. For stochastic
        solvers ('sgd', 'adam'), note that this determines the number of epochs
        (how many times each data point will be used), not the number of
        gradient steps.

    shuffle : bool, optional, default True
        Whether to shuffle samples in each iteration. Only used when
        solver='sgd' or 'adam'.

    random_state : int, RandomState instance or None, optional, default None
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    tol : float, optional, default 1e-4
        Tolerance for the optimization. When the loss or score is not improving
        by at least ``tol`` for ``n_iter_no_change`` consecutive iterations,
        unless ``learning_rate`` is set to 'adaptive', convergence is
        considered to be reached and training stops.

    verbose : bool, optional, default False
        Whether to print progress messages to stdout.

    warm_start : bool, optional, default False
        When set to True, reuse the solution of the previous
        call to fit as initialization, otherwise, just erase the
        previous solution. See :term:`the Glossary <warm_start>`.

    momentum : float, default 0.9
        Momentum for gradient descent update.  Should be between 0 and 1. Only
        used when solver='sgd'.

    nesterovs_momentum : boolean, default True
        Whether to use Nesterov's momentum. Only used when solver='sgd' and
        momentum > 0.

    early_stopping : bool, default False
        Whether to use early stopping to terminate training when validation
        score is not improving. If set to true, it will automatically set
        aside 10% of training data as validation and terminate training when
        validation score is not improving by at least ``tol`` for
        ``n_iter_no_change`` consecutive epochs.
        Only effective when solver='sgd' or 'adam'

    validation_fraction : float, optional, default 0.1
        The proportion of training data to set aside as validation set for
        early stopping. Must be between 0 and 1.
        Only used if early_stopping is True

    beta_1 : float, optional, default 0.9
        Exponential decay rate for estimates of first moment vector in adam,
        should be in [0, 1). Only used when solver='adam'

    beta_2 : float, optional, default 0.999
        Exponential decay rate for estimates of second moment vector in adam,
        should be in [0, 1). Only used when solver='adam'

    epsilon : float, optional, default 1e-8
        Value for numerical stability in adam. Only used when solver='adam'

    n_iter_no_change : int, optional, default 10
        Maximum number of epochs to not meet ``tol`` improvement.
        Only effective when solver='sgd' or 'adam'

        .. versionadded:: 0.20

    Attributes
    ----------
    loss_ : float
        The current loss computed with the loss function.

    coefs_ : list, length n_layers - 1
        The ith element in the list represents the weight matrix corresponding
        to layer i.

    intercepts_ : list, length n_layers - 1
        The ith element in the list represents the bias vector corresponding to
        layer i + 1.

    n_iter_ : int,
        The number of iterations the solver has ran.

    n_layers_ : int
        Number of layers.

    n_outputs_ : int
        Number of outputs.

    out_activation_ : string
        Name of the output activation function.

    Notes
    -----
    MLPRegressor trains iteratively since at each time step
    the partial derivatives of the loss function with respect to the model
    parameters are computed to update the parameters.

    It can also have a regularization term added to the loss function
    that shrinks model parameters to prevent overfitting.

    This implementation works with data represented as dense and sparse numpy
    arrays of floating point values.

    References
    ----------
    Hinton, Geoffrey E.
        "Connectionist learning procedures." Artificial intelligence 40.1
        (1989): 185-234.

    Glorot, Xavier, and Yoshua Bengio. "Understanding the difficulty of
        training deep feedforward neural networks." International Conference
        on Artificial Intelligence and Statistics. 2010.

    He, Kaiming, et al. "Delving deep into rectifiers: Surpassing human-level
        performance on imagenet classification." arXiv preprint
        arXiv:1502.01852 (2015).

    Kingma, Diederik, and Jimmy Ba. "Adam: A method for stochastic
        optimization." arXiv preprint arXiv:1412.6980 (2014).
    id   R   R   g-C6?R   R   gMbP?g      ?i   g?g?g+?g:0yE>i
   c      /   C   s   t  t |   } | j d | d | d | d | d | d | d | d | d	 |	 d
 d d |
 d | d | d | d | d | d | d | d | d | d | d | d |  d  S(   NR.   R%   R&   R'   R(   R)   R*   R+   R,   R-   t   squared_lossR   R/   R0   R1   R2   R3   R4   R5   R6   R7   R8   R9   R:   (   R   R   R<   (   R;   R.   R%   R&   R'   R(   R)   R*   R+   R,   R   R/   R0   R1   R2   R3   R4   R5   R6   R7   R8   R9   R:   R   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR<     s    c         C   s=   t  |  d  |  j |  } | j d d k r9 | j   S| S(   s:  Predict using the multi-layer perceptron model.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_samples, n_features)
            The input data.

        Returns
        -------
        y : array-like, shape (n_samples, n_outputs)
            The predicted values.
        R    i   (   R   R   RF   R   (   R;   RX   R   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR     s
    
c      	   C   sq   t  | | d d d d g d t d t \ } } | j d k rg | j d d k rg t | d	 t } n  | | f S(
   NR   R   R   R   R   t	   y_numerici   i   R   (   R   R   R   RF   R   (   R;   RX   RY   R   (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR      s
    "(   id   N(	   R   R   R   R   R   R   R<   R   R   (    (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyR   )  s   				(2   R   t   numpyR   t   abcR    R   t   scipy.optimizeR   R   t   baseR   R   R   R   t   _baseR   R   R	   t   _stochastic_optimizersR
   R   t   model_selectionR   t	   externalsR   t   preprocessingR   t   utilsR   R   R   R   R   R   t
   exceptionsR   t   utils.extmathR   t   utils.validationR   t   utils.multiclassR   R   R   Rq   R#   t   with_metaclassR$   R   R   (    (    (    sK   lib/python2.7/site-packages/sklearn/neural_network/multilayer_perceptron.pyt   <module>   s6   	"   