ó
‡ˆ\c           @   s  d  Z  d d l m Z d d l Z d d l Z d d l 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 d d e e d d „ Z d d e e d „ Z d d e e d d „ Z d e d d „ Z d e f d „  ƒ  YZ d S(   sn   
Robust location and covariance estimators.

Here are implemented estimators that are resistant to outliers.

iÿÿÿÿ(   t   divisionN(   t   linalg(   t   chi2i   (   t   empirical_covariancet   EmpiricalCovariancei   (   t   fast_logdet(   t   check_random_statet   check_arrayi   c         C   sF   t  j |  ƒ }  t | ƒ } t |  | d | d | d | d | d | ƒS(   s)  C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Data set in which we look for the n_support observations whose
        scatter matrix has minimum determinant.

    n_support : int, > n_samples / 2
        Number of observations to compute the robust estimates of location
        and covariance from.

    remaining_iterations : int, optional
        Number of iterations to perform.
        According to [Rouseeuw1999]_, two iterations are sufficient to get
        close to the minimum, and we never need more than 30 to reach
        convergence.

    initial_estimates : 2-tuple, optional
        Initial estimates of location and shape from which to run the c_step
        procedure:
        - initial_estimates[0]: an initial location estimate
        - initial_estimates[1]: an initial covariance estimate

    verbose : boolean, optional
        Verbose mode.

    cov_computation_method : callable, default empirical_covariance
        The function which will be used to compute the covariance.
        Must return shape (n_features, n_features)

    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`.

    Returns
    -------
    location : array-like, shape (n_features,)
        Robust location estimates.

    covariance : array-like, shape (n_features, n_features)
        Robust covariance estimates.

    support : array-like, shape (n_samples,)
        A mask for the `n_support` observations whose scatter matrix has
        minimum determinant.

    References
    ----------
    .. [Rouseeuw1999] A Fast Algorithm for the Minimum Covariance Determinant
        Estimator, 1999, American Statistical Association and the American
        Society for Quality, TECHNOMETRICS

    t   remaining_iterationst   initial_estimatest   verboset   cov_computation_methodt   random_state(   t   npt   asarrayR   t   _c_step(   t   Xt	   n_supportR   R	   R
   R   R   (    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyt   c_step   s    ;c         C   s  |  j  \ } } t j }	 t j | d t ƒ}
 | d  k rS t |
 | j | ƒ |  <nc | d } | d } t j	 | ƒ } |  | } t j
 | | ƒ | j d ƒ }	 t |
 t j |	 ƒ |  <|  |
 } | j d ƒ } | | ƒ } t | ƒ } t j | ƒ rt j	 | ƒ } n  t j } xé | | k  rü| d k rüt j | ƒ rü| } | } | } |
 } t j	 | ƒ } |  | } t j
 | | ƒ | j d d ƒ }	 t j | d t ƒ}
 t |
 t j |	 ƒ |  <|  |
 } | j d d ƒ } | | ƒ } t | ƒ } | d 8} qW|	 } t j
 |  | | ƒ |  | j d d ƒ }	 t j | ƒ rT| | | |
 |	 f } n  t j | | ƒ r| rxd | GHn  | | | |
 |	 f } nE | | k rÕt j d | | | | f t ƒ | | | | | f } n  | d k r| rïd GHn  | | | |
 |	 f } n  | S(   Nt   dtypei    i   t   axissN   Optimal couple (location, covariance) found before ending iterations (%d left)s³   Determinant has increased; this should not happen: log(det) > log(previous_det) (%.15f > %.15f). You may want to try with a higher value of support_fraction (current value: %.3f).s$   Maximum number of iterations reached(   t   shapeR   t   inft   zerost   boolt   Nonet   Truet   permutationR   t   pinvht   dott   sumt   argsortt   meanR   t   isinft   allcloset   warningst   warnt   RuntimeWarning(   R   R   R   R   R	   R
   R   t	   n_samplest
   n_featurest   distt   supportt   locationt
   covariancet	   precisiont
   X_centeredt	   X_supportt   dett   previous_dett   previous_locationt   previous_covariancet   previous_supportt   previous_distt   results(    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyR   a   sl    	



	
"
*		c         C   sÆ  t  | ƒ } |  j \ } }	 t | t j ƒ r6 t }
 nK t | t ƒ re t }
 | } | d j d } n t d | t	 | ƒ f ƒ ‚ g  } |
 sÕ x¬ t
 | ƒ D]4 } | j t |  | d | d | d | d | ƒƒ qš Wng xd t
 | ƒ D]V } | d | | d | f } | j t |  | d | d | d | d | d | ƒƒ qâ Wt | Œ  \ } } } } } t j | ƒ |  } t j | ƒ | } t j | ƒ | } t j | ƒ | } t j | ƒ | } | | | | f S(	   s)  Finds the best pure subset of observations to compute MCD from it.

    The purpose of this function is to find the best sets of n_support
    observations with respect to a minimization of their covariance
    matrix determinant. Equivalently, it removes n_samples-n_support
    observations to construct what we call a pure data set (i.e. not
    containing outliers). The list of the observations of the pure
    data set is referred to as the `support`.

    Starting from a random support, the pure data set is found by the
    c_step procedure introduced by Rousseeuw and Van Driessen in
    [RV]_.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Data (sub)set in which we look for the n_support purest observations.

    n_support : int, [(n + p + 1)/2] < n_support < n
        The number of samples the pure data set must contain.

    n_trials : int, nb_trials > 0 or 2-tuple
        Number of different initial sets of observations from which to
        run the algorithm.
        Instead of giving a number of trials to perform, one can provide a
        list of initial estimates that will be used to iteratively run
        c_step procedures. In this case:
        - n_trials[0]: array-like, shape (n_trials, n_features)
          is the list of `n_trials` initial location estimates
        - n_trials[1]: array-like, shape (n_trials, n_features, n_features)
          is the list of `n_trials` initial covariances estimates

    select : int, int > 0
        Number of best candidates results to return.

    n_iter : int, nb_iter > 0
        Maximum number of iterations for the c_step procedure.
        (2 is enough to be close to the final solution. "Never" exceeds 20).

    verbose : boolean, default False
        Control the output verbosity.

    cov_computation_method : callable, default empirical_covariance
        The function which will be used to compute the covariance.
        Must return shape (n_features, n_features)

    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`.

    See Also
    ---------
    c_step

    Returns
    -------
    best_locations : array-like, shape (select, n_features)
        The `select` location estimates computed from the `select` best
        supports found in the data set (`X`).

    best_covariances : array-like, shape (select, n_features, n_features)
        The `select` covariance estimates computed from the `select`
        best supports found in the data set (`X`).

    best_supports : array-like, shape (select, n_samples)
        The `select` best supports found in the data set (`X`).

    References
    ----------
    .. [RV] A Fast Algorithm for the Minimum Covariance Determinant
        Estimator, 1999, American Statistical Association and the American
        Society for Quality, TECHNOMETRICS

    i    sE   Invalid 'n_trials' parameter, expected tuple or  integer, got %s (%s)R   R
   R   R   i   R	   (   R   R   t
   isinstancet   numberst   Integralt   Falset   tupleR   t	   TypeErrort   typet   ranget   appendR   t   zipR   R   R   (   R   R   t   n_trialst   selectt   n_iterR
   R   R   R&   R'   t   run_from_estimatest   estimates_listt   all_estimatest   jR	   t   all_locs_subt   all_covs_subt   all_dets_subt   all_supports_subt
   all_ds_subt
   index_bestt   best_locationst   best_covariancest   best_supportst   best_ds(    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyt   select_candidates¸   s@    P		c   0      C   sî  t  | ƒ } t |  d d d d ƒ}  |  j \ } } | d k rc t t j d | | d ƒ ƒ } n t | | ƒ } | d k r1| | k  r¥t j t j |  ƒ ƒ } | | | | |  } t j	 | t j
 | ƒ k ƒ d }	 d | | |	 | |	 j ƒ  }
 t j | d t ƒ} |  |
 } t | t j t j | ƒ d ƒ |  <t j t j |  | ƒ g g ƒ } t j |
 g ƒ }
 t j | ƒ } t j | | ƒ | j d	 d ƒ } q1t j | d t ƒ} t j t j |  ƒ g g ƒ } t j t j |  ƒ g ƒ }
 |  |
 } t j | ƒ } t j | | ƒ | j d	 d ƒ } n  | d
 k r)| d k r)| d } | | } | j | ƒ } t t j | | t | ƒ ƒ ƒ } d
 } d } t d | | ƒ } | | } t j | | f ƒ } y t j | | | f ƒ } Wn5 t k
 r t j | | | f ƒ } d } d } n Xx¡ t | ƒ D]“ } | | } | | } |  | | | !} t | | | d | d d d | d | ƒ\ } } }  }  t j | | | d | ƒ }! | | |! <| | |! <q.Wt
 d | ƒ }" t t j |" | t | ƒ ƒ ƒ }# | d k rd }$ n d }$ | j | ƒ |"  }% t |  |% |# d | | f d |$ d | d | ƒ\ }& }' }( }) | d k  rÅ|& d }
 |' d } t j | d t ƒ} t j | ƒ } |( d | |% <|) d | |% <qÞt |  | d |& |' f d d d | d | ƒ\ }* }+ }, }) |* d }
 |+ d } |, d } |) d } nµ | d k rÞd } d }- t |  | d | d |- d d d | d | ƒ\ }. }/ }  }  t |  | d |. |/ f d d d | d | ƒ\ }* }+ }, }) |* d }
 |+ d } |, d } |) d } n  |
 | | | f S(   sF
  Estimates the Minimum Covariance Determinant matrix.

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

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
      The data matrix, with p features and n samples.

    support_fraction : float, 0 < support_fraction < 1
          The proportion of points to be included in the support of the raw
          MCD estimate. Default is None, which implies that the minimum
          value of support_fraction will be used within the algorithm:
          `[n_sample + n_features + 1] / 2`.

    cov_computation_method : callable, default empirical_covariance
        The function which will be used to compute the covariance.
        Must return shape (n_features, n_features)

    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`.

    Notes
    -----
    The FastMCD algorithm has been introduced by Rousseuw and Van Driessen
    in "A Fast Algorithm for the Minimum Covariance Determinant Estimator,
    1999, American Statistical Association and the American Society
    for Quality, TECHNOMETRICS".
    The principle is to compute robust estimates and random subsets before
    pooling them into a larger subsets, and finally into the full data set.
    Depending on the size of the initial sample, we have one, two or three
    such computation levels.

    Note that only raw estimates are returned. If one is interested in
    the correction and reweighting steps described in [RouseeuwVan]_,
    see the MinCovDet object.

    References
    ----------

    .. [RouseeuwVan] A Fast Algorithm for the Minimum Covariance
        Determinant Estimator, 1999, American Statistical Association
        and the American Society for Quality, TECHNOMETRICS

    .. [Butler1993] R. W. Butler, P. L. Davies and M. Jhun,
        Asymptotics For The Minimum Covariance Determinant Estimator,
        The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400

    Returns
    -------
    location : array-like, shape (n_features,)
        Robust location of the data.

    covariance : array-like, shape (n_features, n_features)
        Robust covariance of the features.

    support : array-like, type boolean, shape (n_samples,)
        A mask of the observations that have been used to compute
        the robust location and covariance estimates of the data set.

    t   ensure_min_samplesi   t	   estimatort   fast_mcdg      à?i   i    R   R   iô  i,  i
   RA   RB   R   R   iÜ  R@   i   N(    R   R   R   R   t   intR   t   ceilt   sortt   ravelt   wheret   minR    R   R   R   R   t   absR   t   vart   arrayR   R   R   R   t   onesR   t   floatt   maxt   MemoryErrorR=   RQ   t   arange(0   R   t   support_fractionR   R   R&   R'   R   t   X_sortedt   difft   halves_startR*   R)   R-   R+   R,   R(   t	   n_subsetst   n_samples_subsetst   samples_shufflet   h_subsett   n_trials_tott
   n_best_subR@   t
   n_best_tott   all_best_locationst   all_best_covariancest   it	   low_boundt
   high_boundt   current_subsett   best_locations_subt   best_covariances_subt   _t   subset_slicet   n_samples_mergedt   h_mergedt   n_best_mergedt	   selectiont   locations_mergedt   covariances_mergedt   supports_mergedt   dt   locations_fullt   covariances_fullt   supports_fullt   n_bestt   locations_bestt   covariances_best(    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyRT   4  sÎ    C$"
#"%
%






	

	





t	   MinCovDetc           B   sM   e  Z d  Z e e ƒ Z e e d d d „ Z	 d d „ Z
 d „  Z d „  Z RS(   s5  Minimum Covariance Determinant (MCD): robust estimator of covariance.

    The Minimum Covariance Determinant covariance estimator is to be applied
    on Gaussian-distributed data, but could still be relevant on data
    drawn from a unimodal, symmetric distribution. It is not meant to be used
    with multi-modal data (the algorithm used to fit a MinCovDet object is
    likely to fail in such a case).
    One should consider projection pursuit methods to deal with multi-modal
    datasets.

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

    Parameters
    ----------
    store_precision : bool
        Specify if the estimated precision is stored.

    assume_centered : bool
        If True, the support of the robust location and the covariance
        estimates is computed, and a covariance estimate is recomputed from
        it, without centering the data.
        Useful to work with data whose mean is significantly equal to
        zero but is not exactly zero.
        If False, the robust location and covariance are directly computed
        with the FastMCD algorithm without additional treatment.

    support_fraction : float, 0 < support_fraction < 1
        The proportion of points to be included in the support of the raw
        MCD estimate. Default is None, which implies that the minimum
        value of support_fraction will be used within the algorithm:
        [n_sample + n_features + 1] / 2

    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`.

    Attributes
    ----------
    raw_location_ : array-like, shape (n_features,)
        The raw robust estimated location before correction and re-weighting.

    raw_covariance_ : array-like, shape (n_features, n_features)
        The raw robust estimated covariance before correction and re-weighting.

    raw_support_ : array-like, shape (n_samples,)
        A mask of the observations that have been used to compute
        the raw robust estimates of location and shape, before correction
        and re-weighting.

    location_ : array-like, shape (n_features,)
        Estimated robust location

    covariance_ : array-like, shape (n_features, n_features)
        Estimated robust covariance matrix

    precision_ : array-like, shape (n_features, n_features)
        Estimated pseudo inverse matrix.
        (stored only if store_precision is True)

    support_ : array-like, shape (n_samples,)
        A mask of the observations that have been used to compute
        the robust estimates of location and shape.

    dist_ : array-like, shape (n_samples,)
        Mahalanobis distances of the training set (on which `fit` is called)
        observations.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import MinCovDet
    >>> from sklearn.datasets import make_gaussian_quantiles
    >>> real_cov = np.array([[.8, .3],
    ...                      [.3, .4]])
    >>> np.random.seed(0)
    >>> X = np.random.multivariate_normal(mean=[0, 0],
    ...                                   cov=real_cov,
    ...                                   size=500)
    >>> cov = MinCovDet(random_state=0).fit(X)
    >>> cov.covariance_ # doctest: +ELLIPSIS
    array([[0.7411..., 0.2535...],
           [0.2535..., 0.3053...]])
    >>> cov.location_
    array([0.0813... , 0.0427...])

    References
    ----------

    .. [Rouseeuw1984] `P. J. Rousseeuw. Least median of squares regression.
        J. Am Stat Ass, 79:871, 1984.`
    .. [Rousseeuw] `A Fast Algorithm for the Minimum Covariance Determinant
        Estimator, 1999, American Statistical Association and the American
        Society for Quality, TECHNOMETRICS`
    .. [ButlerDavies] `R. W. Butler, P. L. Davies and M. Jhun,
        Asymptotics For The Minimum Covariance Determinant Estimator,
        The Annals of Statistics, 1993, Vol. 21, No. 3, 1385-1400`

    c         C   s(   | |  _  | |  _ | |  _ | |  _ d  S(   N(   t   store_precisiont   assume_centeredRc   R   (   t   selfR‡   Rˆ   Rc   R   (    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyt   __init__i  s    			c         C   s_  t  | d d d d ƒ} t |  j ƒ } | j \ } } t j t j | j | ƒ ƒ d k j	 ƒ  | k rv t
 j d ƒ n  t | d |  j d |  j d	 | ƒ\ } } } }	 |  j rt j | ƒ } |  j | | d
 t ƒ} t j | ƒ }
 t j	 t j | |
 ƒ | d ƒ }	 n  | |  _ | |  _ | |  _ | |  _ | |  _ |	 |  _ |  j | ƒ |  j | ƒ |  S(   s¡  Fits a Minimum Covariance Determinant with the FastMCD algorithm.

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

        y
            not used, present for API consistence purpose.

        Returns
        -------
        self : object

        RR   i   RS   R†   g:Œ0âŽyE>sA   The covariance matrix associated to your dataset is not full rankRc   R   R   Rˆ   i   (   R   R   R   R   R   t   svdvalsR   R   t   TR   R#   R$   RT   Rc   t   _nonrobust_covarianceRˆ   R   R   R   t   raw_location_t   raw_covariance_t   raw_support_t	   location_t   support_t   dist_t   correct_covariancet   reweight_covariance(   R‰   R   t   yR   R&   R'   t   raw_locationt   raw_covariancet   raw_supportt   raw_distR,   (    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyt   fitp  s0    0			%						c         C   s   t  |  j ƒ } t j |  j ƒ } | | k  rQ t j |  j d ƒ rQ t d ƒ ‚ n  t j |  j ƒ t	 | j
 d ƒ j d ƒ } |  j | } |  j | _ | S(   sN  Apply a correction to raw Minimum Covariance Determinant estimates.

        Correction using the empirical correction factor suggested
        by Rousseeuw and Van Driessen in [RVD]_.

        Parameters
        ----------
        data : array-like, shape (n_samples, n_features)
            The data matrix, with p features and n samples.
            The data set must be the one which was used to compute
            the raw estimates.

        References
        ----------

        .. [RVD] `A Fast Algorithm for the Minimum Covariance
            Determinant Estimator, 1999, American Statistical Association
            and the American Society for Quality, TECHNOMETRICS`

        Returns
        -------
        covariance_corrected : array-like, shape (n_features, n_features)
            Corrected robust covariance estimate.

        i    sY   The covariance matrix of the support data is equal to 0, try to increase support_fractioni   g      à?(   t   lenR“   R   R   R’   R"   R   t
   ValueErrort   medianR   R   t   isf(   R‰   t   dataR&   R   t
   correctiont   covariance_corrected(    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyR”   ¡  s    !,c   	      C   sú   | j  \ } } |  j t | ƒ j d ƒ k  } |  j rH t j | ƒ } n | | j d ƒ } |  j | | d |  j ƒ} t j | d t	 ƒ} t
 | | <|  j | ƒ | |  _ | |  _ | |  j } t j t j | |  j ƒ  ƒ | d ƒ |  _ | | | f S(   s  Re-weight raw Minimum Covariance Determinant estimates.

        Re-weight observations using Rousseeuw's method (equivalent to
        deleting outlying observations from the data set before
        computing location and covariance estimates) described
        in [RVDriessen]_.

        Parameters
        ----------
        data : array-like, shape (n_samples, n_features)
            The data matrix, with p features and n samples.
            The data set must be the one which was used to compute
            the raw estimates.

        References
        ----------

        .. [RVDriessen] `A Fast Algorithm for the Minimum Covariance
            Determinant Estimator, 1999, American Statistical Association
            and the American Society for Quality, TECHNOMETRICS`

        Returns
        -------
        location_reweighted : array-like, shape (n_features, )
            Re-weighted robust location estimate.

        covariance_reweighted : array-like, shape (n_features, n_features)
            Re-weighted robust covariance estimate.

        support_reweighted : array-like, type boolean, shape (n_samples,)
            A mask of the observations that have been used to compute
            the re-weighted robust location and covariance estimates.

        gš™™™™™™?i    Rˆ   R   i   (   R   R“   R   RŸ   Rˆ   R   R   R    R   R   R   t   _set_covarianceR‘   R’   R   R   t   get_precision(	   R‰   R    R&   R'   t   maskt   location_reweightedt   covariance_reweightedt   support_reweightedR-   (    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyR•   È  s     #	
		%N(   t   __name__t
   __module__t   __doc__t   staticmethodR   R   R   R9   R   RŠ   R›   R”   R•   (    (    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyR†     s   d1	'(   R«   t
   __future__R    R#   R7   t   numpyR   t   scipyR   t   scipy.statsR   t    R   R   t   utils.extmathR   t   utilsR   R   R   R9   R   R   RQ   RT   R†   (    (    (    sC   lib/python2.7/site-packages/sklearn/covariance/robust_covariance.pyt   <module>   s.   
AUyÌ