`L i)dZddlmZmZmZddlmZmZddlZ ddl m Z ddl m Z ddlmZdd lmZdd lmZdd lmZdd lmZmZdd lmZmZmZddlmZmZm Z m!Z!ddl"m#Z#m$Z$ddl%m&Z&m'Z'ddl(m)Z)dZ*dZ+Gdde)Z,y)zPrincipal Component Analysis.)lgammalogsqrt)IntegralRealN)linalg)issparse)svds) _fit_context)check_random_state)_init_arpack_v0)_convert_to_numpy get_namespace)Interval RealNotInt StrOptions)_randomized_svd fast_logdet stable_cumsumsvd_flip)_implicit_column_offsetmean_variance_axis)check_is_fitted validate_data)_BasePCAc t|\}}|jd}d|cxkr|kstdtdd}||dz |kr |j S| t dz}t d|dzD];}|t ||z dzdz t |j||z dzzdz z z }=|j|j |d|} | |zdz } t||j||d||z z } t |  |z||z zdz } ||z||dzzdz z } t d|jz| |zzdz } d}|j|d }| |||t |D]X}t |dz|jdD]7}|t ||||z d||z d||z z zt |zz }9Z|| z| z| z|dz z |t |zdz z }|S) ajCompute the log-likelihood of a rank ``rank`` dataset. The dataset is assumed to be embedded in gaussian noise of shape(n, dimf) having spectrum ``spectrum``. This implements the method of T. P. Minka. Parameters ---------- spectrum : ndarray of shape (n_features,) Data spectrum. rank : int Tested rank value. It should be strictly lower than n_features, otherwise the method isn't specified (division by zero in equation (31) from the paper). n_samples : int Number of samples. Returns ------- ll : float The log-likelihood. References ---------- This implements the method of `Thomas P. Minka: Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604 `_ rrz0the tested rank should be in [1, n_features - 1]gV瞯<@N?Tcopy) rshape ValueErrorinfrrangerpisummaxasarray)spectrumrank n_samplesxp_ n_featuresepspuiplvpvmpppa spectrum_jlls `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sklearn/decomposition/_pca.py_assess_dimensionr?sa: ( #EB"J  !z !KLL "KLL CqC w S B 1dQh   JNQ&#- .RUUzA~PQ?Q1RUX1X X  x' (B y3 B C(J,=>?A a&9  T 1 2S 8BTDD3J/#55A S255[ QX & ,B B 8$ /I!"Id: 4[q1uhnnQ/0 A #!x{*sYq\/AC)TU,DV/VWI B  b2 R#X %s9~(=(C CB Ict|\}}|j|}|j |d<td|jdD]}t |||||<|j |S)zuInfers the dimension of a dataset with a given spectrum. The returned value will be in [1, n_features - 1]. rr)r empty_liker&r'r$r?argmax)r,r.r/r0r=r-s r>_infer_dimensionrDcsp ( #EB x B VVGBqEa*+@$XtY?4@ 99R=r@c ~eZdZUdZeedddeedddedhdgd gd gehd geedddged heedddgeedddgehd gd gd Z e e d< dddd dd dd dddZ e dddZe dddZdZdZdZdZddZfdZxZS) PCAa$+Principal component analysis (PCA). Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. The input data is centered but not scaled for each feature before applying the SVD. It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, depending on the shape of the input data and the number of components to extract. With sparse inputs, the ARPACK implementation of the truncated SVD can be used (i.e. through :func:`scipy.sparse.linalg.svds`). Alternatively, one may consider :class:`TruncatedSVD` where the data are not centered. Notice that this class only supports sparse inputs for some solvers such as "arpack" and "covariance_eigh". See :class:`TruncatedSVD` for an alternative with sparse data. For a usage example, see :ref:`sphx_glr_auto_examples_decomposition_plot_pca_iris.py` Read more in the :ref:`User Guide `. Parameters ---------- n_components : int, float or 'mle', default=None Number of components to keep. if n_components is not set all components are kept:: n_components == min(n_samples, n_features) If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's MLE is used to guess the dimension. Use of ``n_components == 'mle'`` will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``. If ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components. If ``svd_solver == 'arpack'``, the number of components must be strictly less than the minimum of n_features and n_samples. Hence, the None case results in:: n_components == min(n_samples, n_features) - 1 copy : bool, default=True If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead. whiten : bool, default=False When True (False by default) the `components_` vectors are multiplied by the square root of n_samples and then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometime improve the predictive accuracy of the downstream estimators by making their data respect some hard-wired assumptions. svd_solver : {'auto', 'full', 'covariance_eigh', 'arpack', 'randomized'}, default='auto' "auto" : The solver is selected by a default 'auto' policy is based on `X.shape` and `n_components`: if the input data has fewer than 1000 features and more than 10 times as many samples, then the "covariance_eigh" solver is used. Otherwise, if the input data is larger than 500x500 and the number of components to extract is lower than 80% of the smallest dimension of the data, then the more efficient "randomized" method is selected. Otherwise the exact "full" SVD is computed and optionally truncated afterwards. "full" : Run exact full SVD calling the standard LAPACK solver via `scipy.linalg.svd` and select the components by postprocessing "covariance_eigh" : Precompute the covariance matrix (on centered data), run a classical eigenvalue decomposition on the covariance matrix typically using LAPACK and select the components by postprocessing. This solver is very efficient for n_samples >> n_features and small n_features. It is, however, not tractable otherwise for large n_features (large memory footprint required to materialize the covariance matrix). Also note that compared to the "full" solver, this solver effectively doubles the condition number and is therefore less numerical stable (e.g. on input data with a large range of singular values). "arpack" : Run SVD truncated to `n_components` calling ARPACK solver via `scipy.sparse.linalg.svds`. It requires strictly `0 < n_components < min(X.shape)` "randomized" : Run randomized SVD by the method of Halko et al. .. versionadded:: 0.18.0 .. versionchanged:: 1.5 Added the 'covariance_eigh' solver. tol : float, default=0.0 Tolerance for singular values computed by svd_solver == 'arpack'. Must be of range [0.0, infinity). .. versionadded:: 0.18.0 iterated_power : int or 'auto', default='auto' Number of iterations for the power method computed by svd_solver == 'randomized'. Must be of range [0, infinity). .. versionadded:: 0.18.0 n_oversamples : int, default=10 This parameter is only relevant when `svd_solver="randomized"`. It corresponds to the additional number of random vectors to sample the range of `X` so as to ensure proper conditioning. See :func:`~sklearn.utils.extmath.randomized_svd` for more details. .. versionadded:: 1.1 power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Power iteration normalizer for randomized SVD solver. Not used by ARPACK. See :func:`~sklearn.utils.extmath.randomized_svd` for more details. .. versionadded:: 1.1 random_state : int, RandomState instance or None, default=None Used when the 'arpack' or 'randomized' solvers are used. Pass an int for reproducible results across multiple function calls. See :term:`Glossary `. .. versionadded:: 0.18.0 Attributes ---------- components_ : ndarray of shape (n_components, n_features) Principal axes in feature space, representing the directions of maximum variance in the data. Equivalently, the right singular vectors of the centered input data, parallel to its eigenvectors. The components are sorted by decreasing ``explained_variance_``. explained_variance_ : ndarray of shape (n_components,) The amount of variance explained by each of the selected components. The variance estimation uses `n_samples - 1` degrees of freedom. Equal to n_components largest eigenvalues of the covariance matrix of X. .. versionadded:: 0.18 explained_variance_ratio_ : ndarray of shape (n_components,) Percentage of variance explained by each of the selected components. If ``n_components`` is not set then all components are stored and the sum of the ratios is equal to 1.0. singular_values_ : ndarray of shape (n_components,) The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the ``n_components`` variables in the lower-dimensional space. .. versionadded:: 0.19 mean_ : ndarray of shape (n_features,) Per-feature empirical mean, estimated from the training set. Equal to `X.mean(axis=0)`. n_components_ : int The estimated number of components. When n_components is set to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this number is estimated from input data. Otherwise it equals the parameter n_components, or the lesser value of n_features and n_samples if n_components is None. n_samples_ : int Number of samples in the training data. noise_variance_ : float The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. It is required to compute the estimated data covariance and score samples. Equal to the average of (min(n_features, n_samples) - n_components) smallest eigenvalues of the covariance matrix of X. 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 -------- KernelPCA : Kernel Principal Component Analysis. SparsePCA : Sparse Principal Component Analysis. TruncatedSVD : Dimensionality reduction using truncated SVD. IncrementalPCA : Incremental Principal Component Analysis. References ---------- For n_components == 'mle', this class uses the method from: `Minka, T. P.. "Automatic choice of dimensionality for PCA". In NIPS, pp. 598-604 `_ Implements the probabilistic PCA model from: `Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal component analysis". Journal of the Royal Statistical Society: Series B (Statistical Methodology), 61(3), 611-622. `_ via the score and score_samples methods. For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`. For svd_solver == 'randomized', see: :doi:`Halko, N., Martinsson, P. G., and Tropp, J. A. (2011). "Finding structure with randomness: Probabilistic algorithms for constructing approximate matrix decompositions". SIAM review, 53(2), 217-288. <10.1137/090771806>` and also :doi:`Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011). "A randomized algorithm for the decomposition of matrices". Applied and Computational Harmonic Analysis, 30(1), 47-68. <10.1016/j.acha.2010.02.003>` Examples -------- >>> import numpy as np >>> from sklearn.decomposition import PCA >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) >>> pca = PCA(n_components=2) >>> pca.fit(X) PCA(n_components=2) >>> print(pca.explained_variance_ratio_) [0.9924 0.0075] >>> print(pca.singular_values_) [6.30061 0.54980] >>> pca = PCA(n_components=2, svd_solver='full') >>> pca.fit(X) PCA(n_components=2, svd_solver='full') >>> print(pca.explained_variance_ratio_) [0.9924 0.00755] >>> print(pca.singular_values_) [6.30061 0.54980] >>> pca = PCA(n_components=1, svd_solver='arpack') >>> pca.fit(X) PCA(n_components=1, svd_solver='arpack') >>> print(pca.explained_variance_ratio_) [0.99244] >>> print(pca.singular_values_) [6.30061] rNleft)closedrneithermleboolean>autofullarpack randomizedcovariance_eighrL>LUQRrLnone random_state n_componentsr#whiten svd_solvertoliterated_power n_oversamplespower_iteration_normalizerrT_parameter_constraintsTFr! )r#rWrXrYrZr[r\rTc||_||_||_||_||_||_||_||_| |_yNrU) selfrVr#rWrXrYrZr[r\rTs r>__init__z PCA.__init__sH)  $,**D'(r@)prefer_skip_nested_validationc(|j||S)aFit the model with X. Parameters ---------- X : {array-like, sparse matrix} 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 Ignored. Returns ------- self : object Returns the instance itself. )_fit)raXys r>fitzPCA.fits$ !  r@c|j|\}}}}}}|U|ddd|jf}|jr |t|jddz z}|S||d|jz}|S|j |||S)axFit the model with X and apply the dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix} 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 Ignored. Returns ------- X_new : ndarray of shape (n_samples, n_components) Transformed values. Notes ----- This method returns a Fortran-ordered array. To convert it to a C-ordered array, use 'np.ascontiguousarray'. Nrr) x_is_centered)re n_components_rWrr$ _transform)rarfrgUSr0rjr/s r> fit_transformzPCA.fit_transforms.)- ! %1aM2 =!)t))))*A{{T!''!*q.)) HQ+++,,H??1b ?F Fr@c t|\}}t|r'|jdvrtd|jd|jdk(r |r t dt |||j |jgdddd }|j|_|jd k(rt|rd|_|j>|jdk7rt|j}n%t|jd z }n |j}|jd k(r|jd d kr*|jdd|jd zk\rd|_nXt|jdks|dk(rd|_n3d |cxkrdt|jzkr nnd|_nd|_|jdvr|j||||S|jdvr|j|||Sy )z?Dispatch to the right submethod depending on the chosen solver.rLrNrPzWPCA only support sparse inputs with the "arpack" and "covariance_eigh" solvers, while "z:" was passed. See TruncatedSVD for a possible alternative.rNzCPCA with svd_solver='arpack' is not supported for Array API inputs.T)csrcscF)dtypeforce_writeable accept_sparse ensure_2dr#rLNrirr^rPirJrMg?rO)rMrP)rNrO)rr rX TypeErrorr%rfloat64float32_fit_svd_solverrVminr$r* _fit_full_fit_truncated)rarfr/is_array_api_compliantrVs r>rezPCA._fits%21%5" " A;4??2WW66:oo5FG<<  ??h &+AU    ::rzz* (  $   6 )hqk#+D    $##x/"177| "177|a/ ,,L   6 )wwqzU"qwwqzR!''!*_'D'8$QWW$ (='-$l7S3qww<%77'3$(.$   #> >>>!\27MN N  ! !%= =&&q,; ;>r@c <|j\}}|dk(r||krJtdd|cxkrt||ks*ntd|dt||d|j|j |d|_|j |j|j d|_|jd k(r|jr|j|d n|}||j z}|j }|stj|d \} } } n!|jj|d \} } } | dz|dz z } n|jdk(sJd }|j|z} | ||j |j dz|j |j dzz} | |dz z} |jj| \}}|j |j|d}|j|}|j|d}|j|d}d||dk<|} |j||dz z} |j} d} t| | d \} } | }|j!| }| |z }|j| d }|dk(r t#| |}nFd|cxkrdkr;nn8|rt%||}n|}t'|}t)j*||ddz}|t||kr|j | |d|_nd|_||_||_|j|d|ddfd |_|j| d|d |_|j|d|d |_|j|d|d |_| | | |||fS)z)Fit the model by computing full SVD on X.rJz?n_components='mle' is only supported if n_samples >= n_featuresr n_components=z2 must be between 0 and min(n_samples, n_features)=z with svd_solver=axis)rMTr"F) full_matricesr rrP)rr)rrr!Nu_based_decisionr )r/right)side)r$r%r|r{meanmean_reshaper+r#rsvdTeighfliprrr)rDrrnp searchsortednoise_variance_ n_samples_rk components_explained_variance_explained_variance_ratio_singular_values_)rarfrVr/rr.r1 X_centeredrjrmrnVtrC eigenvals eigenvecsr total_varrrexplained_variance_ratio_np ratio_cumsums r>r}z PCA._fit_full s ! : 5 :% Ul@c)Z&@@ ~...1)Z.H-IJ"2257  WWQQW' ZZ 4:: 6>   6 )59YYAD1AJ $** $J $ MM)"::jF1b99==5=I1b#$a4IM": ''+<< << "MaA **TZZ12**TZZ12 A Q A#%99>>!#4 Iy 2::i#8%@I 9-I 2I 2I *-Ii#o &"+  Y]34ABAB72 FF./ $7)$C!::ad:3 5 +,?KL  # # &/@-"/+/H+()DEL??<GTWXXL #j)4 4#%77+>|}+M#ND #&D #)::k-<-2B&C$:O$&::   .T$.$  *, %m| 44*4* &!# +;M\+JQU V!RM2--r@c  |j\}}|j}t|trt d|d|dd|cxkrt ||ks!nt d|dt ||d|d|dk(r.|t ||k(rt d|dt ||d|dt |j}d }t|rGt|d \|_ } | j|z|dz z }t||j} d } nU|j|d |_ |jr|j|d n|} | |jz} |j } |dk(rft!t |j|} t#| ||j$| \} }}|d d d}t'| d d d d df|d d dd \} }nJ|dk(rEt)| ||j*|j,|j.d |\} }}t'| |d \} }||_|_||_dz|dz z |_|+|jd dz }| dz} |j| |z }|j6|z |_|j|d |_|j4t ||krF||j|j6z |_|xj<t |||z zc_nd|_ |||| |fS)zYFit the model by computing truncated SVD (by ARPACK or randomized) on X. rz% cannot be a string with svd_solver=''rz2 must be between 1 and min(n_samples, n_features)=z with svd_solver='rNz7 must be strictly less than min(n_samples, n_features)=NrrFTr")krYv0rrrO)rVr[n_iterr\ flip_signrTr r!)r$r{ isinstancestrr%r|r rTr rrr)rrr#r+rr rYrrr[rZr\rrrkrrrr)rarfrVr/r.r1rXrTrvarrrjrrmrnrNs r>r~zPCA._fit_truncateds !" :)) lC (- l@c)Z&@@ Y !;ZI  8 # Iz8R(R Y !;ZI *$*;*;<  A;0;ODJ I-Q?I0DJJ?J!M+DJ59YYAD1AJ $** $J $ MM  ! QWW|$M M #&D !RM2--r@cxt|t|\}}t|||j|jgd}||j z }|j d}|j}d|j|||zzdz}|d|tdtjzzt|z zz}|S)aReturn the log-likelihood of each sample. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : array-like of shape (n_samples, n_features) The data. Returns ------- ll : ndarray of shape (n_samples,) Log-likelihood of each sample under the current model. F)rtresetrgrg?r) rrrryrzrr$ get_precisionr)rrr(r)rarfr/r0Xrr1 precisionlog_likes r> score_sampleszPCA.score_sampless" a A $"**bjj)A O ^WWQZ &&( "&&rI~!6Q&??C:C"%%K(88;y;QQRRr@cpt|\}}t|j|j|S)aReturn the average log-likelihood of all samples. See. "Pattern Recognition and Machine Learning" by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf Parameters ---------- X : array-like of shape (n_samples, n_features) The data. y : Ignored Ignored. Returns ------- ll : float Average log-likelihood of the samples under the current model. )rfloatrr)rarfrgr/r0s r>scorez PCA.score9s1(a ARWWT//2344r@ct|}ddg|j_d|_|j dv|j _|S)NryrzTrq)super__sklearn_tags__transformer_tagspreserves_dtypearray_api_supportrX input_tagssparse)ratags __class__s r>rzPCA.__sklearn_tags__PsLw')1:I0F-!%!%5 "   r@r`)__name__ __module__ __qualname____doc__rrrrrr]dict__annotations__rbr rhrorer}r~rrr __classcell__)rs@r>rFrFqs>ER Xq$v 6 ZAi 8 w     + R S q$v67 x Xq$v 6 #8QVDE'12N'O&P'('$D0) #)).56(5#G6#GJ=<~^.@\.|65.  r@rF)-rmathrrrnumbersrrnumpyrscipyr scipy.sparser scipy.sparse.linalgr baser utilsr utils._arpackrutils._array_apirrutils._param_validationrrr utils.extmathrrrrutils.sparsefuncsrrutils.validationrr_baserr?rDrFr@r>rsZ# #""!$&+?FFQQK=GT h (h r@