`L icdZddlZddlmZmZddlZddlmZddl m Z ddl m Z ddl mZmZdd lmZdd lmZdd lmZd d lmZmZdddedfdZdddefdZd ddedfdZdedfdZGddeZy)zn Robust location and covariance estimators. Here are implemented estimators that are resistant to outliers. N)IntegralReal)linalg)chi2) _fit_context) check_arraycheck_random_state)Interval) fast_logdet) validate_data)EmpiricalCovarianceempirical_covarianceFc ftj|}t|}t|||||||S)aSC_step procedure described in [Rouseeuw1984]_ aiming at computing MCD. Parameters ---------- X : array-like of 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 Number of observations to compute the robust estimates of location and covariance from. This parameter must be greater than `n_samples / 2`. remaining_iterations : int, default=30 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 : tuple of shape (2,), default=None 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 : bool, default=False Verbose mode. cov_computation_method : callable, default=:func:`sklearn.covariance.empirical_covariance` The function which will be used to compute the covariance. Must return array of shape (n_features, n_features). random_state : int, RandomState instance or None, default=None Determines the pseudo random number generator for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. Returns ------- location : ndarray of shape (n_features,) Robust location estimates. covariance : ndarray of shape (n_features, n_features) Robust covariance estimates. support : ndarray of 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 remaining_iterationsinitial_estimatesverbosecov_computation_method random_state)npasarrayr _c_step)X n_supportrrrrrs k/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/covariance/_robust_covariance.pyc_stepr!s>B 1 A%l3L  1+5! c|j\}}tj} ||j|d|} nh|d} |d} t j | } || z }tj || |zjd} tj| |dz d|} || }|jd} ||} t| }tj|rt j | } tj}||kr|dkDrtj|s| }| }|}| }t j | } || z }tj || |zjd} tj| |dz d|} || }|jd} ||} t| }|dz}||kr|dkDrtj|s| }tj || z  || z zjd} tj|r| | || | f}tj||r|rtd|z| | || | f}n/||kDr*tjd||||z fzt ||f}|dk(r|r td| | || | f}\} } }} } tj"| |j%t&}| | ||| fS)NrraxiszNOptimal couple (location, covariance) found before ending iterations (%d left)zDeterminant 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).z$Maximum number of iterations reached) minlength)shaperinf permutationrpinvhdotsum argpartitionmeanr isinfallcloseprintwarningswarnRuntimeWarningbincountastypebool)rrrrrrr n_samples n_featuresdistsupport_indiceslocation covariance precision X_centered X_supportdet previous_detprevious_locationprevious_covarianceprevious_support_indices previous_distresultssupports rrrosGGIz 66D &229=jyI%Q'&q) LL, \ z9- :??B//$ A >z J/"I~~a H' 2J j !C xx}LL, 66L !5!9"((3-$( #2 LL, \ z9- :??Q?G//$ A >z Jo& >>q>)+I6 *%!#  !5!9"((3-&M FF1x< +q8| < A Aq A ID xx}J_dB {{3 %  /2FH J_dB |   6L)i"78  9       $   q  8 9J_dB7>4Hj#kk/Y?FFtLG Zgt 33r c t|}t|trd}nBt|trd}|} | djd}nt d|dt |dg} |s1t|D]"} | jt||||||$nAt|D]3}  d| | d| f} | jt|||| ||| 5t| \} }}}}tj|d |}tj| |}tj||}tj||}tj||}||||fS) a 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 of shape (n_samples, n_features) Data (sub)set in which we look for the n_support purest observations. n_support : int The number of samples the pure data set must contain. This parameter must be in the range `[(n + p + 1)/2] < n_support < n`. n_trials : int or tuple of shape (2,) Number of different initial sets of observations from which to run the algorithm. This parameter should be a strictly positive integer. 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, default=1 Number of best candidates results to return. This parameter must be a strictly positive integer. n_iter : int, default=30 Maximum number of iterations for the c_step procedure. (2 is enough to be close to the final solution. "Never" exceeds 20). This parameter must be a strictly positive integer. verbose : bool, default=False Control the output verbosity. cov_computation_method : callable, default=:func:`sklearn.covariance.empirical_covariance` The function which will be used to compute the covariance. Must return an array of shape (n_features, n_features). random_state : int, RandomState instance or None, default=None Determines the pseudo random number generator for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. See Also --------- c_step Returns ------- best_locations : ndarray of shape (select, n_features) The `select` location estimates computed from the `select` best supports found in the data set (`X`). best_covariances : ndarray of shape (select, n_features, n_features) The `select` covariance estimates computed from the `select` best supports found in the data set (`X`). best_supports : ndarray of 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 FTrz>Invalid 'n_trials' parameter, expected tuple or integer, got z ())rrrrrrN)r isinstancertupler% TypeErrortyperangeappendrziprargsortr)rrn_trialsselectn_iterrrrrun_from_estimatesestimates_list all_estimatesjr all_locs_sub all_covs_sub all_dets_suball_supports_sub all_ds_sub index_bestbest_locationsbest_covariances best_supportsbest_dss rselect_candidatesrbsr&l3L(H%" He $!!!!$**1-h )  M x A  )/#+A!-   x A!/!21!5~a7H7K L   )/&7#+A!-  NQ NJL, .> L)'62JZZ -j9Nzz,/ ;JJ/0`. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix, with p features and n samples. support_fraction : float, default=None 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_samples + n_features + 1) / 2 * n_samples`. This parameter must be in the range (0, 1). cov_computation_method : callable, default=:func:`sklearn.covariance.empirical_covariance` The function which will be used to compute the covariance. Must return an array of shape (n_features, n_features). random_state : int, RandomState instance or None, default=None Determines the pseudo random number generator for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. Returns ------- location : ndarray of shape (n_features,) Robust location of the data. covariance : ndarray of shape (n_features, n_features) Robust covariance of the features. support : ndarray of shape (n_samples,), dtype=bool A mask of the observations that have been used to compute the robust location and covariance estimates of the data set. 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 rfast_mcdensure_min_samples estimatorN?rrdtypeTr"ii, )rRrSrri)rQrRrrr)rQrRrSrr)r r r%minintrceilsortravelwherer,zerosr5rPabsrvararrayrr(r)r*onesr'floatmax MemoryErrorrMrbarange)0rsupport_fractionrrr6r7rX_sorteddiff halves_startr:rFr=r;r<r8 n_subsetsn_samples_subsetssamples_shuffleh_subset n_trials_tot n_best_subrQ n_best_totall_best_locationsall_best_covariancesi low_bound high_boundcurrent_subsetbest_locations_subbest_covariances_sub_ subset_slicen_samples_mergedh_merged n_best_merged selectionlocations_mergedcovariances_mergedsupports_mergeddlocations_fullcovariances_full supports_fulln_bestlocations_bestcovariances_bests0 rrdrdgsL&l3LA!zBAGGIzBGGC9z+AA+E$FGH)T (945 Q y wwrxx{+HIJ'(3Li)6K*MMD88DBFF4L$89!? #%88ZZ,P#Q y! FA--I"%66JyDEN=N!'=)> :  4a99Q^a!ez5IJL/A | ,1E  . F$tY/rww/9uY?O3OPQR t MM ,,Y78I9IJ CT iL (*>? #9% D @,oq t '*H+A.Jhhy5G88I&D!0!3GI dDOBS*,>?'=) B >N,mQ&a(H)!,J#A&GQ4D a1B #9%2 .(!Q>O $&67#9% > :(-"!$%a( "t Z$ ..w J#%88ZZ,P#Q J  sR;;%S$#S$ceZdZUdZiej eeddddgdgdZee d <e e Z d d ddd d Z ed ddZdZdZy) MinCovDetaNMinimum 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 `. Parameters ---------- store_precision : bool, default=True Specify if the estimated precision is stored. assume_centered : bool, default=False 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, default=None 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_samples + n_features + 1) / 2 * n_samples`. The parameter must be in the range (0, 1]. random_state : int, RandomState instance or None, default=None Determines the pseudo random number generator for shuffling the data. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. Attributes ---------- raw_location_ : ndarray of shape (n_features,) The raw robust estimated location before correction and re-weighting. raw_covariance_ : ndarray of shape (n_features, n_features) The raw robust estimated covariance before correction and re-weighting. raw_support_ : ndarray of 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_ : ndarray of shape (n_features,) Estimated robust location. For an example of comparing raw robust estimates with the true location and covariance, refer to :ref:`sphx_glr_auto_examples_covariance_plot_robust_vs_empirical_covariance.py`. covariance_ : ndarray of shape (n_features, n_features) Estimated robust covariance matrix. precision_ : ndarray of shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) support_ : ndarray of shape (n_samples,) A mask of the observations that have been used to compute the robust estimates of location and shape. dist_ : ndarray of shape (n_samples,) Mahalanobis distances of the training set (on which :meth:`fit` is called) observations. 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. EmpiricalCovariance : Maximum likelihood covariance estimator. GraphicalLasso : Sparse inverse covariance estimation with an l1-penalized estimator. GraphicalLassoCV : Sparse inverse covariance with cross-validated choice of the l1 penalty. LedoitWolf : LedoitWolf Estimator. OAS : Oracle Approximating Shrinkage Estimator. ShrunkCovariance : Covariance estimator with shrinkage. 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 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]]) >>> rng = np.random.RandomState(0) >>> X = rng.multivariate_normal(mean=[0, 0], ... cov=real_cov, ... size=500) >>> cov = MinCovDet(random_state=0).fit(X) >>> cov.covariance_ array([[0.7411, 0.2535], [0.2535, 0.3053]]) >>> cov.location_ array([0.0813 , 0.0427]) rrright)closedNr)r{r_parameter_constraintsTFstore_precisionassume_centeredr{rc<||_||_||_||_yNr)selfrrr{rs r__init__zMinCovDet.__init__s$ /. 0(r )prefer_skip_nested_validationct||dd}t|j}|j\}}t j t j|j|dkDj|k7rtjdt||j|j|\}}}} |jrmt j |}|j||d}t j"|} t jt j|| |zd } ||_||_||_||_||_| |_|j1||j3||S) aFit a Minimum Covariance Determinant with the FastMCD algorithm. 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. rrreg:0yE>zAThe covariance matrix associated to your dataset is not full rank)r{rrTrr)r r rr%rsvdvalsrr)Tr*r0r1rdr{_nonrobust_covariancerrrr( raw_location_raw_covariance_ raw_support_ location_support_dist_correct_covariancereweight_covariance) rryrr6r7 raw_locationraw_covariance raw_supportraw_distr<s rfitz MinCovDet.fitsQ$ $a; O)$*;*;< ! : NN266!##q> *T 1 6 6 8J F MMS ?G !22#'#=#=% ? ; nk8   88J/L!77+8N ^4IvvbffQ 2Q6:H)-'%#   "   # r ct|j}tj|j}||kr+tj |j dr tdtj|jt|jdjdz }|j |z}|xj|zc_|S)aLApply 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 of 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. Returns ------- covariance_corrected : ndarray of shape (n_features, n_features) Corrected robust covariance estimate. References ---------- .. [RVD] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS rzYThe covariance matrix of the support data is equal to 0, try to increase support_fractionrrh) lenrrr*rr.r ValueErrormedianrr%isf)rdatar6r correctioncovariance_correcteds rrzMinCovDet.correct_covariances8 O FF4==) y R[[1E1Eq%IB YYtzz*T$**Q--@-D-DS-II #33j@ j ##r c@|j\}}|jt|jdk}|jrt j |}n||jd}|j|||j}t j |t}d||<|j|||_ ||_ ||jz }t jt j||j|zd|_|||fS)aRe-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 of 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. Returns ------- location_reweighted : ndarray of shape (n_features,) Re-weighted robust location estimate. covariance_reweighted : ndarray of shape (n_features, n_features) Re-weighted robust covariance estimate. support_reweighted : ndarray of shape (n_samples,), dtype=bool A mask of the observations that have been used to compute the re-weighted robust location and covariance estimates. References ---------- .. [RVDriessen] A Fast Algorithm for the Minimum Covariance Determinant Estimator, 1999, American Statistical Association and the American Society for Quality, TECHNOMETRICS g?rrriTr)r%rrrrrrrr,rr5_set_covariancerrr*r) get_precision) rrr6r7masklocation_reweightedcovariance_reweightedsupport_reweightedr=s rrzMinCovDet.reweight_covariance8sD!%  :zzD,0077   "$((:"6 "&t*//!"4  $ : : J(<(<!;!  XXit<#'4  23,* DNN* VVBFF:t/A/A/CDzQSTU "$9;MMMr r)__name__ __module__ __qualname____doc__rrr rdict__annotations__ staticmethodrrrrrrrr rrrEs~@$  4 4$%dAqA4H'($D ))=>  )5363j&$P2Nr r)rr0numbersrrnumpyrscipyr scipy.statsrbaserutilsr r utils._param_validationr utils.extmathr utils.validationr _empirical_covariancerrrrrbrdrrr rrs"3.',L /Kd /c4T /ODh/ [/|eN#eNr