ó
‡ˆ\c           @   sà   d  Z  d d l m Z d d l Z d d l Z d d l m Z m Z d d l	 m
 Z
 d d l m Z d	 d
 „ Z d e f d „  ƒ  YZ e d d „ Z e d d „ Z d e f d „  ƒ  YZ e d „ Z d e f d „  ƒ  YZ d S(   s²   
Covariance estimators using shrinkage.

Shrinkage corresponds to regularising `cov` using a convex combination:
shrunk_cov = (1-shrinkage)*cov + shrinkage*structured_estimate.

iÿÿÿÿ(   t   divisionNi   (   t   empirical_covariancet   EmpiricalCovariancei   (   t   xrange(   t   check_arraygš™™™™™¹?c         C   sb   t  |  ƒ }  |  j d } t j |  ƒ | } d | |  } | j d d | d … c | | 7<| S(   s’  Calculates a covariance matrix shrunk on the diagonal

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

    Parameters
    ----------
    emp_cov : array-like, shape (n_features, n_features)
        Covariance matrix to be shrunk

    shrinkage : float, 0 <= shrinkage <= 1
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Returns
    -------
    shrunk_cov : array-like
        Shrunk covariance.

    Notes
    -----
    The regularized (shrunk) covariance is given by:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    i    g      ð?Ni   (   R   t   shapet   npt   tracet   flat(   t   emp_covt	   shrinkaget
   n_featurest   mut
   shrunk_cov(    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyt   shrunk_covariance   s    $t   ShrunkCovariancec           B   s,   e  Z d  Z e e d d „ Z d d „ Z RS(   sË  Covariance estimator with shrinkage

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

    Parameters
    ----------
    store_precision : boolean, default True
        Specify if the estimated precision is stored

    assume_centered : boolean, default False
        If True, data are not centered before computation.
        Useful when working with data whose mean is almost, but not exactly
        zero.
        If False, data are centered before computation.

    shrinkage : float, 0 <= shrinkage <= 1, default 0.1
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Attributes
    ----------
    location_ : array-like, shape (n_features,)
        Estimated location, i.e. the estimated mean.

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

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

    shrinkage : float, 0 <= shrinkage <= 1
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import ShrunkCovariance
    >>> 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 = ShrunkCovariance().fit(X)
    >>> cov.covariance_ # doctest: +ELLIPSIS
    array([[0.7387..., 0.2536...],
           [0.2536..., 0.4110...]])
    >>> cov.location_
    array([0.0622..., 0.0193...])

    Notes
    -----
    The regularized covariance is given by:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    gš™™™™™¹?c         C   s,   t  t |  ƒ j d | d | ƒ | |  _ d  S(   Nt   store_precisiont   assume_centered(   t   superR   t   __init__R
   (   t   selfR   R   R
   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyR   €   s    c         C   s{   t  | ƒ } |  j r1 t j | j d ƒ |  _ n | j d ƒ |  _ t | d |  j ƒ} t | |  j	 ƒ } |  j
 | ƒ |  S(   s¾   Fits the shrunk covariance model
        according to the given training data and parameters.

        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

        i   i    R   (   R   R   R   t   zerosR   t	   location_t   meanR   R   R
   t   _set_covariance(   R   t   Xt   yt
   covariance(    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyt   fit†   s    	N(   t   __name__t
   __module__t   __doc__t   Truet   FalseR   t   NoneR   (    (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyR   A   s   >iè  c      	   C   s-  t  j |  ƒ }  t |  j ƒ d k r; |  j d d k r; d S|  j d k r_ t  j |  d ƒ }  n  |  j d d k r‚ t j d ƒ n  |  j \ } } | s­ |  |  j d ƒ }  n  t	 | | ƒ } |  d } t  j
 | d d ƒ| } t  j
 | ƒ | } d }	 d }
 xpt | ƒ D]b} xº t | ƒ D]¬ } t | | | | d ƒ } t | | | | d ƒ } |	 t  j
 t  j | j | | d d … | f ƒ ƒ 7}	 |
 t  j
 t  j |  j | |  d d … | f ƒ d ƒ 7}
 qWt | | | | d ƒ } |	 t  j
 t  j | j | | d d … | | d … f ƒ ƒ 7}	 |
 t  j
 t  j |  j | |  d d … | | d … f ƒ d ƒ 7}
 qWx§ t | ƒ D]™ } t | | | | d ƒ } |	 t  j
 t  j | j | | | d d … | f ƒ ƒ 7}	 |
 t  j
 t  j |  j | | |  d d … | f ƒ d ƒ 7}
 qW|
 t  j
 t  j |  j | | |  d d … | | d … f ƒ d ƒ 7}
 |
 | d }
 |	 t  j
 t  j | j | | | d d … | | d … f ƒ ƒ 7}	 d	 | | |	 | |
 } |
 d
 | | j
 ƒ  | | d } | | } t | | ƒ } | d k rd n | | } | S(   s¸  Estimates the shrunk Ledoit-Wolf covariance matrix.

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

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Data from which to compute the Ledoit-Wolf shrunk covariance shrinkage.

    assume_centered : bool
        If True, data are not centered before computation.
        Useful to work with data whose mean is significantly equal to
        zero but is not exactly zero.
        If False, data are centered before computation.

    block_size : int
        Size of the blocks into which the covariance matrix will be split.

    Returns
    -------
    shrinkage : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Notes
    -----
    The regularized (shrunk) covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    i   i   g        iÿÿÿÿi    sB   Only one sample available. You may want to reshape your data arrayt   axisNg      ð?g       @(   i   iÿÿÿÿ(   R   t   asarrayt   lenR   t   ndimt   reshapet   warningst   warnR   t   intt   sumR   t   slicet   dott   Tt   min(   R   R   t
   block_sizet	   n_samplesR   t   n_splitst   X2t   emp_cov_traceR   t   beta_t   delta_t   it   jt   rowst   colst   betat   deltaR
   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyt   ledoit_wolf_shrinkage©   sT    "(
6>@	?:	9+'$
c   	      C   s>  t  j |  ƒ }  t |  j ƒ d k rm |  j d d k rm | sP |  |  j ƒ  }  n  t  j |  d j ƒ  ƒ d f S|  j d k r­ t  j |  d
 ƒ }  t j	 d ƒ d } |  j
 } n |  j \ } } t |  d | d | ƒ} t |  d | ƒ} t  j t  j | ƒ ƒ | } d | | } | j d	 d	 | d … c | | 7<| | f S(   se  Estimates the shrunk Ledoit-Wolf covariance matrix.

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

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Data from which to compute the covariance estimate

    assume_centered : boolean, default=False
        If True, data are not centered before computation.
        Useful to work with data whose mean is significantly equal to
        zero but is not exactly zero.
        If False, data are centered before computation.

    block_size : int, default=1000
        Size of the blocks into which the covariance matrix will be split.
        This is purely a memory optimization and does not affect results.

    Returns
    -------
    shrunk_cov : array-like, shape (n_features, n_features)
        Shrunk covariance.

    shrinkage : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Notes
    -----
    The regularized (shrunk) covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    i   i   g        iÿÿÿÿsB   Only one sample available. You may want to reshape your data arrayR   R0   g      ð?N(   i   iÿÿÿÿ(   R   R$   R%   R   R   t
   atleast_2dR&   R'   R(   R)   t   sizeR=   R   R+   R   R   (	   R   R   R0   R1   R   R
   R	   R   R   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyt   ledoit_wolf  s$    &($t
   LedoitWolfc           B   s,   e  Z d  Z e e d d „ Z d d „ Z RS(   s/
  LedoitWolf Estimator

    Ledoit-Wolf is a particular form of shrinkage, where the shrinkage
    coefficient is computed using O. Ledoit and M. Wolf's formula as
    described in "A Well-Conditioned Estimator for Large-Dimensional
    Covariance Matrices", Ledoit and Wolf, Journal of Multivariate
    Analysis, Volume 88, Issue 2, February 2004, pages 365-411.

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

    Parameters
    ----------
    store_precision : bool, default=True
        Specify if the estimated precision is stored.

    assume_centered : bool, default=False
        If True, data are not centered before computation.
        Useful when working with data whose mean is almost, but not exactly
        zero.
        If False (default), data are centered before computation.

    block_size : int, default=1000
        Size of the blocks into which the covariance matrix will be split
        during its Ledoit-Wolf estimation. This is purely a memory
        optimization and does not affect results.

    Attributes
    ----------
    location_ : array-like, shape (n_features,)
        Estimated location, i.e. the estimated mean.

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

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

    shrinkage_ : float, 0 <= shrinkage <= 1
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.covariance import LedoitWolf
    >>> real_cov = np.array([[.4, .2],
    ...                      [.2, .8]])
    >>> np.random.seed(0)
    >>> X = np.random.multivariate_normal(mean=[0, 0],
    ...                                   cov=real_cov,
    ...                                   size=50)
    >>> cov = LedoitWolf().fit(X)
    >>> cov.covariance_ # doctest: +ELLIPSIS
    array([[0.4406..., 0.1616...],
           [0.1616..., 0.8022...]])
    >>> cov.location_
    array([ 0.0595... , -0.0075...])

    Notes
    -----
    The regularised covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features
    and shrinkage is given by the Ledoit and Wolf formula (see References)

    References
    ----------
    "A Well-Conditioned Estimator for Large-Dimensional Covariance Matrices",
    Ledoit and Wolf, Journal of Multivariate Analysis, Volume 88, Issue 2,
    February 2004, pages 365-411.

    iè  c         C   s,   t  t |  ƒ j d | d | ƒ | |  _ d  S(   NR   R   (   R   RA   R   R0   (   R   R   R   R0   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyR   ”  s    c         C   s…   t  | ƒ } |  j r1 t j | j d ƒ |  _ n | j d ƒ |  _ t | |  j d t d |  j	 ƒ\ } } | |  _
 |  j | ƒ |  S(   sÉ   Fits the Ledoit-Wolf shrunk covariance model
        according to the given training data and parameters.

        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

        i   i    R   R0   (   R   R   R   R   R   R   R   R@   R    R0   t
   shrinkage_R   (   R   R   R   R   R
   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyR   š  s    		N(   R   R   R   R    R!   R   R"   R   (    (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyRA   H  s   Kc         C   s}  t  j |  ƒ }  t |  j ƒ d k rm |  j d d k rm | sP |  |  j ƒ  }  n  t  j |  d j ƒ  ƒ d f S|  j d k r­ t  j |  d
 ƒ }  t j	 d ƒ d } |  j
 } n |  j \ } } t |  d | ƒ} t  j | ƒ | } t  j | d ƒ } | | d } | d | | d | } | d k r.d n t | | d ƒ }	 d |	 | }
 |
 j d	 d	 | d … c |	 | 7<|
 |	 f S(   s   Estimate covariance with the Oracle Approximating Shrinkage algorithm.

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Data from which to compute the covariance estimate.

    assume_centered : boolean
      If True, data are not centered before computation.
      Useful to work with data whose mean is significantly equal to
      zero but is not exactly zero.
      If False, data are centered before computation.

    Returns
    -------
    shrunk_cov : array-like, shape (n_features, n_features)
        Shrunk covariance.

    shrinkage : float
        Coefficient in the convex combination used for the computation
        of the shrunk estimate.

    Notes
    -----
    The regularised (shrunk) covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features

    The formula we used to implement the OAS is slightly modified compared
    to the one given in the article. See :class:`OAS` for more details.

    i   i   g        iÿÿÿÿsB   Only one sample available. You may want to reshape your data arrayR   g      ð?i    N(   i   iÿÿÿÿ(   R   R$   R%   R   R   R>   R&   R'   R(   R)   R?   R   R   R/   R   (   R   R   R1   R   R	   R   t   alphat   numt   denR
   R   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyt   oas½  s(    #(%$t   OASc           B   s   e  Z d  Z d d „ Z RS(   sE  Oracle Approximating Shrinkage Estimator

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

    OAS is a particular form of shrinkage described in
    "Shrinkage Algorithms for MMSE Covariance Estimation"
    Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010.

    The formula used here does not correspond to the one given in the
    article. In the original article, formula (23) states that 2/p is
    multiplied by Trace(cov*cov) in both the numerator and denominator, but
    this operation is omitted because for a large p, the value of 2/p is
    so small that it doesn't affect the value of the estimator.

    Parameters
    ----------
    store_precision : bool, default=True
        Specify if the estimated precision is stored.

    assume_centered : bool, default=False
        If True, data are not centered before computation.
        Useful when working with data whose mean is almost, but not exactly
        zero.
        If False (default), data are centered before computation.

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

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

    shrinkage_ : float, 0 <= shrinkage <= 1
      coefficient in the convex combination used for the computation
      of the shrunk estimate.

    Notes
    -----
    The regularised covariance is:

    (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features)

    where mu = trace(cov) / n_features
    and shrinkage is given by the OAS formula (see References)

    References
    ----------
    "Shrinkage Algorithms for MMSE Covariance Estimation"
    Chen et al., IEEE Trans. on Sign. Proc., Volume 58, Issue 10, October 2010.

    c         C   s|   t  | ƒ } |  j r1 t j | j d ƒ |  _ n | j d ƒ |  _ t | |  j d t ƒ\ } } | |  _	 |  j
 | ƒ |  S(   sÕ   Fits the Oracle Approximating Shrinkage covariance model
        according to the given training data and parameters.

        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

        i   i    R   (   R   R   R   R   R   R   R   RF   R    RB   R   (   R   R   R   R   R
   (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyR   5  s    		N(   R   R   R   R"   R   (    (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyRG   þ  s   5(   R   t
   __future__R    R(   t   numpyR   t   empirical_covariance_R   R   t   externals.six.movesR   t   utilsR   R   R   R!   R=   R@   RA   RF   RG   (    (    (    sD   lib/python2.7/site-packages/sklearn/covariance/shrunk_covariance_.pyt   <module>   s   	&h_@uA