
    -iE                         S r SSKJrJr  SSKrSSKJrJrJ	r	J
r
  SSKJr  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJr  SSKJrJr   " S S\\	\5      r " S S\5      r " S S\5      rg)z%Matrix factorization with Sparse PCA.    )IntegralRealN   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)ridge_regression)check_random_state)Interval
StrOptions)svd_flip)check_arraycheck_is_fittedvalidate_data   )MiniBatchDictionaryLearningdict_learningc                     ^  \ rS rSr% SrS\" \SSSS9/\" \SSSS9/\" \SSSS9/\" \SSSS9/\" \SSSS9/\" S	S
15      /\S/S/S/S.	r	\
\S'    SSSSSS	SSSS.S jjr\" SS9SS j5       rS rS r\S 5       rU 4S jrSrU =r$ )_BaseSparsePCA   z/Base class for SparsePCA and MiniBatchSparsePCANr   leftclosedg        r   larscdverboserandom_state	n_componentsalpharidge_alphamax_itertolmethodn_jobsr   r   _parameter_constraints{Gz?  :0yE>F)r!   r"   r#   r$   r%   r&   r   r   c                p    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        Xl        g Nr   )
selfr    r!   r"   r#   r$   r%   r&   r   r   s
             T/var/www/html/venv/lib/python3.13/site-packages/sklearn/decomposition/_sparse_pca.py__init___BaseSparsePCA.__init__'   s4     )
& (    T)prefer_skip_nested_validationc                     [        U R                  5      n[        X5      nUR                  SS9U l        XR                  -
  nU R
                  c  UR                  S   nOU R
                  nU R                  XU5      $ )a`  Fit the model from data in X.

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

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

Returns
-------
self : object
    Returns the instance itself.
r   axisr   )r   r   r   meanmean_r    shape_fit)r-   Xyr   r    s        r.   fit_BaseSparsePCA.fit>   so    $ *$*;*;<$"VVV^


N$771:L,,Lyy,77r1   c                     [        U 5        [        XSS9nXR                  -
  n[        U R                  R
                  UR
                  U R                  SS9nU$ )a`  Least Squares projection of the data onto the sparse components.

To avoid instability issues in case the system is under-determined,
regularization can be applied (Ridge regression) via the
`ridge_alpha` parameter.

Note that Sparse PCA components orthogonality is not enforced as in PCA
hence one cannot use a simple linear projection.

Parameters
----------
X : ndarray of shape (n_samples, n_features)
    Test data to be transformed, must have the same number of
    features as the data used to train the model.

Returns
-------
X_new : ndarray of shape (n_samples, n_components)
    Transformed data.
F)resetcholesky)solver)r   r   r7   r
   components_Tr"   )r-   r:   Us      r.   	transform_BaseSparsePCA.transform]   sS    * 	$/

NT%5%5j
 r1   c                 d    [        U 5        [        U5      nXR                  -  U R                  -   $ )a  Transform data from the latent space to the original space.

This inversion is an approximation due to the loss of information
induced by the forward decomposition.

.. versionadded:: 1.2

Parameters
----------
X : ndarray of shape (n_samples, n_components)
    Data in the latent space.

Returns
-------
X_original : ndarray of shape (n_samples, n_features)
    Reconstructed data in the original space.
)r   r   rB   r7   )r-   r:   s     r.   inverse_transform _BaseSparsePCA.inverse_transform}   s-    $ 	N$$$

