ó
‡ˆ\c           @  sÙ  d  Z  d d l m Z d d l m Z d d l m Z m Z d d l m Z m	 Z	 d d l
 m Z m Z d d l m Z d d l Z d d l Z d d l Z d d l 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 d
 d l  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+ d
 d l) m, Z- m. Z/ d
 d l) m0 Z1 d
 d l2 m3 Z3 d
 d l4 m5 Z5 m6 Z6 d
 d l7 m8 Z8 d
 d l9 m: Z: d
 d l; m< Z< d
 d l; m= Z= d d  d! d" d# g Z> d  e? f d$ „  ƒ  YZ@ d" e? f d% „  ƒ  YZA d& d' „ ZB d( „  ZC d) e d) d* d+ d, f ƒ f d- „  ƒ  YZD d. e& jE e e e ƒ f d/ „  ƒ  YZF d eF f d0 „  ƒ  YZG d# eF f d1 „  ƒ  YZH d S(2   sl   
The :mod:`sklearn.model_selection._search` includes utilities to fine-tune the
parameters of an estimator.
iÿÿÿÿ(   t   print_function(   t   division(   t   ABCMetat   abstractmethod(   t
   namedtuplet   defaultdict(   t   partialt   reduce(   t   productN(   t   rankdatai   (   t   BaseEstimatort   is_classifiert   clone(   t   MetaEstimatorMixini   (   t   check_cv(   t   _fit_and_score(   t   _aggregate_score_dicts(   t   NotFittedError(   t   Parallelt   delayed(   t   six(   t   check_random_state(   t
   sp_version(   t   MaskedArray(   t   _Mappingt	   _Sequence(   t	   _Iterable(   t   sample_without_replacement(   t	   indexablet   check_is_fitted(   t   if_delegate_has_method(   t   DeprecationDict(   t   _check_multimetric_scoring(   t   check_scoringt   GridSearchCVt   ParameterGridt   fit_grid_pointt   ParameterSamplert   RandomizedSearchCVc           B  s2   e  Z d  Z d „  Z d „  Z d „  Z d „  Z RS(   sí  Grid of parameters with a discrete number of values for each.

    Can be used to iterate over parameter value combinations with the
    Python built-in function iter.

    Read more in the :ref:`User Guide <grid_search>`.

    Parameters
    ----------
    param_grid : dict of string to sequence, or sequence of such
        The parameter grid to explore, as a dictionary mapping estimator
        parameters to sequences of allowed values.

        An empty dict signifies default parameters.

        A sequence of dicts signifies a sequence of grids to search, and is
        useful to avoid exploring parameter combinations that make no sense
        or have no effect. See the examples below.

    Examples
    --------
    >>> from sklearn.model_selection import ParameterGrid
    >>> param_grid = {'a': [1, 2], 'b': [True, False]}
    >>> list(ParameterGrid(param_grid)) == (
    ...    [{'a': 1, 'b': True}, {'a': 1, 'b': False},
    ...     {'a': 2, 'b': True}, {'a': 2, 'b': False}])
    True

    >>> grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}]
    >>> list(ParameterGrid(grid)) == [{'kernel': 'linear'},
    ...                               {'kernel': 'rbf', 'gamma': 1},
    ...                               {'kernel': 'rbf', 'gamma': 10}]
    True
    >>> ParameterGrid(grid)[1] == {'kernel': 'rbf', 'gamma': 1}
    True

    See also
    --------
    :class:`GridSearchCV`:
        Uses :class:`ParameterGrid` to perform a full parallelized parameter
        search.
    c         C  sÐ   t  | t t f ƒ s- t d j | ƒ ƒ ‚ n  t  | t ƒ rH | g } n  xx | D]p } t  | t ƒ s| t d j | ƒ ƒ ‚ n  x@ | D]8 } t  | | t ƒ sƒ t d j | | | ƒ ƒ ‚ qƒ qƒ WqO W| |  _ d  S(   Ns-   Parameter grid is not a dict or a list ({!r})s#   Parameter grid is not a dict ({!r})s;   Parameter grid value is not iterable (key={!r}, value={!r})(   t
   isinstancet   Mappingt   Iterablet	   TypeErrort   formatt   dictt
   param_grid(   t   selfR-   t   gridt   key(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   __init___   s    			c         c  s{   xt |  j  D]i } t | j ƒ  ƒ } | s0 i  Vq
 t | Œ  \ } } x. t | Œ  D]  } t t | | ƒ ƒ } | VqO Wq
 Wd S(   sî   Iterate over the points in the grid.

        Returns
        -------
        params : iterator over dict of string to any
            Yields dictionaries mapping each estimator parameter to one of its
            allowed values.
        N(   R-   t   sortedt   itemst   zipR   R,   (   R.   t   pR3   t   keyst   valuest   vt   params(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   __iter__v   s    	c           s/   t  t t j ƒ ‰  t ‡  f d †  |  j Dƒ ƒ S(   s   Number of points on the grid.c         3  s7   |  ]- } | r+ ˆ  d  „  | j  ƒ  Dƒ ƒ n d Vq d S(   c         s  s   |  ] } t  | ƒ Vq d  S(   N(   t   len(   t   .0R8   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pys	   <genexpr>Ž   s    i   N(   R7   (   R<   R5   (   R   (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pys	   <genexpr>Ž   s   (   R   R   t   operatort   mult   sumR-   (   R.   (    (   R   s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   __len__Š   s    c         C  s  xü |  j  D]ñ } | s6 | d k r& i  S| d 8} q
 n  t t | j ƒ  ƒ d d d … Œ  \ } } g  | D] } t | ƒ ^ qh } t j | ƒ } | | k r¨ | | 8} q
 i  } xF t | | | ƒ D]2 \ }	 } }
 t | |
 ƒ \ } } | | | |	 <qÁ W| Sq
 Wt d ƒ ‚ d S(   s  Get the parameters that would be ``ind``th in iteration

        Parameters
        ----------
        ind : int
            The iteration index

        Returns
        -------
        params : dict of string to any
            Equal to list(self)[ind]
        i    i   Niÿÿÿÿs    ParameterGrid index out of range(	   R-   R4   R2   R3   R;   t   npR   t   divmodt
   IndexError(   R.   t   indt   sub_gridR6   t   values_listst   v_listt   sizest   totalt   outR0   t   nt   offset(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   __getitem__‘   s"    
+"(   t   __name__t
   __module__t   __doc__R1   R:   R@   RM   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR#   3   s
   *			c           B  s,   e  Z d  Z d d „ Z d „  Z d „  Z RS(   s=
  Generator on parameters sampled from given distributions.

    Non-deterministic iterable over random candidate combinations for hyper-
    parameter search. If all parameters are presented as a list,
    sampling without replacement is performed. If at least one parameter
    is given as a distribution, sampling with replacement is used.
    It is highly recommended to use continuous distributions for continuous
    parameters.

    Note that before SciPy 0.16, the ``scipy.stats.distributions`` do not
    accept a custom RNG instance and always use the singleton RNG from
    ``numpy.random``. Hence setting ``random_state`` will not guarantee a
    deterministic iteration whenever ``scipy.stats`` distributions are used to
    define the parameter search space. Deterministic behavior is however
    guaranteed from SciPy 0.16 onwards.

    Read more in the :ref:`User Guide <search>`.

    Parameters
    ----------
    param_distributions : dict
        Dictionary where the keys are parameters and values
        are distributions from which a parameter is to be sampled.
        Distributions either have to provide a ``rvs`` function
        to sample from them, or can be given as a list of values,
        where a uniform distribution is assumed.

    n_iter : integer
        Number of parameter settings that are produced.

    random_state : int, RandomState instance or None, optional (default=None)
        Pseudo random number generator state used for random uniform sampling
        from lists of possible values instead of scipy.stats distributions.
        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`.

    Returns
    -------
    params : dict of string to any
        **Yields** dictionaries mapping each estimator parameter to
        as sampled value.

    Examples
    --------
    >>> from sklearn.model_selection import ParameterSampler
    >>> from scipy.stats.distributions import expon
    >>> import numpy as np
    >>> np.random.seed(0)
    >>> param_grid = {'a':[1, 2], 'b': expon()}
    >>> param_list = list(ParameterSampler(param_grid, n_iter=4))
    >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items())
    ...                 for d in param_list]
    >>> rounded_list == [{'b': 0.89856, 'a': 1},
    ...                  {'b': 0.923223, 'a': 1},
    ...                  {'b': 1.878964, 'a': 2},
    ...                  {'b': 1.038159, 'a': 2}]
    True
    c         C  s   | |  _  | |  _ | |  _ d  S(   N(   t   param_distributionst   n_itert   random_state(   R.   RQ   RR   RS   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR1   ø   s    		c         c  s‘  t  j g  |  j j ƒ  D] } t | d ƒ ^ q ƒ } t |  j ƒ } | rÏ t |  j ƒ } t | ƒ } |  j	 } | | k  r£ t
 j d | |  j	 | f t ƒ | } n  xç t | | d | ƒD] } | | Vq¹ Wn¾ t |  j j ƒ  ƒ } x¦ t j j |  j	 ƒ D] }	 t ƒ  }
 xx | D]p \ } } t | d ƒ rct d k  rJ| j ƒ  |
 | <q€| j d | ƒ |
 | <q| | j t | ƒ ƒ |
 | <qW|
 Vqú Wd  S(   Nt   rvss}   The total space of parameters %d is smaller than n_iter=%d. Running %d iterations. For exhaustive searches, use GridSearchCV.RS   i    i   (   i    i   (   RA   t   allRQ   R7   t   hasattrR   RS   R#   R;   RR   t   warningst   warnt   UserWarningR   R2   R3   R   t   movest   rangeR,   R   RT   t   randint(   R.   R8   t	   all_listst   rndR-   t	   grid_sizeRR   t   iR3   t   _R9   t   k(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR:   ý   s2    	,			!c         C  s   |  j  S(   s&   Number of points that will be sampled.(   RR   (   R.   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR@   $  s    N(   RN   RO   RP   t   NoneR1   R:   R@   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR%   »   s   <	's   raise-deprecatingc	         K  sS   t  | | ƒ t | |  | | | | | | d |	 d t d | ƒ\ }
 } |
 | | f S(   sÄ  Run fit on one set of parameters.

    Parameters
    ----------
    X : array-like, sparse matrix or list
        Input data.

    y : array-like or None
        Targets for input data.

    estimator : estimator object
        A object of that type is instantiated for each grid point.
        This is assumed to implement the scikit-learn estimator interface.
        Either estimator needs to provide a ``score`` function,
        or ``scoring`` must be passed.

    parameters : dict
        Parameters to be set on estimator for this grid point.

    train : ndarray, dtype int or bool
        Boolean mask or indices for training set.

    test : ndarray, dtype int or bool
        Boolean mask or indices for test set.

    scorer : callable or None
        The scorer callable object / function must have its signature as
        ``scorer(estimator, X, y)``.

        If ``None`` the estimator's default scorer is used.

    verbose : int
        Verbosity level.

    **fit_params : kwargs
        Additional parameter passed to the fit function of the estimator.

    error_score : 'raise' or numeric
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised. If a numeric value is given,
        FitFailedWarning is raised. This parameter does not affect the refit
        step, which will always raise the error. Default is 'raise' but from
        version 0.22 it will change to np.nan.

    Returns
    -------
    score : float
         Score of this parameter setting on given training / test split.

    parameters : dict
        The parameters that have been evaluated.

    n_samples_test : int
        Number of test samples in this split.
    t
   fit_paramst   return_n_test_samplest   error_score(   R!   R   t   True(   t   Xt   yt	   estimatort
   parameterst   traint   testt   scorert   verboseRf   Rd   t   scorest   n_samples_test(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR$   )  s    ;c         C  sê   t  |  d ƒ r |  g }  n  xÈ |  D]À } x· | j ƒ  D]© \ } } t | t j ƒ rq | j d k rq t d ƒ ‚ n  t | t j ƒ sœ t | t j t	 f ƒ r´ t d j
 | ƒ ƒ ‚ n  t | ƒ d k r5 t d j
 | ƒ ƒ ‚ q5 q5 Wq" Wd  S(   NR3   i   s*   Parameter array should be one-dimensional.s[   Parameter values for parameter ({0}) need to be a sequence(but not a string) or np.ndarray.i    sE   Parameter values for parameter ({0}) need to be a non-empty sequence.(   RV   R3   R'   RA   t   ndarrayt   ndimt
   ValueErrorR   t   string_typest   SequenceR+   R;   (   R-   R5   t   nameR8   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   _check_param_gridn  s    !		t   _CVScoreTupleRk   t   mean_validation_scoret   cv_validation_scoresc           B  s   e  Z d Z d  „  Z RS(   c         C  s%   d j  |  j t j |  j ƒ |  j ƒ S(   s-   Simple custom repr to summarize the main infos(   mean: {0:.5f}, std: {1:.5f}, params: {2}(   R+   Rz   RA   t   stdR{   Rk   (   R.   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   __repr__‘  s    (    (   RN   RO   t	   __slots__R}   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyRy   ƒ  s   t   BaseSearchCVc           B  s  e  Z d  Z e d d d d e d d d d e d „
 ƒ Z e d „  ƒ Z d d „ Z	 d „  Z
 e d	 d ƒ d „  ƒ Z e d	 d ƒ d „  ƒ Z e d	 d ƒ d „  ƒ Z e d	 d ƒ d „  ƒ Z e d	 d ƒ d „  ƒ Z e d	 d ƒ d „  ƒ Z e d „  ƒ Z d „  Z d d d „ Z d „  Z RS(   sJ   Abstract base class for hyper parameter search with cross-validation.
    RX   i    s   2*n_jobss   raise-deprecatingc         C  sg   | |  _  | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _ |
 |  _	 | |  _
 d  S(   N(   t   scoringRj   t   n_jobsRd   t   iidt   refitt   cvRo   t   pre_dispatchRf   t   return_train_score(   R.   Rj   R€   Rd   R   R‚   Rƒ   R„   Ro   R…   Rf   R†   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR1   ž  s    										c         C  s
   |  j  j S(   N(   Rj   t   _estimator_type(   R.   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR‡   °  s    c         C  sg   |  j  d ƒ |  j d k r2 t d |  j ƒ ‚ n  |  j rK |  j |  j n |  j } | |  j | | ƒ S(   sš  Returns the score on the given data, if the estimator has been refit.

        This uses the score defined by ``scoring`` where provided, and the
        ``best_estimator_.score`` method otherwise.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            Input data, where n_samples is the number of samples and
            n_features is the number of features.

        y : array-like, shape = [n_samples] or [n_samples, n_output], optional
            Target relative to X for classification or regression;
            None for unsupervised learning.

        Returns
        -------
        score : float
        t   scoresN   No score function explicitly defined, and the estimator doesn't provide one %sN(   t   _check_is_fittedt   scorer_Rc   Rt   t   best_estimator_t   multimetric_Rƒ   (   R.   Rh   Ri   Rˆ   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyRˆ   ´  s    "c         C  s<   |  j  s+ t d t |  ƒ j | f ƒ ‚ n t |  d ƒ d  S(   Ns¸   This %s instance was initialized with refit=False. %s is available only after refitting on the best parameters. You can refit an estimator manually using the ``best_params_`` attributeR‹   (   Rƒ   R   t   typeRN   R   (   R.   t   method_name(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR‰   Ð  s    	t   delegateR‹   Rj   c         C  s   |  j  d ƒ |  j j | ƒ S(   sT  Call predict on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``predict``.

        Parameters
        -----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        t   predict(   R‰   R‹   R   (   R.   Rh   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR   Ü  s    c         C  s   |  j  d ƒ |  j j | ƒ S(   s`  Call predict_proba on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``predict_proba``.

        Parameters
        -----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        t   predict_proba(   R‰   R‹   R‘   (   R.   Rh   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR‘   í  s    c         C  s   |  j  d ƒ |  j j | ƒ S(   sh  Call predict_log_proba on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``predict_log_proba``.

        Parameters
        -----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        t   predict_log_proba(   R‰   R‹   R’   (   R.   Rh   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR’   þ  s    c         C  s   |  j  d ƒ |  j j | ƒ S(   sh  Call decision_function on the estimator with the best found parameters.

        Only available if ``refit=True`` and the underlying estimator supports
        ``decision_function``.

        Parameters
        -----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        t   decision_function(   R‰   R‹   R“   (   R.   Rh   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR“     s    c         C  s   |  j  d ƒ |  j j | ƒ S(   sX  Call transform on the estimator with the best found parameters.

        Only available if the underlying estimator supports ``transform`` and
        ``refit=True``.

        Parameters
        -----------
        X : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        t	   transform(   R‰   R‹   R”   (   R.   Rh   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR”      s    c         C  s   |  j  d ƒ |  j j | ƒ S(   sg  Call inverse_transform on the estimator with the best found params.

        Only available if the underlying estimator implements
        ``inverse_transform`` and ``refit=True``.

        Parameters
        -----------
        Xt : indexable, length n_samples
            Must fulfill the input assumptions of the
            underlying estimator.

        t   inverse_transform(   R‰   R‹   R•   (   R.   t   Xt(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR•   1  s    c         C  s   |  j  d ƒ |  j j S(   Nt   classes_(   R‰   R‹   R—   (   R.   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR—   B  s    c         C  s   t  d ƒ ‚ d S(   s{  Repeatedly calls `evaluate_candidates` to conduct a search.

        This method, implemented in sub-classes, makes it possible to
        customize the the scheduling of evaluations: GridSearchCV and
        RandomizedSearchCV schedule evaluations for their whole parameter
        search space at once but other more sequential approaches are also
        possible: for instance is possible to iteratively schedule evaluations
        for new regions of the parameter search space based on previously
        collected evaluation results. This makes it possible to implement
        Bayesian optimization or more generally sequential model-based
        optimization by deriving from the BaseSearchCV abstract base class.

        Parameters
        ----------
        evaluate_candidates : callable
            This callback accepts a list of candidates, where each candidate is
            a dict of parameter settings. It returns a dict of all results so
            far, formatted like ``cv_results_``.

        Examples
        --------

        ::

            def _run_search(self, evaluate_candidates):
                'Try C=0.1 only if C=1 is better than C=10'
                all_results = evaluate_candidates([{'C': 1}, {'C': 10}])
                score = all_results['mean_test_score']
                if score[0] < score[1]:
                    evaluate_candidates([{'C': 0.1}])
        s   _run_search not implemented.N(   t   NotImplementedError(   R.   t   evaluate_candidates(    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   _run_searchG  s     c           s  ˆ j  d k	 rD t j d t ƒ | r8 t j d t ƒ qD ˆ j  } n  ˆ j } t ˆ j ˆ d t	 | ƒ ƒ‰ t
 ˆ j d ˆ j ƒ\ ‰
 ˆ _ ˆ j rë ˆ j t k	 rß t ˆ j t j ƒ sÉ ˆ j ˆ
 k rß t d ˆ j ƒ ‚ qñ ˆ j } n d } t ˆ  ˆ ˆ ƒ \ ‰  ‰ ‰ ˆ j ˆ  ˆ ˆ ƒ ‰ t ˆ j ƒ ‰ t d ˆ j d ˆ j d	 ˆ j ƒ ‰ t d
 ˆ
 d | d ˆ j d t d t d t d ˆ j d ˆ j ƒ ‰ i  g ‰	 ˆ Q g  ‰ g  ‰ ‡  ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡	 ‡
 ‡ ‡ f d †  } ˆ j | ƒ Wd QXˆ	 d } ˆ j sˆ j r[| d | j ƒ  ˆ _  | d ˆ j  ˆ _! | d | ˆ j  ˆ _" n  ˆ j rßt ˆ ƒ j# ˆ j!   ˆ _$ t% j% ƒ  }	 ˆ d k	 r°ˆ j$ j& ˆ  ˆ |  n ˆ j$ j& ˆ  |  t% j% ƒ  }
 |
 |	 ˆ _' n  ˆ j rîˆ
 n ˆ
 d ˆ _( | ˆ _) ˆ ˆ _* ˆ S(   sé  Run fit with all sets of parameters.

        Parameters
        ----------

        X : array-like, shape = [n_samples, n_features]
            Training vector, where n_samples is the number of samples and
            n_features is the number of features.

        y : array-like, shape = [n_samples] or [n_samples, n_output], optional
            Target relative to X for classification or regression;
            None for unsupervised learning.

        groups : array-like, with shape (n_samples,), optional
            Group labels for the samples used while splitting the dataset into
            train/test set.

        **fit_params : dict of string -> object
            Parameters passed to the ``fit`` method of the estimator
        s›   "fit_params" as a constructor argument was deprecated in version 0.19 and will be removed in version 0.21. Pass fit parameters to the "fit" method instead.sg   Ignoring fit_params passed as a constructor argument in favor of keyword arguments to the "fit" method.t
   classifierR€   s  For multi-metric scoring, the parameter refit must be set to a scorer key to refit an estimator with the best parameter setting on the whole data and make the best_* attributes available for that metric. If this is not needed, refit should be set to False explicitly. %r was passed.Rˆ   R   Ro   R…   Rn   Rd   R†   Re   t   return_timest   return_parametersRf   c           sÂ   t  |  ƒ }  t |  ƒ } ˆ j d k rG t d j ˆ | | ˆ ƒ ƒ n  ˆ ‡  ‡ ‡ ‡ f d †  t |  ˆ j ˆ  ˆ ˆ ƒ ƒ Dƒ ƒ } ˆ j |  ƒ ˆ j | ƒ ˆ j ˆ ˆ
 ˆ ˆ ƒ ˆ	 d <ˆ	 d S(   Ni    s@   Fitting {0} folds for each of {1} candidates, totalling {2} fitsc         3  sN   |  ]D \ } \ } } t  t ƒ t ˆ ƒ ˆ  ˆ d  | d | d | ˆ Vq d S(   Rl   Rm   Rk   N(   R   R   R   (   R<   Rk   Rl   Rm   (   Rh   t   base_estimatort   fit_and_score_kwargsRi   (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pys	   <genexpr>À  s   (	   t   listR;   Ro   t   printR+   R   t   splitt   extendt   _format_results(   t   candidate_paramst   n_candidatesRJ   (   Rh   t   all_candidate_paramst   all_outRž   R„   RŸ   t   groupst   n_splitst   parallelt   results_containert   scorersR.   Ri   (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR™   ·  s    	Ni    s   rank_test_%sR9   s   mean_test_%s(+   Rd   Rc   RW   RX   t   DeprecationWarningt   RuntimeWarningRj   R   R„   R   R    R€   RŒ   Rƒ   t   FalseR'   R   Ru   Rt   R   t   get_n_splitsR   R   R   Ro   R…   R,   R†   Rg   Rf   Rš   t   argmint   best_index_t   best_params_t   best_score_t
   set_paramsR‹   t   timet   fitt   refit_time_RŠ   t   cv_results_t	   n_splits_(   R.   Rh   Ri   R©   Rd   Rj   t   refit_metricR™   t   resultst   refit_start_timet   refit_end_time(    (   Rh   R§   R¨   Rž   R„   RŸ   R©   Rª   R«   R¬   R­   R.   Ri   s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR¸   i  sr    		
					3
			c      
     s  t  | ƒ ‰  |  j r3 t | Œ  \ } } } } }	 n t | Œ  \ } } } }	 t | ƒ }
 |  j ro t | ƒ } n  |  j d k r‡ t ƒ  n i  ‰ d  t t ‡  ‡ ‡ f d † } | d | ƒ | d |	 ƒ t t t	 t
 j ˆ  ƒ d t d t ƒƒ } xI t | ƒ D]; \ } } x, | j ƒ  D] \ } } | | d | | <qWqü Wˆ j | ƒ | ˆ d <t
 j | ˆ  d t
 j ƒ} |  j } |  j d k r3t } x‚ | j ƒ  D]t } |
 | j ˆ  ˆ ƒ } t
 j | d	 d
 d | ƒ} t
 j | d	 d
 ƒ} t
 j | | d d d d ƒs™t } Pq™q™W| r*t j d t ƒ n  t } n  xÕ | j ƒ  D]Ç } | d | |
 | d t d t d | rr| n d  ƒ|  j r@t ˆ j ƒ  ƒ } | d | | | d t ƒ|  j d k rxC t ˆ j ƒ  ƒ | D]( } d j | ƒ } ˆ j | | t ƒ qÕWqq@q@Wˆ S(   NRX   c           s  t  j | d t  j ƒj ˆ  ˆ ƒ } | rh x; t ˆ ƒ D]* } | d d … | f ˆ d | |  f <q7 Wn  t  j | d d d | ƒ} | ˆ d |  <t  j t  j | | d d … t  j f d d d d | ƒƒ } | ˆ d	 |  <| rt  j t	 | d
 d ƒd t  j
 ƒˆ d |  <n  d S(   s;   A small helper to store the scores/times to the cv_results_t   dtypeNs
   split%d_%st   axisi   t   weightss   mean_%si   s   std_%st   methodt   mins   rank_%s(   RA   t   arrayt   float64t   reshapeR[   t   averaget   sqrtt   newaxist   asarrayR	   t   int32(   t   key_nameRÅ   RÂ   t   splitst   rankt   split_it   array_meanst
   array_stds(   R¦   Rª   R½   (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   _store  s    	+t   fit_timet
   score_timet   maskRÀ   s   param_%sR9   RÁ   i   RÂ   t   rtolg-Cëâ6?t   atols°   The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.s   test_%sRÎ   RÏ   s   train_%ss£   You are accessing a training score ({!r}), which will not be available by default any more in 0.21. If you need training scores, please set return_train_score=True(   R;   R†   R4   R   R   Rc   R°   R   R   R   RA   t   emptyRg   t   objectt	   enumerateR3   t   updateRÅ   t   intR‚   R6   RÇ   RÈ   t   allcloseRW   RX   R®   t   setR+   t   add_warningt   FutureWarning(   R.   R¥   R­   Rª   RJ   t   train_score_dictst   test_score_dictst   test_sample_countsRÔ   RÕ   t   test_scorest   train_scoresRÓ   t   param_resultst   cand_iR9   Rw   t   valueR‚   RX   t   scorer_nameRp   t   means_weightedt   means_unweightedt	   prev_keysR0   t   message(    (   R¦   Rª   R½   s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR¤   ò  sl    			
				
			!N(   R‹   Rj   (   R‹   Rj   (   R‹   Rj   (   R‹   Rj   (   R‹   Rj   (   R‹   Rj   (   RN   RO   RP   R   Rc   Rg   R1   t   propertyR‡   Rˆ   R‰   R   R   R‘   R’   R“   R”   R•   R—   Rš   R¸   R¤   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR   ™  s&   			"‰c           B  s>   e  Z d  Z e e e d e d d d d d d „
 Z d „  Z RS(   s³6  Exhaustive search over specified parameter values for an estimator.

    Important members are fit, predict.

    GridSearchCV implements a "fit" and a "score" method.
    It also implements "predict", "predict_proba", "decision_function",
    "transform" and "inverse_transform" if they are implemented in the
    estimator used.

    The parameters of the estimator used to apply these methods are optimized
    by cross-validated grid-search over a parameter grid.

    Read more in the :ref:`User Guide <grid_search>`.

    Parameters
    ----------
    estimator : estimator object.
        This is assumed to implement the scikit-learn estimator interface.
        Either estimator needs to provide a ``score`` function,
        or ``scoring`` must be passed.

    param_grid : dict or list of dictionaries
        Dictionary with parameters names (string) as keys and lists of
        parameter settings to try as values, or a list of such
        dictionaries, in which case the grids spanned by each dictionary
        in the list are explored. This enables searching over any sequence
        of parameter settings.

    scoring : string, callable, list/tuple, dict or None, default: None
        A single string (see :ref:`scoring_parameter`) or a callable
        (see :ref:`scoring`) to evaluate the predictions on the test set.

        For evaluating multiple metrics, either give a list of (unique) strings
        or a dict with names as keys and callables as values.

        NOTE that when using custom scorers, each scorer should return a single
        value. Metric functions returning a list/array of values can be wrapped
        into multiple scorers that return one value each.

        See :ref:`multimetric_grid_search` for an example.

        If None, the estimator's default scorer (if available) is used.

    fit_params : dict, optional
        Parameters to pass to the fit method.

        .. deprecated:: 0.19
           ``fit_params`` as a constructor argument was deprecated in version
           0.19 and will be removed in version 0.21. Pass fit parameters to
           the ``fit`` method instead.

    n_jobs : int or None, optional (default=None)
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    pre_dispatch : int, or string, optional
        Controls the number of jobs that get dispatched during parallel
        execution. Reducing this number can be useful to avoid an
        explosion of memory consumption when more jobs get dispatched
        than CPUs can process. This parameter can be:

            - None, in which case all the jobs are immediately
              created and spawned. Use this for lightweight and
              fast-running jobs, to avoid delays due to on-demand
              spawning of the jobs

            - An int, giving the exact number of total jobs that are
              spawned

            - A string, giving an expression as a function of n_jobs,
              as in '2*n_jobs'

    iid : boolean, default='warn'
        If True, return the average score across folds, weighted by the number
        of samples in each test set. In this case, the data is assumed to be
        identically distributed across the folds, and the loss minimized is
        the total loss per sample, and not the mean loss across the folds. If
        False, return the average score across folds. Default is True, but
        will change to False in version 0.21, to correspond to the standard
        definition of cross-validation.

        .. versionchanged:: 0.20
            Parameter ``iid`` will change from True to False by default in
            version 0.22, and will be removed in 0.24.

    cv : int, cross-validation generator or an iterable, optional
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 3-fold cross validation,
        - integer, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs, if the estimator is a classifier and ``y`` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.20
            ``cv`` default value if None will change from 3-fold to 5-fold
            in v0.22.

    refit : boolean, or string, default=True
        Refit an estimator using the best found parameters on the whole
        dataset.

        For multiple metric evaluation, this needs to be a string denoting the
        scorer is used to find the best parameters for refitting the estimator
        at the end.

        The refitted estimator is made available at the ``best_estimator_``
        attribute and permits using ``predict`` directly on this
        ``GridSearchCV`` instance.

        Also for multiple metric evaluation, the attributes ``best_index_``,
        ``best_score_`` and ``best_params_`` will only be available if
        ``refit`` is set and all of them will be determined w.r.t this specific
        scorer.

        See ``scoring`` parameter to know more about multiple metric
        evaluation.

    verbose : integer
        Controls the verbosity: the higher, the more messages.

    error_score : 'raise' or numeric
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised. If a numeric value is given,
        FitFailedWarning is raised. This parameter does not affect the refit
        step, which will always raise the error. Default is 'raise' but from
        version 0.22 it will change to np.nan.

    return_train_score : boolean, optional
        If ``False``, the ``cv_results_`` attribute will not include training
        scores.

        Current default is ``'warn'``, which behaves as ``True`` in addition
        to raising a warning when a training score is looked up.
        That default will be changed to ``False`` in 0.21.
        Computing training scores is used to get insights on how different
        parameter settings impact the overfitting/underfitting trade-off.
        However computing the scores on the training set can be computationally
        expensive and is not strictly required to select the parameters that
        yield the best generalization performance.


    Examples
    --------
    >>> from sklearn import svm, datasets
    >>> from sklearn.model_selection import GridSearchCV
    >>> iris = datasets.load_iris()
    >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]}
    >>> svc = svm.SVC(gamma="scale")
    >>> clf = GridSearchCV(svc, parameters, cv=5)
    >>> clf.fit(iris.data, iris.target)
    ...                             # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
    GridSearchCV(cv=5, error_score=...,
           estimator=SVC(C=1.0, cache_size=..., class_weight=..., coef0=...,
                         decision_function_shape='ovr', degree=..., gamma=...,
                         kernel='rbf', max_iter=-1, probability=False,
                         random_state=None, shrinking=True, tol=...,
                         verbose=False),
           fit_params=None, iid=..., n_jobs=None,
           param_grid=..., pre_dispatch=..., refit=..., return_train_score=...,
           scoring=..., verbose=...)
    >>> sorted(clf.cv_results_.keys())
    ...                             # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
    ['mean_fit_time', 'mean_score_time', 'mean_test_score',...
     'mean_train_score', 'param_C', 'param_kernel', 'params',...
     'rank_test_score', 'split0_test_score',...
     'split0_train_score', 'split1_test_score', 'split1_train_score',...
     'split2_test_score', 'split2_train_score',...
     'std_fit_time', 'std_score_time', 'std_test_score', 'std_train_score'...]

    Attributes
    ----------
    cv_results_ : dict of numpy (masked) ndarrays
        A dict with keys as column headers and values as columns, that can be
        imported into a pandas ``DataFrame``.

        For instance the below given table

        +------------+-----------+------------+-----------------+---+---------+
        |param_kernel|param_gamma|param_degree|split0_test_score|...|rank_t...|
        +============+===========+============+=================+===+=========+
        |  'poly'    |     --    |      2     |       0.80      |...|    2    |
        +------------+-----------+------------+-----------------+---+---------+
        |  'poly'    |     --    |      3     |       0.70      |...|    4    |
        +------------+-----------+------------+-----------------+---+---------+
        |  'rbf'     |     0.1   |     --     |       0.80      |...|    3    |
        +------------+-----------+------------+-----------------+---+---------+
        |  'rbf'     |     0.2   |     --     |       0.93      |...|    1    |
        +------------+-----------+------------+-----------------+---+---------+

        will be represented by a ``cv_results_`` dict of::

            {
            'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'],
                                         mask = [False False False False]...)
            'param_gamma': masked_array(data = [-- -- 0.1 0.2],
                                        mask = [ True  True False False]...),
            'param_degree': masked_array(data = [2.0 3.0 -- --],
                                         mask = [False False  True  True]...),
            'split0_test_score'  : [0.80, 0.70, 0.80, 0.93],
            'split1_test_score'  : [0.82, 0.50, 0.70, 0.78],
            'mean_test_score'    : [0.81, 0.60, 0.75, 0.85],
            'std_test_score'     : [0.01, 0.10, 0.05, 0.08],
            'rank_test_score'    : [2, 4, 3, 1],
            'split0_train_score' : [0.80, 0.92, 0.70, 0.93],
            'split1_train_score' : [0.82, 0.55, 0.70, 0.87],
            'mean_train_score'   : [0.81, 0.74, 0.70, 0.90],
            'std_train_score'    : [0.01, 0.19, 0.00, 0.03],
            'mean_fit_time'      : [0.73, 0.63, 0.43, 0.49],
            'std_fit_time'       : [0.01, 0.02, 0.01, 0.01],
            'mean_score_time'    : [0.01, 0.06, 0.04, 0.04],
            'std_score_time'     : [0.00, 0.00, 0.00, 0.01],
            'params'             : [{'kernel': 'poly', 'degree': 2}, ...],
            }

        NOTE

        The key ``'params'`` is used to store a list of parameter
        settings dicts for all the parameter candidates.

        The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and
        ``std_score_time`` are all in seconds.

        For multi-metric evaluation, the scores for all the scorers are
        available in the ``cv_results_`` dict at the keys ending with that
        scorer's name (``'_<scorer_name>'``) instead of ``'_score'`` shown
        above. ('split0_test_precision', 'mean_train_precision' etc.)

    best_estimator_ : estimator or dict
        Estimator that was chosen by the search, i.e. estimator
        which gave highest score (or smallest loss if specified)
        on the left out data. Not available if ``refit=False``.

        See ``refit`` parameter for more information on allowed values.

    best_score_ : float
        Mean cross-validated score of the best_estimator

        For multi-metric evaluation, this is present only if ``refit`` is
        specified.

    best_params_ : dict
        Parameter setting that gave the best results on the hold out data.

        For multi-metric evaluation, this is present only if ``refit`` is
        specified.

    best_index_ : int
        The index (of the ``cv_results_`` arrays) which corresponds to the best
        candidate parameter setting.

        The dict at ``search.cv_results_['params'][search.best_index_]`` gives
        the parameter setting for the best model, that gives the highest
        mean score (``search.best_score_``).

        For multi-metric evaluation, this is present only if ``refit`` is
        specified.

    scorer_ : function or a dict
        Scorer function used on the held out data to choose the best
        parameters for the model.

        For multi-metric evaluation, this attribute holds the validated
        ``scoring`` dict which maps the scorer key to the scorer callable.

    n_splits_ : int
        The number of cross-validation splits (folds/iterations).

    refit_time_ : float
        Seconds used for refitting the best model on the whole dataset.

        This is present only if ``refit`` is not False.

    Notes
    ------
    The parameters selected are those that maximize the score of the left out
    data, unless an explicit score is passed in which case it is used instead.

    If `n_jobs` was set to a value higher than one, the data is copied for each
    point in the grid (and not `n_jobs` times). This is done for efficiency
    reasons if individual jobs take very little time, but may raise errors if
    the dataset is large and not enough memory is available.  A workaround in
    this case is to set `pre_dispatch`. Then, the memory is copied only
    `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 *
    n_jobs`.

    See Also
    ---------
    :class:`ParameterGrid`:
        generates all the combinations of a hyperparameter grid.

    :func:`sklearn.model_selection.train_test_split`:
        utility function to split the data into a development set usable
        for fitting a GridSearchCV instance and an evaluation set for
        its final evaluation.

    :func:`sklearn.metrics.make_scorer`:
        Make a scorer from a performance metric or loss function.

    RX   i    s   2*n_jobss   raise-deprecatingc         C  sl   t  t |  ƒ j d | d | d | d | d | d | d | d |	 d	 |
 d
 | d | ƒ | |  _ t | ƒ d  S(   NRj   R€   Rd   R   R‚   Rƒ   R„   Ro   R…   Rf   R†   (   t   superR"   R1   R-   Rx   (   R.   Rj   R-   R€   Rd   R   R‚   Rƒ   R„   Ro   R…   Rf   R†   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR1   ™  s    	c         C  s   | t  |  j ƒ ƒ d S(   s#   Search all candidates in param_gridN(   R#   R-   (   R.   R™   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyRš   ¥  s    (   RN   RO   RP   Rc   Rg   R1   Rš   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR"   b  s   ÿ 6	c           B  sD   e  Z d  Z d e e e d e d d d e d d d „ Z d „  Z RS(   sØ4  Randomized search on hyper parameters.

    RandomizedSearchCV implements a "fit" and a "score" method.
    It also implements "predict", "predict_proba", "decision_function",
    "transform" and "inverse_transform" if they are implemented in the
    estimator used.

    The parameters of the estimator used to apply these methods are optimized
    by cross-validated search over parameter settings.

    In contrast to GridSearchCV, not all parameter values are tried out, but
    rather a fixed number of parameter settings is sampled from the specified
    distributions. The number of parameter settings that are tried is
    given by n_iter.

    If all parameters are presented as a list,
    sampling without replacement is performed. If at least one parameter
    is given as a distribution, sampling with replacement is used.
    It is highly recommended to use continuous distributions for continuous
    parameters.

    Note that before SciPy 0.16, the ``scipy.stats.distributions`` do not
    accept a custom RNG instance and always use the singleton RNG from
    ``numpy.random``. Hence setting ``random_state`` will not guarantee a
    deterministic iteration whenever ``scipy.stats`` distributions are used to
    define the parameter search space.

    Read more in the :ref:`User Guide <randomized_parameter_search>`.

    Parameters
    ----------
    estimator : estimator object.
        A object of that type is instantiated for each grid point.
        This is assumed to implement the scikit-learn estimator interface.
        Either estimator needs to provide a ``score`` function,
        or ``scoring`` must be passed.

    param_distributions : dict
        Dictionary with parameters names (string) as keys and distributions
        or lists of parameters to try. Distributions must provide a ``rvs``
        method for sampling (such as those from scipy.stats.distributions).
        If a list is given, it is sampled uniformly.

    n_iter : int, default=10
        Number of parameter settings that are sampled. n_iter trades
        off runtime vs quality of the solution.

    scoring : string, callable, list/tuple, dict or None, default: None
        A single string (see :ref:`scoring_parameter`) or a callable
        (see :ref:`scoring`) to evaluate the predictions on the test set.

        For evaluating multiple metrics, either give a list of (unique) strings
        or a dict with names as keys and callables as values.

        NOTE that when using custom scorers, each scorer should return a single
        value. Metric functions returning a list/array of values can be wrapped
        into multiple scorers that return one value each.

        See :ref:`multimetric_grid_search` for an example.

        If None, the estimator's default scorer (if available) is used.

    fit_params : dict, optional
        Parameters to pass to the fit method.

        .. deprecated:: 0.19
           ``fit_params`` as a constructor argument was deprecated in version
           0.19 and will be removed in version 0.21. Pass fit parameters to
           the ``fit`` method instead.

    n_jobs : int or None, optional (default=None)
        Number of jobs to run in parallel.
        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    pre_dispatch : int, or string, optional
        Controls the number of jobs that get dispatched during parallel
        execution. Reducing this number can be useful to avoid an
        explosion of memory consumption when more jobs get dispatched
        than CPUs can process. This parameter can be:

            - None, in which case all the jobs are immediately
              created and spawned. Use this for lightweight and
              fast-running jobs, to avoid delays due to on-demand
              spawning of the jobs

            - An int, giving the exact number of total jobs that are
              spawned

            - A string, giving an expression as a function of n_jobs,
              as in '2*n_jobs'

    iid : boolean, default='warn'
        If True, return the average score across folds, weighted by the number
        of samples in each test set. In this case, the data is assumed to be
        identically distributed across the folds, and the loss minimized is
        the total loss per sample, and not the mean loss across the folds. If
        False, return the average score across folds. Default is True, but
        will change to False in version 0.21, to correspond to the standard
        definition of cross-validation.

        .. versionchanged:: 0.20
            Parameter ``iid`` will change from True to False by default in
            version 0.22, and will be removed in 0.24.

    cv : int, cross-validation generator or an iterable, optional
        Determines the cross-validation splitting strategy.
        Possible inputs for cv are:

        - None, to use the default 3-fold cross validation,
        - integer, to specify the number of folds in a `(Stratified)KFold`,
        - :term:`CV splitter`,
        - An iterable yielding (train, test) splits as arrays of indices.

        For integer/None inputs, if the estimator is a classifier and ``y`` is
        either binary or multiclass, :class:`StratifiedKFold` is used. In all
        other cases, :class:`KFold` is used.

        Refer :ref:`User Guide <cross_validation>` for the various
        cross-validation strategies that can be used here.

        .. versionchanged:: 0.20
            ``cv`` default value if None will change from 3-fold to 5-fold
            in v0.22.

    refit : boolean, or string default=True
        Refit an estimator using the best found parameters on the whole
        dataset.

        For multiple metric evaluation, this needs to be a string denoting the
        scorer that would be used to find the best parameters for refitting
        the estimator at the end.

        The refitted estimator is made available at the ``best_estimator_``
        attribute and permits using ``predict`` directly on this
        ``RandomizedSearchCV`` instance.

        Also for multiple metric evaluation, the attributes ``best_index_``,
        ``best_score_`` and ``best_params_`` will only be available if
        ``refit`` is set and all of them will be determined w.r.t this specific
        scorer.

        See ``scoring`` parameter to know more about multiple metric
        evaluation.

    verbose : integer
        Controls the verbosity: the higher, the more messages.

    random_state : int, RandomState instance or None, optional, default=None
        Pseudo random number generator state used for random uniform sampling
        from lists of possible values instead of scipy.stats distributions.
        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`.

    error_score : 'raise' or numeric
        Value to assign to the score if an error occurs in estimator fitting.
        If set to 'raise', the error is raised. If a numeric value is given,
        FitFailedWarning is raised. This parameter does not affect the refit
        step, which will always raise the error. Default is 'raise' but from
        version 0.22 it will change to np.nan.

    return_train_score : boolean, optional
        If ``False``, the ``cv_results_`` attribute will not include training
        scores.

        Current default is ``'warn'``, which behaves as ``True`` in addition
        to raising a warning when a training score is looked up.
        That default will be changed to ``False`` in 0.21.
        Computing training scores is used to get insights on how different
        parameter settings impact the overfitting/underfitting trade-off.
        However computing the scores on the training set can be computationally
        expensive and is not strictly required to select the parameters that
        yield the best generalization performance.

    Attributes
    ----------
    cv_results_ : dict of numpy (masked) ndarrays
        A dict with keys as column headers and values as columns, that can be
        imported into a pandas ``DataFrame``.

        For instance the below given table

        +--------------+-------------+-------------------+---+---------------+
        | param_kernel | param_gamma | split0_test_score |...|rank_test_score|
        +==============+=============+===================+===+===============+
        |    'rbf'     |     0.1     |       0.80        |...|       2       |
        +--------------+-------------+-------------------+---+---------------+
        |    'rbf'     |     0.2     |       0.90        |...|       1       |
        +--------------+-------------+-------------------+---+---------------+
        |    'rbf'     |     0.3     |       0.70        |...|       1       |
        +--------------+-------------+-------------------+---+---------------+

        will be represented by a ``cv_results_`` dict of::

            {
            'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'],
                                          mask = False),
            'param_gamma'  : masked_array(data = [0.1 0.2 0.3], mask = False),
            'split0_test_score'  : [0.80, 0.90, 0.70],
            'split1_test_score'  : [0.82, 0.50, 0.70],
            'mean_test_score'    : [0.81, 0.70, 0.70],
            'std_test_score'     : [0.01, 0.20, 0.00],
            'rank_test_score'    : [3, 1, 1],
            'split0_train_score' : [0.80, 0.92, 0.70],
            'split1_train_score' : [0.82, 0.55, 0.70],
            'mean_train_score'   : [0.81, 0.74, 0.70],
            'std_train_score'    : [0.01, 0.19, 0.00],
            'mean_fit_time'      : [0.73, 0.63, 0.43],
            'std_fit_time'       : [0.01, 0.02, 0.01],
            'mean_score_time'    : [0.01, 0.06, 0.04],
            'std_score_time'     : [0.00, 0.00, 0.00],
            'params'             : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...],
            }

        NOTE

        The key ``'params'`` is used to store a list of parameter
        settings dicts for all the parameter candidates.

        The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and
        ``std_score_time`` are all in seconds.

        For multi-metric evaluation, the scores for all the scorers are
        available in the ``cv_results_`` dict at the keys ending with that
        scorer's name (``'_<scorer_name>'``) instead of ``'_score'`` shown
        above. ('split0_test_precision', 'mean_train_precision' etc.)

    best_estimator_ : estimator or dict
        Estimator that was chosen by the search, i.e. estimator
        which gave highest score (or smallest loss if specified)
        on the left out data. Not available if ``refit=False``.

        For multi-metric evaluation, this attribute is present only if
        ``refit`` is specified.

        See ``refit`` parameter for more information on allowed values.

    best_score_ : float
        Mean cross-validated score of the best_estimator.

        For multi-metric evaluation, this is not available if ``refit`` is
        ``False``. See ``refit`` parameter for more information.

    best_params_ : dict
        Parameter setting that gave the best results on the hold out data.

        For multi-metric evaluation, this is not available if ``refit`` is
        ``False``. See ``refit`` parameter for more information.

    best_index_ : int
        The index (of the ``cv_results_`` arrays) which corresponds to the best
        candidate parameter setting.

        The dict at ``search.cv_results_['params'][search.best_index_]`` gives
        the parameter setting for the best model, that gives the highest
        mean score (``search.best_score_``).

        For multi-metric evaluation, this is not available if ``refit`` is
        ``False``. See ``refit`` parameter for more information.

    scorer_ : function or a dict
        Scorer function used on the held out data to choose the best
        parameters for the model.

        For multi-metric evaluation, this attribute holds the validated
        ``scoring`` dict which maps the scorer key to the scorer callable.

    n_splits_ : int
        The number of cross-validation splits (folds/iterations).

    refit_time_ : float
        Seconds used for refitting the best model on the whole dataset.

        This is present only if ``refit`` is not False.

    Notes
    -----
    The parameters selected are those that maximize the score of the held-out
    data, according to the scoring parameter.

    If `n_jobs` was set to a value higher than one, the data is copied for each
    parameter setting(and not `n_jobs` times). This is done for efficiency
    reasons if individual jobs take very little time, but may raise errors if
    the dataset is large and not enough memory is available.  A workaround in
    this case is to set `pre_dispatch`. Then, the memory is copied only
    `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 *
    n_jobs`.

    See Also
    --------
    :class:`GridSearchCV`:
        Does exhaustive search over a grid of parameters.

    :class:`ParameterSampler`:
        A generator over parameter settings, constructed from
        param_distributions.

    i
   RX   i    s   2*n_jobss   raise-deprecatingc         C  st   | |  _  | |  _ | |  _ t t |  ƒ j d | d | d | d | d | d | d |	 d |
 d	 | d
 | d | ƒ d  S(   NRj   R€   Rd   R   R‚   Rƒ   R„   Ro   R…   Rf   R†   (   RQ   RR   RS   Rð   R&   R1   (   R.   Rj   RQ   RR   R€   Rd   R   R‚   Rƒ   R„   Ro   R…   RS   Rf   R†   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR1   Ù  s    			c         C  s&   | t  |  j |  j d |  j ƒƒ d S(   s1   Search n_iter candidates from param_distributionsRS   N(   R%   RQ   RR   RS   (   R.   R™   (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyRš   ç  s    (   RN   RO   RP   Rc   Rg   R1   Rš   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyR&   ª  s   ÿ .	
(I   RP   t
   __future__R    R   t   abcR   R   t   collectionsR   R   t	   functoolsR   R   t	   itertoolsR   R=   R·   RW   t   numpyRA   t   scipy.statsR	   t   baseR
   R   R   R   t   _splitR   t   _validationR   R   t
   exceptionsR   t   utils._joblibR   R   t	   externalsR   t   utilsR   t   utils.fixesR   R   R   R(   R   Rv   R   R)   t   utils.randomR   t   utils.validationR   R   t   utils.metaestimatorsR   t   utils.deprecationR   t   metrics.scorerR    R!   t   __all__RÚ   R#   R%   R$   Rx   Ry   t   with_metaclassR   R"   R&   (    (    (    s>   lib/python2.7/site-packages/sklearn/model_selection/_search.pyt   <module>   s\   		ˆoD		ÿ Éÿ I