
    0PhF                         d Z ddlmZmZ ddlZddlmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZ ddlmZmZ  G d dee	e          Z G d de          Z G d de          ZdS )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            
       `    e Zd ZU dZd eeddd          g eeddd          g eeddd          g eeddd          g eeddd          g edd	h          gedgd
gdgd	Ze	e
d<   	 dddddddddddZ ed          dd            Zd Zd Zed             Z fdZ xZS )_BaseSparsePCAz/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                    || _         || _        || _        || _        || _        || _        || _        || _        |	| _        d S Nr   )
selfr   r    r!   r"   r#   r$   r%   r   r   s
             a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/decomposition/_sparse_pca.py__init__z_BaseSparsePCA.__init__'   sL     )
& (    T)prefer_skip_nested_validationc                     t          | j                  }t          | |          }|                    d          | _        || j        z
  }| j        |j        d         }n| j        }|                     |||          S )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   axisNr   )r   r   r   meanmean_r   shape_fit)r,   Xyr   r   s        r-   fitz_BaseSparsePCA.fit>   su    $ *$*;<<$""VVV^^

N$71:LL,LyyL,777r/   c                     t          |            t          | |d          }|| j        z
  }t          | j        j        |j        | j        d          }|S )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   r5   r
   components_Tr!   )r,   r8   Us      r-   	transformz_BaseSparsePCA.transform]   s`    * 	$///
NT%5j
 
 
 r/   c                 b    t          |            t          |          }|| j        z  | j        z   S )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   r?   r5   )r,   r8   s     r-   inverse_transformz _BaseSparsePCA.inverse_transform}   s2    $ 	NND$$
22r/   c                 &    | j         j        d         S )z&Number of transformed output features.r   )r?   r6   )r,   s    r-   _n_features_outz_BaseSparsePCA._n_features_out   s     %a((r/   c                 d    t                                                      }ddg|j        _        |S )Nfloat64float32)super__sklearn_tags__transformer_tagspreserves_dtype)r,   tags	__class__s     r-   rK   z_BaseSparsePCA.__sklearn_tags__   s-    ww''))1:I0F-r/   r+   )__name__
__module____qualname____doc__r   r   r   r   r&   dict__annotations__r.   r	   r:   rB   rD   propertyrF   rK   __classcell__rO   s   @r-   r   r      s        99 xx!T&IIIJ(4d6:::; sD@@@AXh4???@sD8889:vtn--.T";'(
$ 
$D 
 
 
 ) ) ) ) ) ). \5558 8 8 658<  @3 3 3. ) ) X)        r/   r   c                        e Zd ZU dZi ej        dej        gdej        gdZee	d<   	 dddddd	dddd
dd
 fdZ
d Z xZS )	SparsePCAau  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%   r[   r\   r   r   c       
         x    t                                          ||||||||
|	  	         || _        |	| _        d S Nr   )rJ   r.   r[   r\   )r,   r   r    r!   r"   r#   r$   r%   r[   r\   r   r   rO   s               r-   r.   zSparsePCA.__init__  sU     	%#% 	 
	
 
	
 
	
 r/   c                    | j         | j         j        nd}| j        | j        j        nd}t          |j        || j        | j        | j        | j        | j        | j	        |||d          \  }}}| _
        t          ||d          \  }}|j        | _        t          j                            | j        d          ddt          j        f         }	d|	|	dk    <   | xj        |	z  c_        t#          | j                  | _        || _        | S )z Specialized `fit` for SparsePCA.NT)
r    r#   r"   r$   r%   r   r   	code_init	dict_initreturn_n_iter)u_based_decisionr   r2   r   )r\   r@   r[   r   r    r#   r"   r$   r%   r   n_iter_r   r?   nplinalgnormnewaxislenn_components_error_)
r,   r8   r   r   r`   ra   code
dictionaryEcomponents_norms
             r-   r7   zSparsePCA._fit4  s    &*[%<DKMM$	%)[%<DKMM$	,9C*];;L%-
 -
 -
)j!T\ $D*tLLLj6)..)9.BB111bj=Q011,-O+ !122r/   r+   )rP   rQ   rR   rS   r   r&   re   ndarrayrT   rU   r.   r7   rW   rX   s   @r-   rZ   rZ      s         o ob$

/$$$$ $ $D           :      r/   rZ   c                        e Zd ZU dZi ej         eeddd          gdeg eeddd          gdg eeddd          dgdZe	e
d	<   	 ddd
ddddddddddd fdZd Z xZS )MiniBatchSparsePCAa  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"   rt   ru   r   rv   r%   r$   r   r#   rw   c                    t                                          ||||||
|	||	  	         || _        || _        || _        || _        d S r^   )rJ   r.   rt   ru   rv   rw   )r,   r   r    r!   r"   rt   ru   r   rv   r%   r$   r   r#   rw   rO   s                 r-   r.   zMiniBatchSparsePCA.__init__  sf    " 	%#% 	 
	
 
	
 
	
 !$"4r/   c                 ^   d| j         z   }t          || j        | j        d| j        | j        | j        | j         ||| j        | j        | j        | j	        | j
                  }|                    d           |                    |j                   |                    |j                  j        |j        c| _        | _        t"          j                            | j        d          ddt"          j        f         }d||dk    <   | xj        |z  c_        t+          | j                  | _        | S )	z)Specialized `fit` for MiniBatchSparsePCA.lasso_N)r   r    r"   ra   ru   rv   r%   fit_algorithmr   transform_algorithmtransform_alphar   rt   r#   rw   default)rB   r   r2   r   )r$   r   r    r"   ru   rv   r%   r   rt   r#   rw   
set_outputr:   r@   rB   rd   r?   re   rf   rg   rh   ri   rj   )r,   r8   r   r   r~   estro   s          r-   r7   zMiniBatchSparsePCA._fit  s    '4)%*]L;+% 3 JL]#6
 
 
" 	+++),qs););)=s{&$,)..)9.BB111bj=Q011,-O+ !122r/   r+   )rP   rQ   rR   rS   r   r&   r   r   callablerT   rU   r.   r7   rW   rX   s   @r-   rr   rr   S  s        E EN$

/$Xh4???@8$x!T&AAAB;'x!T&III4P$ $ $D    5 5 5 5 5 5 5 5B      r/   rr   )rS   numbersr   r   numpyre   baser   r   r   r	   linear_modelr
   utilsr   utils._param_validationr   r   utils.extmathr   utils.validationr   r   r   _dict_learningr   r   r   rZ   rr    r/   r-   <module>r      s   + +
 # " " " " " " "                , + + + + + & & & & & & : : : : : : : : $ $ $ $ $ $ J J J J J J J J J J F F F F F F F FD D D D D46F D D DNq q q q q q q qhQ Q Q Q Q Q Q Q Q Qr/   