22r1   c                 4    U R                   R                  S   $ )z&Number of transformed output features.r   )rB   r8   )r-   s    r.   _n_features_out_BaseSparsePCA._n_features_out   s     %%a((r1   c                 J   > [         TU ]  5       nSS/UR                  l        U$ )Nfloat64float32)super__sklearn_tags__transformer_tagspreserves_dtype)r-   tags	__class__s     r.   rQ   _BaseSparsePCA.__sklearn_tags__   s(    w')1:I0F-r1   )
r!   r#   r7   r%   r    r&   r   r"   r$   r   r,   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   r'   dict__annotations__r/   r	   r<   rE   rH   propertyrK   rQ   __static_attributes____classcell__rU   s   @r.   r   r      s    9 x!T&IJ4d6:; sD@Ah4?@sD89vtn-.T";'(
$D 
 ) ). 58 68<@3. ) ) r1   r   c                      ^  \ rS rSr% Sr0 \R                  ES\R                  /S\R                  /S.Er\	\
S'    SSSSS	S
SSSSSS.
U 4S jjjrS rSrU =r$ )	SparsePCA   a  Sparse Principal Components Analysis (SparsePCA).

Finds the set of sparse components that can optimally reconstruct
the data.  The amount of sparseness is controllable by the coefficient
of the L1 penalty, given by the parameter alpha.

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

Parameters
----------
n_components : int, default=None
    Number of sparse atoms to extract. If None, then ``n_components``
    is set to ``n_features``.

alpha : float, default=1
    Sparsity controlling parameter. Higher values lead to sparser
    components.

ridge_alpha : float, default=0.01
    Amount of ridge shrinkage to apply in order to improve
    conditioning when calling the transform method.

max_iter : int, default=1000
    Maximum number of iterations to perform.

tol : float, default=1e-8
    Tolerance for the stopping condition.

method : {'lars', 'cd'}, default='lars'
    Method to be used for optimization.
    lars: uses the least angle regression method to solve the lasso problem
    (linear_model.lars_path)
    cd: uses the coordinate descent method to compute the
    Lasso solution (linear_model.Lasso). Lars will be faster if
    the estimated components are sparse.

n_jobs : int, default=None
    Number of parallel jobs to run.
    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

U_init : ndarray of shape (n_samples, n_components), default=None
    Initial values for the loadings for warm restart scenarios. Only used
    if `U_init` and `V_init` are not None.

V_init : ndarray of shape (n_components, n_features), default=None
    Initial values for the components for warm restart scenarios. Only used
    if `U_init` and `V_init` are not None.

verbose : int or bool, default=False
    Controls the verbosity; the higher, the more messages. Defaults to 0.

random_state : int, RandomState instance or None, default=None
    Used during dictionary learning. Pass an int for reproducible results
    across multiple function calls.
    See :term:`Glossary <random_state>`.

Attributes
----------
components_ : ndarray of shape (n_components, n_features)
    Sparse components extracted from the data.

error_ : ndarray
    Vector of errors at each iteration.

n_components_ : int
    Estimated number of components.

    .. versionadded:: 0.23

n_iter_ : int
    Number of iterations run.

mean_ : ndarray of shape (n_features,)
    Per-feature empirical mean, estimated from the training set.
    Equal to ``X.mean(axis=0)``.

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
--------
PCA : Principal Component Analysis implementation.
MiniBatchSparsePCA : Mini batch variant of `SparsePCA` that is faster but less
    accurate.
DictionaryLearning : Generic dictionary learning problem using a sparse code.

Examples
--------
>>> import numpy as np
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.decomposition import SparsePCA
>>> X, _ = make_friedman1(n_samples=200, n_features=30, random_state=0)
>>> transformer = SparsePCA(n_components=5, random_state=0)
>>> transformer.fit(X)
SparsePCA(...)
>>> X_transformed = transformer.transform(X)
>>> X_transformed.shape
(200, 5)
>>> # most values in the components_ are zero (sparsity)
>>> np.mean(transformer.components_ == 0)
np.float64(0.9666)
N)U_initV_initr'   r   r(   r)   r*   r   F)
r!   r"   r#   r$   r%   r&   re   rf   r   r   c       
         H   > [         TU ]  UUUUUUUU
