`L i 0 dZddlZddlZddlmZddlmZddlm Z ddl m Z m Z ddl mZdd lmZdd lmZdd lmZdd lmZeej.gej.gd ddZedgdgdddddZGdde Zy)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 precisionTprefer_skip_nested_validationc|jd}tj||z t|z}||tjdtj zzz}|dz}|S)afCompute 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. rrg@)shapenpsumr logpi)rrplog_likelihood_s n/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/covariance/_empirical_covariance.pylog_likelihoodrsb6 Avvg 122[5KKOq266!bee),,,OsO z array-likeboolean)Xassume_centeredFrct|dd}|jdk(rtj|d}|jddk(rt j d|r1tj|j||jdz }n!tj|jd}|jdk(rtj|gg}|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_2densure_all_finite)r$rzBOnly one sample available. You may want to reshape your data array)bias) r ndimrreshaperwarningswarndotTcovarray)rr covariances rempirical_covariancer0<sH A%@Avv{ JJq' "wwqzQ P VVACC^aggaj0 VVACCa( !XX |n- rceZdZUdZdej iZdgdgdZee d<ddddZ d Z d Z e d dd ZddZddZdZy )EmpiricalCovarianceaMaximum likelihood covariance estimator. Read more in the :ref:`User Guide `. 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_testrstore_precisionr_parameter_constraintsTFc ||_||_yNr4)selfr5rs r__init__zEmpiricalCovariance.__init__s..rct|}||_|jrtj|d|_yd|_y)asSaves 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_r5rpinvh precision_)r9r/s r_set_covariancez#EmpiricalCovariance._set_covariances8!, %   $ll:EJDO"DOrc||jr|j}|Stj|jd}|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<)r5r@rr?r>)r9rs r get_precisionz!EmpiricalCovariance.get_precisions<   I T%5%5EJIrrNct||}|jr(tj|jd|_n|j d|_t||j}|j||S)aFit 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$rr ) r rrzerosr location_meanr0rA)r9ryr/s rfitzEmpiricalCovariance.fitse$ $ "   XXaggaj1DNVVAYDN)!T=Q=QR  Z( rct||d}t||jz d}t||j }|S)aCompute 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. FresetTr )r r0rFrrC)r9r3rHtest_covress rscorezEmpiricalCovariance.scoresB.tV59'(?QUVXt'9'9';< rcl||jz }|dk(rtj|dz}nW|dk(rGtjt j tj |j|}n td|r||jdz }|r|}|Stj|}|S)atCompute 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. frobeniusrspectralz1Only spectral and frobenius norms are implementedr) r>rramaxrsvdvalsr+r,NotImplementedErrorrsqrt)r9comp_covnormscalingsquarederror squared_normresults r error_normzEmpiricalCovariance.error_norm$s<4+++ ; 66%(+L Z 776>>"&&%2H#IJL%C  '%++a.8L !F WW\*F rc"t||d}|j}td5t||jt j ddfd|}dddt jt|fdzS#1swY,xYw) aCompute the squared Mahalanobis distances of given observations. For a detailed example of how outliers affects the Mahalanobis distance, see :ref:`sphx_glr_auto_examples_covariance_plot_mahalanobis_distances.py`. 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. FrKT) assume_finiteN mahalanobis)metricVIr) r rCrr rFrnewaxisr(len)r9rrdists rrazEmpiricalCovariance.mahalanobisWs$ $ /&&( $ / %4>>"**a-09D  zz$Q *a//   s /BBr8)rQTT)__name__ __module__ __qualname____doc__rUNUSED-_EmpiricalCovariance__metadata_request__scorer6dict__annotations__r:rArCrrIrOr^rarrr2r2tswCL"*+;+B+B C&;%;$D +//#* 566>1f0rr2)rjr)numpyrscipyr sklearn.utilsrrbaserrmetrics.pairwiser utilsr utils._param_validationr utils.extmathr utils.validationr ndarrayrr0r2rorrr{s*.15',JJ<jj\#' 6^%;#' 05..b~0-~0r