ó
‡ˆ\c           @   s­   d  Z  d d l m Z d d l Z d d l 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
 „  Z e d „ Z d e	 f d „  ƒ  YZ d S(   s+   
Maximum likelihood covariance estimator.

iÿÿÿÿ(   t   divisionN(   t   linalgi   (   t   BaseEstimator(   t   check_array(   t   fast_logdet(   t   pairwise_distancesc         C   sW   | j  d } t j |  | ƒ t | ƒ } | | t j d t j ƒ 8} | d } | S(   s9  Computes the sample mean of the log_likelihood under a covariance model

    computes the empirical expected log-likelihood (accounting for the
    normalization terms and scaling), allowing for universal comparison (beyond
    this software package)

    Parameters
    ----------
    emp_cov : 2D ndarray (n_features, n_features)
        Maximum Likelihood Estimator of covariance

    precision : 2D ndarray (n_features, n_features)
        The precision matrix of the covariance model to be tested

    Returns
    -------
    sample mean of the log-likelihood
    i    i   g       @(   t   shapet   npt   sumR   t   logt   pi(   t   emp_covt	   precisiont   pt   log_likelihood_(    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   log_likelihood   s
    
c         C   sÂ   t  j |  ƒ }  |  j d k r3 t  j |  d ƒ }  n  |  j d d k rV t j d ƒ n  | r t  j |  j |  ƒ |  j d } n t  j	 |  j d d ƒ} | j d k r¾ t  j
 | g g ƒ } n  | S(   sB  Computes the Maximum likelihood covariance estimator


    Parameters
    ----------
    X : ndarray, 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 when working with data whose mean is almost, but not exactly
        zero.
        If False, data are centered before computation.

    Returns
    -------
    covariance : 2D ndarray, shape (n_features, n_features)
        Empirical covariance (Maximum Likelihood Estimator).

    i   iÿÿÿÿi    sB   Only one sample available. You may want to reshape your data arrayt   bias(   i   iÿÿÿÿ(   R   t   asarrayt   ndimt   reshapeR   t   warningst   warnt   dott   Tt   covt   array(   t   Xt   assume_centeredt
   covariance(    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   empirical_covariance2   s    #t   EmpiricalCovariancec           B   sb   e  Z d  Z e e d „ Z d „  Z d „  Z d	 d „ Z	 d	 d „ Z
 d e e d „ Z d „  Z RS(
   sÖ  Maximum likelihood covariance estimator

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

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

    assume_centered : bool
        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
    ----------
    location_ : array-like, shape (n_features,)
        Estimated location, i.e. the estimated mean.

    covariance_ : 2D ndarray, shape (n_features, n_features)
        Estimated covariance matrix

    precision_ : 2D ndarray, shape (n_features, n_features)
        Estimated pseudo-inverse matrix.
        (stored only if store_precision is True)

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

    c         C   s   | |  _  | |  _ d  S(   N(   t   store_precisionR   (   t   selfR   R   (    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   __init__ˆ   s    	c         C   s@   t  | ƒ } | |  _ |  j r3 t j | ƒ |  _ n	 d |  _ d S(   sr  Saves the covariance and precision estimates

        Storage is done accordingly to `self.store_precision`.
        Precision stored only if invertible.

        Parameters
        ----------
        covariance : 2D ndarray, shape (n_features, n_features)
            Estimated covariance matrix to be stored, and from which precision
            is computed.

        N(   R   t   covariance_R   R   t   pinvht
   precision_t   None(   R    R   (    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   _set_covarianceŒ   s
    		c         C   s+   |  j  r |  j } n t j |  j ƒ } | S(   s¹   Getter for the precision matrix.

        Returns
        -------
        precision_ : array-like
            The precision matrix associated to the current covariance object.

        (   R   R$   R   R#   R"   (   R    R   (    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   get_precision¢   s    		c         C   si   t  | ƒ } |  j r1 t j | j d ƒ |  _ n | j d ƒ |  _ t | d |  j ƒ} |  j | ƒ |  S(   sÏ  Fits the Maximum Likelihood Estimator 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    R   t   yR   (    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   fit±   s    	c         C   s2   t  | |  j d t ƒ} t | |  j ƒ  ƒ } | S(   sù  Computes the log-likelihood of a Gaussian data set with
        `self.covariance_` as an estimator of its covariance matrix.

        Parameters
        ----------
        X_test : array-like, shape = [n_samples, n_features]
            Test data of which we compute the likelihood, where n_samples is
            the number of samples and n_features is the number of features.
            X_test is assumed to be drawn from the same distribution than
            the data used in fit (including centering).

        y
            not used, present for API consistence purpose.

        Returns
        -------
        res : float
            The likelihood of the data set with `self.covariance_` as an
            estimator of its covariance matrix.

        R   (   R   R)   t   TrueR   R'   (   R    t   X_testR+   t   test_covt   res(    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   scoreÎ   s    t	   frobeniusc         C   s­   | |  j  } | d k r/ t j | d ƒ } nB | d k re t j t j t j | j | ƒ ƒ ƒ } n t d ƒ ‚ | r‹ | | j	 d } n  | rš | } n t j
 | ƒ } | S(   s>  Computes the Mean Squared Error between two covariance estimators.
        (In the sense of the Frobenius norm).

        Parameters
        ----------
        comp_cov : array-like, shape = [n_features, n_features]
            The covariance to compare with.

        norm : str
            The type of norm used to compute the error. Available error types:
            - 'frobenius' (default): sqrt(tr(A^t.A))
            - 'spectral': sqrt(max(eigenvalues(A^t.A))
            where A is the error ``(comp_cov - self.covariance_)``.

        scaling : bool
            If True (default), the squared error norm is divided by n_features.
            If False, the squared error norm is not rescaled.

        squared : bool
            Whether to compute the squared error norm or the error norm.
            If True (default), the squared error norm is returned.
            If False, the error norm is returned.

        Returns
        -------
        The Mean Squared Error (in the sense of the Frobenius norm) between
        `self` and `comp_cov` covariance estimators.

        R2   i   t   spectrals1   Only spectral and frobenius norms are implementedi    (   R"   R   R   t   amaxR   t   svdvalsR   R   t   NotImplementedErrorR   t   sqrt(   R    t   comp_covt   normt   scalingt   squaredt   errort   squared_normt   result(    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt
   error_normì   s     *		c         C   sZ   |  j  ƒ  } t | |  j t j d d … f d d d | ƒ} t j | t | ƒ f ƒ d S(   sù  Computes the squared Mahalanobis distances of given observations.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]
            The observations, the Mahalanobis distances of the which we
            compute. Observations are assumed to be drawn from the same
            distribution than the data used in fit.

        Returns
        -------
        dist : array, shape = [n_samples,]
            Squared Mahalanobis distances of the observations.

        Nt   metrict   mahalanobist   VIi   (   R'   R   R)   R   t   newaxisR   t   len(   R    R   R   t   dist(    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyRA      s    "N(   t   __name__t
   __module__t   __doc__R-   t   FalseR!   R&   R'   R%   R,   R1   R?   RA   (    (    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyR   Y   s   .		3(   RH   t
   __future__R    R   t   numpyR   t   scipyR   t   baseR   t   utilsR   t   utils.extmathR   t   metrics.pairwiseR   R   RI   R   R   (    (    (    sG   lib/python2.7/site-packages/sklearn/covariance/empirical_covariance_.pyt   <module>   s   		'