US9	  Xl        Xl        g Nr   )rP   r/   re   rf   )r-   r    r!   r"   r#   r$   r%   r&   re   rf   r   r   rU   s               r.   r/   SparsePCA.__init__  s>     	%#% 	 
	
 r1   c                    U R                   b  U R                   R                  OSnU R                  b  U R                  R                  OSn[        UR                  UU R                  U R
                  U R                  U R                  U R                  U R                  UUUSS9u  pgol
        [        XgSS9u  pgUR                  U l        [        R                  R                  U R                  SS9SS2[        R                   4   n	SXS:H  '   U =R                  U	-  sl        [#        U R                  5      U l        Xl        U $ )z Specialized `fit` for SparsePCA.NT)
r!   r$   r#   r%   r&   r   r   	code_init	dict_initreturn_n_iter)u_based_decisionr   r4   r   )rf   rC   re   r   r!   r$   r#   r%   r&   r   n_iter_r   rB   nplinalgnormnewaxislenn_components_error_)
r-   r:   r    r   rk   rl   code
dictionaryEcomponents_norms
             r.   r9   SparsePCA._fit4  s    &*[[%<DKKMM$	%)[[%<DKKMM$	,9CC**]];;;;LL%-
)!\ $DtL66))..)9)9.B1bjj=Q011,-O+ !1!12r1   )re   rf   rB   rv   ru   ro   r,   )rW   rX   rY   rZ   r[   r   r'   rp   ndarrayr\   r]   r/   r9   r_   r`   ra   s   @r.   rc   rc      s    ob$

/
/$$$$D    : r1   rc   c                      ^  \ rS rSr% Sr0 \R                  E\" \SSSS9/S\	/\" \SSSS9/S/\" \SSSS9S/S	.Er\
\S
'    SSSSSSSSSSSSSS.U 4S jjjrS rSrU =r$ )MiniBatchSparsePCAiS  a)  Mini-batch Sparse Principal Components Analysis.

Finds the set of sparse components that can optimally reconstruct
the data.  The amount of sparseness is controllable by the coefficient
of the L1 penalty, given by the parameter alpha.

For an example comparing sparse PCA to PCA, see
:ref:`sphx_glr_auto_examples_decomposition_plot_faces_decomposition.py`

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

Parameters
----------
n_components : int, default=None
    Number of sparse atoms to extract. If None, then ``n_components``
    is set to ``n_features``.

alpha : int, default=1
    Sparsity controlling parameter. Higher values lead to sparser
    components.

ridge_alpha : float, default=0.01
    Amount of ridge shrinkage to apply in order to improve
    conditioning when calling the transform method.

max_iter : int, default=1_000
    Maximum number of iterations over the complete dataset before
    stopping independently of any early stopping criterion heuristics.

    .. versionadded:: 1.2

callback : callable, default=None
    Callable that gets invoked every five iterations.

batch_size : int, default=3
    The number of features to take in each mini batch.

verbose : int or bool, default=False
    Controls the verbosity; the higher, the more messages. Defaults to 0.

shuffle : bool, default=True
    Whether to shuffle the data before splitting it in batches.

n_jobs : int, default=None
    Number of parallel jobs to run.
    ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
    ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
    for more details.

method : {'lars', 'cd'}, default='lars'
    Method to be used for optimization.
    lars: uses the least angle regression method to solve the lasso problem
    (linear_model.lars_path)
    cd: uses the coordinate descent method to compute the
    Lasso solution (linear_model.Lasso). Lars will be faster if
    the estimated components are sparse.

random_state : int, RandomState instance or None, default=None
    Used for random shuffling when ``shuffle`` is set to ``True``,
    during online dictionary learning. Pass an int for reproducible results
    across multiple function calls.
    See :term:`Glossary <random_state>`.

tol : float, default=1e-3
    Control early stopping based on the norm of the differences in the
    dictionary between 2 steps.

    To disable early stopping based on changes in the dictionary, set
    `tol` to 0.0.

    .. versionadded:: 1.1

max_no_improvement : int or None, default=10
    Control early stopping based on the consecutive number of mini batches
    that does not yield an improvement on the smoothed cost function.

    To disable convergence detection based on cost function, set
    `max_no_improvement` to `None`.

    .. versionadded:: 1.1

Attributes
----------
components_ : ndarray of shape (n_components, n_features)
    Sparse components extracted from the data.

n_components_ : int
    Estimated number of components.

    .. versionadded:: 0.23

n_iter_ : int
    Number of iterations run.

mean_ : ndarray of shape (n_features,)
    Per-feature empirical mean, estimated from the training set.
    Equal to ``X.mean(axis=0)``.

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
--------
DictionaryLearning : Find a dictionary that sparsely encodes data.
IncrementalPCA : Incremental principal components analysis.
PCA : Principal component analysis.
SparsePCA : Sparse Principal Components Analysis.
TruncatedSVD : Dimensionality reduction using truncated SVD.

Examples
--------
>>> import numpy as np
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.decomposition import MiniBatchSparsePCA
>>> X, _ = make_friedman1(n_samples=200, n_features=30, random_state=0)
>>> transformer = MiniBatchSparsePCA(n_components=5, batch_size=50,
...                                  max_iter=10, random_state=0)
>>> transformer.fit(X)
MiniBatchSparsePCA(...)
>>> X_transformed = transformer.transform(X)
>>> X_transformed.shape
(200, 5)
>>> # most values in the components_ are zero (sparsity)
>>> np.mean(transformer.components_ == 0)
np.float64(0.9)
r   Nr   r   r   boolean)r#   callback
batch_sizeshufflemax_no_improvementr'   r(   r)      FTr   gMbP?
   )r!   r"   r#   r   r   r   r   r&   r%   r   r$   r   c                `   > [         TU ]  UUUUUU
