`L im dZddlZddlmZmZddlZddlmZddl m Z ddl m Z m Z ddlmZd d lmZmZd Zd d dZe dge edd dgddd%dZGddeZe dgdge ed ddgddd&dZe ddgid d dddZGd d!eZe ddgid d d d"ZGd#d$eZy)'z Covariance estimators using shrinkage. Shrinkage corresponds to regularising `cov` using a convex combination: shrunk_cov = (1-shrinkage)*cov + shrinkage*structured_estimate. N)IntegralReal) _fit_context) check_array)Intervalvalidate_params) validate_data)EmpiricalCovarianceempirical_covariancect|jdk(rO|jddk(r=|s||jz }tj|dzjdfS|jd}t |||}t ||}tjtj||z }d|z |z}|jdd|dzxx||zz cc<||fS)z2Estimate the shrunk Ledoit-Wolf covariance matrix.rr assume_centered block_sizer?N) lenshapemeannp atleast_2dledoit_wolf_shrinkager sumtraceflat)Xrr n_features shrinkageemp_covmu shrunk_covs k/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/covariance/_shrunk_covariance.py _ledoit_wolfr%s 177|qQWWQZ1_AFFH A}}ad[[]+S00J& ?zI#1oFG ! "Z /B /W,JOO%zA~%&)b.8& y  Frct|jdk(rO|jddk(r=|s||jz }tj|dzjdfS|j\}}t ||}tj|dz}tj ||z }|dz}||z}|dz|||z z z} | dk(rdnt|| z d} d| z |z} | jdd|dzxx| |zz cc<| | fS)aaEstimate covariance with the Oracle Approximating Shrinkage algorithm. The formulation is based on [1]_. [1] "Shrinkage algorithms for MMSE covariance estimation.", Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O. IEEE Transactions on Signal Processing, 58(10), 5016-5029, 2010. https://arxiv.org/pdf/0907.4698.pdf rr rrrrN) rrrrrr rminr) rr n_samplesrr!alphar" mu_squarednumdenr r#s r$_oasr..s 177|qQWWQZ1_AFFH A}}ad[[]+S00GGIz"1oFG GGGQJ E ' Z 'BQJ * C q=UZ*%<< =CaxSsC%8I  /W,JOO%zA~%&)b.8& y  r&z array-likebothclosed)r!r Tprefer_skip_nested_validationc <t|d}|jd}d|z |z}tj|dd|z }tj|t t |j|j}|||ztj|zz }|S)aCalculate covariance matrices shrunk on the diagonal. Read more in the :ref:`User Guide `. Parameters ---------- emp_cov : array-like of shape (..., n_features, n_features) Covariance matrices to be shrunk, at least 2D ndarray. shrinkage : float, default=0.1 Coefficient in the convex combination used for the computation of the shrunk estimate. Range is [0, 1]. Returns ------- shrunk_cov : ndarray of shape (..., n_features, n_features) Shrunk covariance matrices. Notes ----- The regularized (shrunk) covariance is given by:: (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features) where `mu = trace(cov) / n_features`. Examples -------- >>> import numpy as np >>> from sklearn.datasets import make_gaussian_quantiles >>> from sklearn.covariance import empirical_covariance, shrunk_covariance >>> 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) >>> shrunk_covariance(empirical_covariance(X)) array([[0.739, 0.254], [0.254, 0.411]]) T)allow_ndr)axis1axis2axis) rrrr expand_dimstuplerangendimeye)r!r rr#r"s r$shrunk_covariancerAfs\'D1Gr"J /W,J '2 . ;B uRWWgll'C!D EB)b.266*#555J r&ceZdZUdZiej deedddgiZee d<dd d d fd Z e d ddZ xZ S)ShrunkCovariancea Covariance estimator with shrinkage. 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, 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. shrinkage : float, default=0.1 Coefficient in the convex combination used for the computation of the shrunk estimate. Range is [0, 1]. Attributes ---------- covariance_ : ndarray of shape (n_features, n_features) Estimated covariance matrix location_ : ndarray of shape (n_features,) Estimated location, i.e. the estimated mean. 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. 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. MinCovDet : Minimum Covariance Determinant (robust estimator of covariance). OAS : Oracle Approximating Shrinkage Estimator. Notes ----- The regularized covariance is given by: (1 - shrinkage) * cov + shrinkage * mu * np.identity(n_features) where mu = trace(cov) / n_features 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]]) >>> rng = np.random.RandomState(0) >>> X = rng.multivariate_normal(mean=[0, 0], ... cov=real_cov, ... size=500) >>> cov = ShrunkCovariance().fit(X) >>> cov.covariance_ array([[0.7387, 0.2536], [0.2536, 0.4110]]) >>> cov.location_ array([0.0622, 0.0193]) r rr r/r0_parameter_constraintsTF皙?)store_precisionrr c6t|||||_yN)rFr)super__init__r )selfrFrr __class__s r$rJzShrunkCovariance.__init__s# +_  #r&r2c.t||}|jr(tj|jd|_n|j d|_t||j}t||j}|j||S)aFit the shrunk covariance model 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_rr rAr _set_covariance)rKry covariances r$fitzShrunkCovariance.fitsw$ $ "   XXaggaj1DNVVAYDN)!T=Q=QR &z4>>B  Z( r&N)__name__ __module__ __qualname____doc__r rDrrdict__annotations__rJrrS __classcell__rLs@r$rCrCsgQf$  4 4$htQ&9:$D +/QT# 56r&rCbooleanleft)rrrc t|}t|jdk(r|jddk(ry|jdk(rt j |d}|jddk(rt jd|j\}}|s||jdz }t||z }|dz}t j|d|z }t j||z }d} d} t|D]b} t|D]} t|| z|| dzz} t|| z|| dzz}| t jt j|j| |dd|fz } | t jt j|j| |dd|fdzz } t|| z|| dzz} | t jt j|j| |dd||zdfz } | t jt j|j| |dd||zdfdzz } et|D]} t|| z|| dzz}| t jt j|j||zd|dd|fz } | t jt j|j||zd|dd|fdzz } | t jt j|j||zd|dd||zdfdzz } | |dzz} | t jt j|j||zd|dd||zdfz } d ||zz | |z | z z}| d |z|jzz ||dzzz}||z}t||}|dk(rd}|S||z }|S) aYEstimate the shrunk Ledoit-Wolf covariance matrix. Read more in the :ref:`User Guide `. Parameters ---------- X : array-like of shape (n_samples, n_features) Data from which to compute the Ledoit-Wolf shrunk covariance shrinkage. assume_centered : bool, default=False If True, data will not be centered before computation. Useful to work with data whose mean is significantly equal to zero but is not exactly zero. If False, data will be centered before computation. block_size : int, default=1000 Size of 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 Examples -------- >>> import numpy as np >>> from sklearn.covariance import ledoit_wolf_shrinkage >>> real_cov = np.array([[.4, .2], [.2, .8]]) >>> rng = np.random.RandomState(0) >>> X = rng.multivariate_normal(mean=[0, 0], cov=real_cov, size=50) >>> shrinkage_coefficient = ledoit_wolf_shrinkage(X) >>> shrinkage_coefficient np.float64(0.23) rr r)r r6rzBOnly one sample available. You may want to reshape your data arrayr:Nrg@)rrrr?rreshapewarningswarnrintrr>slicedotTr()rrrr)rn_splitsX2 emp_cov_tracer"beta_delta_ijrowscolsbetadeltar s r$rr!sh AA 177|qQWWQZ1_vv{ JJq' "wwqzQ P GGIz  q M : *+H ABFF2A&2M   +B E F 8_Px AAaq1u)=>Daq1u)=>D RVVBFF244:r!T'{;< -G HD S2X 1 1 33 3j2q56H HE ZE tU DQYI %)5LI r&rrclt||dj|}|j|jfS)a"Estimate the shrunk Ledoit-Wolf covariance matrix. Read more in the :ref:`User Guide `. Parameters ---------- X : array-like 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 to work with data whose mean is significantly equal to zero but is not exactly zero. If False, data will be centered before computation. block_size : int, default=1000 Size of blocks into which the covariance matrix will be split. This is purely a memory optimization and does not affect results. Returns ------- shrunk_cov : ndarray of 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 Examples -------- >>> import numpy as np >>> from sklearn.covariance import empirical_covariance, ledoit_wolf >>> real_cov = np.array([[.4, .2], [.2, .8]]) >>> rng = np.random.RandomState(0) >>> X = rng.multivariate_normal(mean=[0, 0], cov=real_cov, size=50) >>> covariance, shrinkage = ledoit_wolf(X) >>> covariance array([[0.44, 0.16], [0.16, 0.80]]) >>> shrinkage np.float64(0.23) F)rrrF) LedoitWolfrS covariance_ shrinkage_)rrr estimators r$ ledoit_wolfrxs?n' c!f   )"6"6 66r&ceZdZUdZiej deedddgiZee d<dd d d fd Z e d ddZ xZ S)rtaVLedoitWolf 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 `. Parameters ---------- store_precision : bool, default=True Specify if the estimated precision is stored. 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 (default), data will be centered before computation. block_size : int, default=1000 Size of 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 ---------- covariance_ : ndarray of shape (n_features, n_features) Estimated covariance matrix. location_ : ndarray of shape (n_features,) Estimated location, i.e. the estimated mean. precision_ : ndarray of shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) shrinkage_ : float Coefficient in the convex combination used for the computation of the shrunk estimate. Range is [0, 1]. 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. MinCovDet : Minimum Covariance Determinant (robust estimator of covariance). OAS : Oracle Approximating Shrinkage Estimator. ShrunkCovariance : Covariance estimator with shrinkage. 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. 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_ array([[0.4406, 0.1616], [0.1616, 0.8022]]) >>> cov.location_ array([ 0.0595 , -0.0075]) See also :ref:`sphx_glr_auto_examples_covariance_plot_covariance_estimation.py` and :ref:`sphx_glr_auto_examples_covariance_plot_lw_vs_oas.py` for more detailed examples. rr Nr^r0rDTFr_)rFrrc6t|||||_yrH)rIrJr)rKrFrrrLs r$rJzLedoitWolf.__init__As# +_  %r&r2c2t||}|jr(tj|jd|_n|j d|_t||j z d|j\}}||_ |j||S)aFit the Ledoit-Wolf shrunk covariance model 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 rTr) r rrrNrrOrr%rrvrPrKrrQrRr s r$rSzLedoitWolf.fitGs& $ "   XXaggaj1DNVVAYDN ,  !  I$ Z( r&rT)rUrVrWrXr rDrrrYrZrJrrSr[r\s@r$rtrtsgfP$  4 4$x!T&AB$D +/RV% 56r&rtcht|j|}|j|jfS)a Estimate covariance with the Oracle Approximating Shrinkage. Read more in the :ref:`User Guide `. Parameters ---------- X : array-like 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 to work with data whose mean is significantly equal to zero but is not exactly zero. If False, data will be centered before computation. Returns ------- shrunk_cov : array-like of 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 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 [1]_). The shrinkage formulation implemented here differs from Eq. 23 in [1]_. In the original article, formula (23) states that 2/p (p being the number of features) 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. References ---------- .. [1] :arxiv:`"Shrinkage algorithms for MMSE covariance estimation.", Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O. IEEE Transactions on Signal Processing, 58(10), 5016-5029, 2010. <0907.4698>` Examples -------- >>> import numpy as np >>> from sklearn.covariance import oas >>> rng = np.random.RandomState(0) >>> real_cov = [[.8, .3], [.3, .4]] >>> X = rng.multivariate_normal(mean=[0, 0], cov=real_cov, size=500) >>> shrunk_cov, shrinkage = oas(X) >>> shrunk_cov array([[0.7533, 0.2763], [0.2763, 0.3964]]) >>> shrinkage np.float64(0.0195) r)OASrSrurv)rrrws r$oasris7B' c!f  )"6"6 66r&c0eZdZdZedddZy)r~aAOracle Approximating Shrinkage Estimator. 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, data will not be centered before computation. Useful when working with data whose mean is almost, but not exactly zero. If False (default), data will be centered before computation. Attributes ---------- covariance_ : ndarray of shape (n_features, n_features) Estimated covariance matrix. location_ : ndarray of shape (n_features,) Estimated location, i.e. the estimated mean. precision_ : ndarray of shape (n_features, n_features) Estimated pseudo inverse matrix. (stored only if store_precision is True) shrinkage_ : float coefficient in the convex combination used for the computation of the shrunk estimate. Range is [0, 1]. 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. MinCovDet : Minimum Covariance Determinant (robust estimator of covariance). ShrunkCovariance : Covariance estimator with shrinkage. 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 [1]_). The shrinkage formulation implemented here differs from Eq. 23 in [1]_. In the original article, formula (23) states that 2/p (p being the number of features) 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. References ---------- .. [1] :arxiv:`"Shrinkage algorithms for MMSE covariance estimation.", Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O. IEEE Transactions on Signal Processing, 58(10), 5016-5029, 2010. <0907.4698>` Examples -------- >>> import numpy as np >>> from sklearn.covariance import OAS >>> 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) >>> oas = OAS().fit(X) >>> oas.covariance_ array([[0.7533, 0.2763], [0.2763, 0.3964]]) >>> oas.precision_ array([[ 1.7833, -1.2431 ], [-1.2431, 3.3889]]) >>> oas.shrinkage_ np.float64(0.0195) See also :ref:`sphx_glr_auto_examples_covariance_plot_covariance_estimation.py` and :ref:`sphx_glr_auto_examples_covariance_plot_lw_vs_oas.py` for more detailed examples. Tr2Nct||}|jr(tj|jd|_n|j d|_t||j z d\}}||_|j||S)aFit the Oracle Approximating Shrinkage covariance model 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 rTr) r rrrNrrOrr.rvrPr|s r$rSzOAS.fitsv" $ "   XXaggaj1DNVVAYDN $Q%7 N I# Z( r&rT)rUrVrWrXrrSr&r$r~r~s"fP56r&r~)rE)Fr_)rXrbnumbersrrnumpyrbaserutilsrutils._param_validationrr utils.validationr r r r%r.rArCrrxrtrr~rr&r$rs:"?,7!* %0!p >tQ&9:#' //d|*|D^%;!T&AB #' ggT<."'',97 97xR$Rl<."'$@7 @7FF Fr&