
    0Pht/                     ,   d 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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  eej        gej        gdd          d             Z edgdgdd          ddd            Z G d de          ZdS )z+
Maximum likelihood covariance estimator.

    N)linalg)metadata_routing   )config_context)BaseEstimator_fit_context)pairwise_distances)check_array)validate_params)fast_logdet)validate_data)emp_cov	precisionTprefer_skip_nested_validationc                     |j         d         }t          j        | |z             t          |          z   }||t          j        dt          j        z            z  z  }|dz  }|S )af  Compute the sample mean of the log_likelihood under a covariance model.

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

    Parameters
    ----------
    emp_cov : ndarray of shape (n_features, n_features)
        Maximum Likelihood Estimator of covariance.

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

    Returns
    -------
    log_likelihood_ : float
        Sample mean of the log-likelihood.
    r   r   g       @)shapenpsumr   logpi)r   r   plog_likelihood_s       h/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/covariance/_empirical_covariance.pylog_likelihoodr      sc    6 	Avg	1222[5K5KKOq26!be),,,,OsO    z
array-likeboolean)Xassume_centeredFr   c                   t          | dd          } | j        dk    rt          j        | d          } | j        d         dk    rt          j        d           |r)t          j        | j        |           | j        d         z  }nt          j	        | j        d          }|j        dk    rt          j
        |gg          }|S )a{  Compute the Maximum likelihood covariance estimator.

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

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

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

    Examples
    --------
    >>> from sklearn.covariance import empirical_covariance
    >>> X = [[1,1,1],[1,1,1],[1,1,1],
    ...      [0,0,0],[0,0,0],[0,0,0]]
    >>> empirical_covariance(X)
    array([[0.25, 0.25, 0.25],
           [0.25, 0.25, 0.25],
           [0.25, 0.25, 0.25]])
    F)	ensure_2densure_all_finite   )r$   r   zBOnly one sample available. You may want to reshape your data array)bias)r
   ndimr   reshaper   warningswarndotTcovarray)r   r   
covariances      r   empirical_covariancer0   <   s    H 	A%@@@Av{{Jq'""wqzQP	
 	
 	
  )VAC^^agaj0

VACa(((
!X
|n--
r   c                       e Zd ZU dZdej        iZdgdgdZee	d<   ddddZ
d	 Zd
 Z ed          dd            ZddZddZd ZdS )EmpiricalCovariancea  Maximum likelihood covariance estimator.

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

    Parameters
    ----------
    store_precision : bool, default=True
        Specifies 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
    ----------
    location_ : ndarray of shape (n_features,)
        Estimated location, i.e. the estimated mean.

    covariance_ : ndarray of shape (n_features, n_features)
        Estimated covariance matrix

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

    n_features_in_ : int
        Number of features seen during :term:`fit`.

        .. versionadded:: 0.24

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

        .. versionadded:: 1.0

    See Also
    --------
    EllipticEnvelope : An object for detecting outliers in
        a Gaussian distributed dataset.
    GraphicalLasso : Sparse inverse covariance estimation
        with an l1-penalized estimator.
    LedoitWolf : LedoitWolf Estimator.
    MinCovDet : Minimum Covariance Determinant
        (robust estimator of covariance).
    OAS : Oracle Approximating Shrinkage Estimator.
    ShrunkCovariance : Covariance estimator with shrinkage.

    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]])
    >>> rng = np.random.RandomState(0)
    >>> X = rng.multivariate_normal(mean=[0, 0],
    ...                             cov=real_cov,
    ...                             size=500)
    >>> cov = EmpiricalCovariance().fit(X)
    >>> cov.covariance_
    array([[0.7569..., 0.2818...],
           [0.2818..., 0.3928...]])
    >>> cov.location_
    array([0.0622..., 0.0193...])
    X_testr   store_precisionr   _parameter_constraintsTFc                "    || _         || _        d S Nr4   )selfr5   r   s      r   __init__zEmpiricalCovariance.__init__   s    ..r   c                     t          |          }|| _        | j        rt          j        |d          | _        dS d| _        dS )as  Saves the covariance and precision estimates

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

        Parameters
        ----------
        covariance : array-like of shape (n_features, n_features)
            Estimated covariance matrix to be stored, and from which precision
            is computed.
        Fcheck_finiteN)r
   covariance_r5   r   pinvh