U	UUS9	  XPl        X`l        Xl        Xl        g rh   )rP   r/   r   r   r   r   )r-   r    r!   r"   r#   r   r   r   r   r&   r%   r   r$   r   rU   s                 r.   r/   MiniBatchSparsePCA.__init__  sI    " 	%#% 	 
	
 !$"4r1   c                    SU R                   -   n[        UU R                  U R                  SU R                  U R
                  U R                  U R                   UUU R                  U R                  U R                  U R                  U R                  S9nUR                  SS9  UR                  UR                  5        UR                  UR                  5      R                  UR                  sU l        U l        ["        R$                  R'                  U R                   SS9SS2["        R(                  4   nSXfS:H  '   U =R                   U-  sl        [+        U R                   5      U l        U $ )	z)Specialized `fit` for MiniBatchSparsePCA.lasso_N)r    r!   r#   rl   r   r   r&   fit_algorithmr   transform_algorithmtransform_alphar   r   r$   r   default)rE   r   r4   r   )r%   r   r!   r#   r   r   r&   r   r   r$   r   
set_outputr<   rC   rE   ro   rB   rp   rq   rr   rs   rt   ru   )r-   r:   r    r   r   estrz   s          r.   r9   MiniBatchSparsePCA._fit  s    '4)%**]]LL;;++% 3 JJLL]]#66
" 	+),qss);)=)=s{{&$,))..)9)9.B1bjj=Q011,-O+ !1!12r1   )r   r   rB   r   ru   ro   r   r,   )rW   rX   rY   rZ   r[   r   r'   r   r   callabler\   r]   r/   r9   r_   r`   ra   s   @r.   r~   r~   S  s    EN$

/
/$h4?@8$!T&AB;'!T&I4P$D  5 5 5B r1   r~   )r[   numbersr   r   numpyrp   baser   r   r   r	   linear_modelr
   utilsr   utils._param_validationr   r   utils.extmathr   utils.validationr   r   r   _dict_learningr   r   r   rc   r~    r1   r.   <module>r      sc    +
 #   , & : $ J J FD46F DNq qhQ Qr1   