precision_)r9   r/   s     r   _set_covariancez#EmpiricalCovariance._set_covariance   sI     !,,
% 	#$l:EJJJDOOO"DOOOr   c                 Z    | j         r| j        }nt          j        | j        d          }|S )zGetter for the precision matrix.

        Returns
        -------
        precision_ : array-like of shape (n_features, n_features)
            The precision matrix associated to the current covariance object.
        Fr<   )r5   r@   r   r?   r>   )r9   r   s     r   get_precisionz!EmpiricalCovariance.get_precision   s6      	KIIT%5EJJJIr   r   Nc                    t          | |          }| j        r%t          j        |j        d                   | _        n|                    d          | _        t          || j                  }|                     |           | S )a  Fit the maximum likelihood covariance estimator to X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
          Training data, where `n_samples` is the number of samples and
          `n_features` is the number of features.

        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
        r$   r   r    )	r   r   r   zerosr   	location_meanr0   rA   )r9   r   yr/   s       r   fitzEmpiricalCovariance.fit   sv    $ $"" 	'Xagaj11DNNVVAYYDN)!T=QRRR
Z(((r   c                     t          | |d          }t          || j        z
  d          }t          ||                                           }|S )a  Compute the log-likelihood of `X_test` under the estimated Gaussian model.

        The Gaussian model is defined by its mean and covariance matrix which are
        represented respectively by `self.location_` and `self.covariance_`.

        Parameters
        ----------
        X_test : array-like of 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 : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        res : float
            The log-likelihood of `X_test` with `self.location_` and `self.covariance_`
            as estimators of the Gaussian model mean and covariance matrix respectively.
        FresetTr    )r   r0   rF   r   rC   )r9   r3   rH   test_covress        r   scorezEmpiricalCovariance.score  sR    . tV5999'(?QUVVVXt'9'9';';<<
r   	frobeniusc                 T   || j         z
  }|dk    rt          j        |dz            }nT|dk    r?t          j        t	          j        t          j        |j        |                              }nt          d          |r||j	        d         z  }|r|}nt          j
        |          }|S )at  Compute the Mean Squared Error between two covariance estimators.

        Parameters
        ----------
        comp_cov : array-like of shape (n_features, n_features)
            The covariance to compare with.

        norm : {"frobenius", "spectral"}, default="frobenius"
            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, default=True
            If True (default), the squared error norm is divided by n_features.
            If False, the squared error norm is not rescaled.

        squared : bool, default=True
            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
        -------
        result : float
            The Mean Squared Error (in the sense of the Frobenius norm) between
            `self` and `comp_cov` covariance estimators.
        rP   r   spectralz1Only spectral and frobenius norms are implementedr   )r>   r   r   amaxr   svdvalsr+   r,   NotImplementedErrorr   sqrt)r9   comp_covnormscalingsquarederrorsquared_normresults           r   
error_normzEmpiricalCovariance.error_norm$  s    < 4++;6%(++LLZ76>"&%2H2H#I#IJJLL%C    	9'%+a.8L 	+!FFW\**Fr   c                 B   t          | |d          }|                                 }t          d          5  t          || j        t
          j        ddf         d|          }ddd           n# 1 swxY w Y   t          j        |t          |          f          dz  S )	a  Compute the squared Mahalanobis distances of given observations.

        Parameters
        ----------
        X : array-like of 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 : ndarray of shape (n_samples,)
            Squared Mahalanobis distances of the observations.
        FrK   T)assume_finiteNmahalanobis)metricVIr   )	r   rC   r   r	   rF   r   newaxisr(   len)r9   r   r   dists       r   ra   zEmpiricalCovariance.mahalanobisW  s     $///&&((	$/// 	 	%4>"*aaa-09  D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 z$Q	**a//s   -A00A47A4r8   )rP   TT)__name__
__module____qualname____doc__r   UNUSED-_EmpiricalCovariance__metadata_request__scorer6   dict__annotations__r:   rA   rC   r   rI   rO   r^   ra    r   r   r2   r2   t   s        C CL "*+;+B C &;%;$ $D   
 +/ / / / / /# # #*   \555   656   >1 1 1 1f0 0 0 0 0r   r2   )rj   r)   numpyr   scipyr   sklearn.utilsr    r   baser   r   metrics.pairwiser	   utilsr
   utils._param_validationr   utils.extmathr   utils.validationr   ndarrayr   r0   r2   ro   r   r   <module>r{      s               * * * * * *       . . . . . . . . 1 1 1 1 1 1       5 5 5 5 5 5 ' ' ' ' ' ' , , , , , , J<j\  #'    6 ^%;  #'   05 . . . . .b{0 {0 {0 {0 {0- {0 {0 {0 {0 {0r   