
    0Ph0(                       d Z ddlZddlZddlZddlmZmZ ddlZddl	m
Z
 ddlmZ ddlmZmZmZmZ ddlmZmZmZmZ dd	lmZmZmZmZ dd
lmZmZmZ ddl m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z(m)Z) d Z*dddddddddd	dZ+ edgdgddgddg eh d          g eeddd          dg eeddd          dgdgddg eeddd          gedgdgdgdgdd          dddddddddddddd            Z,dddddddddddd d!Z-	 	 	 	 	 d9d"Z.d# Z/ edgdg ed$d%h          g eeddd          gd&d          	 d:dd'dddd(dddd%ddddd)d*d+d,            Z0 edg ed%d$h          gdg eeddd          gd-d          d'd.d%ddddddddddd/d0            Z1 G d1 d2ee          Z2 G d3 d4e2e          Z3 G d5 d6e2e          Z4 G d7 d8e2e          Z5dS );zDictionary learning.    N)IntegralReal)effective_n_jobs)linalg   )BaseEstimatorClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)LarsLasso	LassoLarsorthogonal_mp_gram)check_arraycheck_random_stategen_batchesgen_even_slices)Interval
StrOptionsvalidate_params)randomized_svd	row_normssvd_flip)Paralleldelayed)check_is_fittedvalidate_datac                 Z    |r&| dv r$t          d                    |                     d S d S )N)omplarsz9Positive constraint not supported for '{}' coding method.)
ValueErrorformatmethodpositives     d/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/decomposition/_dict_learning.py_check_positive_codingr'      sG     
Fo--GNNvVV
 
 	

 
--    
lasso_larsT  F	gramcov	algorithmregularizationcopy_covinitmax_iterverboser%   c       	   
         | j         \  }}|j         d         }|dk    rt          |          |z  }	 t          j        d          }t	          |d|	|d|
|          }|                    |j        | j        |           |j        }t          j        di | n# t          j        di | w xY w|dk    r|t          |          |z  }t          |d||d	|

          }|(|j	        d         st          j
        |          }||_        |                    |j        | j        d           |j        }n/|dk    r	 t          j        d          }t          d|	|t          |          d          }|                    |j        | j        |           |j        }t          j        di | n# t          j        di | w xY w|dk    r_t          j        |          t          j        t          j        |          |z
  d          z  j        }|
rt          j        |dd|           n<|dk    r6t#          ||t          |          dt%          | d	          |          j        }|                    ||          S )a	  Generic sparse coding with precomputed Gram and/or covariance matrices.

    Each row of the result is the solution to a Lasso problem.

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features)
        Data matrix.

    dictionary : ndarray of shape (n_components, n_features)
        The dictionary matrix against which to solve the sparse coding of
        the data. Some of the algorithms assume normalized rows.

    gram : ndarray of shape (n_components, n_components), default=None
        Precomputed Gram matrix, `dictionary * dictionary'`
        gram can be `None` if method is 'threshold'.

    cov : ndarray of shape (n_components, n_samples), default=None
        Precomputed covariance, `dictionary * X'`.

    algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'},             default='lasso_lars'
        The algorithm used:

        * `'lars'`: uses the least angle regression method
          (`linear_model.lars_path`);
        * `'lasso_lars'`: uses Lars to compute the Lasso solution;
        * `'lasso_cd'`: uses the coordinate descent method to compute the
          Lasso solution (`linear_model.Lasso`). lasso_lars will be faster if
          the estimated components are sparse;
        * `'omp'`: uses orthogonal matching pursuit to estimate the sparse
          solution;
        * `'threshold'`: squashes to zero all coefficients less than
          regularization from the projection `dictionary * data'`.

    regularization : int or float, default=None
        The regularization parameter. It corresponds to alpha when
        algorithm is `'lasso_lars'`, `'lasso_cd'` or `'threshold'`.
        Otherwise it corresponds to `n_nonzero_coefs`.

    init : ndarray of shape (n_samples, n_components), default=None
        Initialization value of the sparse code. Only used if
        `algorithm='lasso_cd'`.

    max_iter : int, default=1000
        Maximum number of iterations to perform if `algorithm='lasso_cd'` or
        `'lasso_lars'`.

    copy_cov : bool, default=True
        Whether to copy the precomputed covariance matrix; if `False`, it may
        be overwritten.

    verbose : int, default=0
        Controls the verbosity; the higher, the more messages.

    positive: bool, default=False
        Whether to enforce a positivity constraint on the sparse code.

        .. versionadded:: 0.20

    Returns
    -------
    code : ndarray of shape (n_components, n_features)
        The sparse codes.
    r   r)   ignore)allF)alphafit_interceptr3   
precomputefit_pathr%   r2   )Xylasso_cdT)r7   r8   r9   r2   
warm_startr%   N	WRITEABLE)check_inputr    )r8   r3   r9   n_nonzero_coefsr:   	thresholdoutr   )squared)Gramr;   r@   tolnorms_squaredcopy_Xy )shapefloatnpseterrr   fitTcoef_r   flagsarrayr   intsignmaximumabsclipr   r   reshape)X
dictionaryr,   r-   r.   r/   r0   r1   r2   r3   r%   	n_samples
n_featuresn_componentsr7   err_mgtr)   new_codeclfr    s                       r&   _sparse_encode_precomputedra   $   s   ^ GIz#A&LL  n%%
2	!iH---G ##!!  J NN:<N555!'HI      BI      	j	 	 n%%
2
 
 
 
  :k* &x~~CI
acu5559	f			!iH---G # #N 3 3  D HHZ\133H///zHI      BI      	k	!	!GCLL2:bfSkkN.JA#N#NNQ 	5GHa84444	e		%//#At444
 
 
  	 I|444s   AB B+7AF( (F;z
array-like>   r   r    r<   rA   r)      leftclosedbooleanr3   rY   rZ   r,   r-   r.   r@   r7   r0   r1   r2   n_jobsr?   r3   r%   prefer_skip_nested_validation)r,   r-   r.   r@   r7   r0   r1   r2   rh   r?   r3   r%   c                   |ru|dk    rQt          |dt          j        t          j        g          }t          | dt          j        t          j        g          } nt          |          }t          |           } |j        d         | j        d         k    r-t          d                    |j        | j                            t          ||           t          | |||||||||	|
||          S )a#  Sparse coding.

    Each row of the result is the solution to a sparse coding problem.
    The goal is to find a sparse array `code` such that::

        X ~= code * dictionary

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

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data matrix.

    dictionary : array-like of shape (n_components, n_features)
        The dictionary matrix against which to solve the sparse coding of
        the data. Some of the algorithms assume normalized rows for meaningful
        output.

    gram : array-like of shape (n_components, n_components), default=None
        Precomputed Gram matrix, `dictionary * dictionary'`.

    cov : array-like of shape (n_components, n_samples), default=None
        Precomputed covariance, `dictionary' * X`.

    algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'},             default='lasso_lars'
        The algorithm used:

        * `'lars'`: uses the least angle regression method
          (`linear_model.lars_path`);
        * `'lasso_lars'`: uses Lars to compute the Lasso solution;
        * `'lasso_cd'`: uses the coordinate descent method to compute the
          Lasso solution (`linear_model.Lasso`). lasso_lars will be faster if
          the estimated components are sparse;
        * `'omp'`: uses orthogonal matching pursuit to estimate the sparse
          solution;
        * `'threshold'`: squashes to zero all coefficients less than
          regularization from the projection `dictionary * data'`.

    n_nonzero_coefs : int, default=None
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
        and is overridden by `alpha` in the `omp` case. If `None`, then
        `n_nonzero_coefs=int(n_features / 10)`.

    alpha : float, default=None
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
        the reconstruction error targeted. In this case, it overrides
        `n_nonzero_coefs`.
        If `None`, default to 1.

    copy_cov : bool, default=True
        Whether to copy the precomputed covariance matrix; if `False`, it may
        be overwritten.

    init : ndarray of shape (n_samples, n_components), default=None
        Initialization value of the sparse codes. Only used if
        `algorithm='lasso_cd'`.

    max_iter : int, default=1000
        Maximum number of iterations to perform if `algorithm='lasso_cd'` or
        `'lasso_lars'`.

    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.

    check_input : bool, default=True
        If `False`, the input arrays X and dictionary will not be checked.

    verbose : int, default=0
        Controls the verbosity; the higher, the more messages.

    positive : bool, default=False
        Whether to enforce positivity when finding the encoding.

        .. versionadded:: 0.20

    Returns
    -------
    code : ndarray of shape (n_samples, n_components)
        The sparse codes.

    See Also
    --------
    sklearn.linear_model.lars_path : Compute Least Angle Regression or Lasso
        path using LARS algorithm.
    sklearn.linear_model.orthogonal_mp : Solves Orthogonal Matching Pursuit problems.
    sklearn.linear_model.Lasso : Train Linear Model with L1 prior as regularizer.
    SparseCoder : Find a sparse representation of data from a fixed precomputed
        dictionary.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.decomposition import sparse_encode
    >>> X = np.array([[-1, -1, -1], [0, 0, 3]])
    >>> dictionary = np.array(
    ...     [[0, 1, 0],
    ...      [-1, -1, 2],
    ...      [1, 1, 1],
    ...      [0, 1, 1],
    ...      [0, 2, 1]],
    ...    dtype=np.float64
    ... )
    >>> sparse_encode(X, dictionary, alpha=1e-10)
    array([[ 0.,  0., -1.,  0.,  0.],
           [ 0.,  1.,  1.,  0.,  0.]])
    r<   C)orderdtyperb   zRDictionary and X have different numbers of features:dictionary.shape: {} X.shape{}r,   r-   r.   r@   r7   r0   r1   r2   rh   r3   r%   )	r   rL   float64float32rJ   r!   r"   r'   _sparse_encoderg   s                 r&   sparse_encoders      s	   v  
""$#bj"*-E  J ASRZ0HIIIAA$Z00JAAagaj((--3VJ4Dag-N-N
 
 	

 9h///	'   r(   ro   c                   	  j         \  }}j         d         }dv r&|!t          t          |dz  d          |          n|d dk    rt          j        j                  "dk    rd	t          j         j                  t          |
          dk    sdk    rt           	
          }|S  j         d         }j         d         }t          j        ||f          }t          t          |t          |
                              } t          |
           	fd|D                       }t          ||          D ]
\  }}|||<   |S )z1Sparse coding without input/parameter validation.r   )r    r   N
   rb   g      ?rA   r<   Fr+   )rh   r3   c              3      K   | ]J} t          t                    |         d d |f         nd |         nd 	
          V  Kd S )Nr+   )r   ra   ).0
this_slicerY   r.   r0   r-   rZ   r,   r1   r2   r%   r/   r3   s     r&   	<genexpr>z!_sparse_encode.<locals>.<genexpr>  s       : :  	,*++jM&)oAAAzM""4)%)%5j!!4	
 	
 	
: : : : : :r(   )rJ   minmaxrL   dotrO   r   ra   emptylistr   r   zip)rY   rZ   r,   r-   r.   r@   r7   r0   r1   r2   rh   r3   r%   r[   r\   r]   codeslices
code_viewsrx   	this_viewr/   s   `````  ``` ``        @r&   rr   rr     s   $ GIz#A&LO##(! Z"_a!8!8,GGN! N|	[00vj*,//
{yJ..fZ%%1$$	[(@(@))
 
 
  
I#A&L8Y-..D/)-=f-E-EFFGGF9999 : : : : : : : : : : : : : : !: : :  J  "%VZ!8!8 % %
I$ZKr(   c           
         |j         \  }}	t          |          }|
|j        |z  }|
|j        |z  }d}
t          |	          D ]}|||f         dk    r2| |xx         |dd|f         ||         | z  z
  |||f         z  z  cc<   no||                    |                   }d|                                pdz  }|                    d|t          |                    }||z   | |<   d|dd|f<   |
dz  }
|r$t          j	        | |         dd| |                    | |xx         t          t          j        | |                   d          z  cc<   |r|
dk    rt          |
 d           dS dS dS )	a  Update the dense dictionary factor in place.

    Parameters
    ----------
    dictionary : ndarray of shape (n_components, n_features)
        Value of the dictionary at the previous iteration.

    Y : ndarray of shape (n_samples, n_features)
        Data matrix.

    code : ndarray of shape (n_samples, n_components)
        Sparse coding of the data against which to optimize the dictionary.

    A : ndarray of shape (n_components, n_components), default=None
        Together with `B`, sufficient stats of the online model to update the
        dictionary.

    B : ndarray of shape (n_features, n_components), default=None
        Together with `A`, sufficient stats of the online model to update the
        dictionary.

    verbose: bool, default=False
        Degree of output the procedure will print.

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

    positive : bool, default=False
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20
    Nr   gư>g{Gz?rb   )sizerB   z unused atoms resampled.)rJ   r   rO   rangechoicestdnormallenrL   rW   r{   r   normprint)rZ   Yr   ABr3   random_stater%   r[   r]   n_unusedknewdnoise_levelnoises                  r&   _update_dictr     s   X #jI|%l33LyFTMyC$JH<   < <QT7T>>qMMMa1g!z(99Qq!tWDDMMMM \((334D $((**/2K '';SYY'GGE 5LJqMDAJMH 	?GJqM1d
1>>>> 	1V[A77;;; 58a<<333444445 5<<r(   c                   t          j                     }||t          j        |d          }|}nFt          j        | d          \  }}}t          ||          \  }}|ddt          j        f         |z  }t          |          }||k    r|ddd|f         }|d|ddf         }nnt          j        |t          j	        t          |          ||z
  f          f         }t          j
        |t          j	        ||z
  |j        d         f          f         }t          j        |          }g }t          j        }|
dk    rt          dd	           d
}t          |          D ]x}t          j                     |z
  }|
dk    r>t           j                            d           t           j                                         n|
rt          d|||dz  |fz             t)          | ||||||||
	  	        }t+          || ||
||           dt          j        | ||z  z
  dz            z  |t          j        t          j        |                    z  z   }|                    |           |dk    rL|d         |d
         z
  }|||d
         z  k     r,|
dk    rt          d           n|
rt          d|z              n$|dz  dk    r|	 |	t3                                 z|r	||||dz   fS |||fS )z"Main dictionary learning algorithmNF)rm   F)full_matricesrb   [dict_learning] )end.zCIteration % 3i (elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)<   )r.   r7   r1   rh   r%   r2   r3   r3   r   r%         ?r   r    z+--- Convergence reached after %d iterations   )timerL   rR   r   svdr   newaxisr   c_zerosr_rJ   asfortranarraynanr   r   sysstdoutwriteflushrs   r   sumrV   appendlocals)rY   r]   r7   r2   rF   r$   rh   	dict_init	code_initcallbackr3   r   return_n_iterpositive_dictpositive_codemethod_max_itert0r   rZ   Srerrorscurrent_costiidtdEs                             r&   _dict_learningr   )  s`   ( 
B!6x	---

$j%@@@a#D*55jqqq"*}%
2
JAqAAA}}$%qqq 01

uT28SYYq0@$ABBBCU,"2J4DQ4G!HIII

 ":..JF6L!||S)))) 
BHoo 3 3Y[[2a<<JS!!!J 	Ur27L12   "$

 

 

 	%"	
 	
 	
 	
 RVQ
):%:q$@AAAEBFF4LLM
 M
 E
 
 	l###66fRj(BC&*$$$a<<"IIII NG"LMMM6Q;;8/HVXX (Za//Z''r(   cdr    )rY   return_coder$   r   d      MbP?ru   )r7   r2   r   r   r   
batch_sizer3   shufflerh   r$   r   r   r   r   rF   max_no_improvementc                    d|z   }t          di d|d|d|d|
d|d|d|	d	|d
|d|d|d|d|d|d|d|d|d|                    |           }|s|j        S |                    |           }||j        fS )a
  Solve a dictionary learning matrix factorization problem online.

    Finds the best dictionary and the corresponding sparse code for
    approximating the data matrix X by solving::

        (U^*, V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
                     (U,V)
                     with || V_k ||_2 = 1 for all  0 <= k < n_components

    where V is the dictionary and U is the sparse code. ||.||_Fro stands for
    the Frobenius norm and ||.||_1,1 stands for the entry-wise matrix norm
    which is the sum of the absolute values of all the entries in the matrix.
    This is accomplished by repeatedly iterating over mini-batches by slicing
    the input data.

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

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data matrix.

    n_components : int or None, default=2
        Number of dictionary atoms to extract. If None, then ``n_components``
        is set to ``n_features``.

    alpha : float, default=1
        Sparsity controlling parameter.

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

        .. versionadded:: 1.1

    return_code : bool, default=True
        Whether to also return the code U or just the dictionary `V`.

    dict_init : ndarray of shape (n_components, n_features), default=None
        Initial values for the dictionary for warm restart scenarios.
        If `None`, the initial values for the dictionary are created
        with an SVD decomposition of the data via
        :func:`~sklearn.utils.extmath.randomized_svd`.

    callback : callable, default=None
        A callable that gets invoked at the end of each iteration.

    batch_size : int, default=256
        The number of samples to take in each batch.

        .. versionchanged:: 1.3
           The default value of `batch_size` changed from 3 to 256 in version 1.3.

    verbose : bool, default=False
        To control the verbosity of the procedure.

    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'
        * `'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 initializing the dictionary when ``dict_init`` is not
        specified, randomly shuffling the data when ``shuffle`` is set to
        ``True``, and updating the dictionary. Pass an int for reproducible
        results across multiple function calls.
        See :term:`Glossary <random_state>`.

    positive_dict : bool, default=False
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    positive_code : bool, default=False
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    method_max_iter : int, default=1000
        Maximum number of iterations to perform when solving the lasso problem.

        .. versionadded:: 0.22

    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, 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

    Returns
    -------
    code : ndarray of shape (n_samples, n_components),
        The sparse code (only returned if `return_code=True`).

    dictionary : ndarray of shape (n_components, n_features),
        The solutions to the dictionary learning problem.

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to `True`.

    See Also
    --------
    dict_learning : Solve a dictionary learning matrix factorization problem.
    DictionaryLearning : Find a dictionary that sparsely encodes data.
    MiniBatchDictionaryLearning : A faster, less accurate, version of the dictionary
        learning algorithm.
    SparsePCA : Sparse Principal Components Analysis.
    MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import make_sparse_coded_signal
    >>> from sklearn.decomposition import dict_learning_online
    >>> X, _, _ = make_sparse_coded_signal(
    ...     n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
    ...     random_state=42,
    ... )
    >>> U, V = dict_learning_online(
    ...     X, n_components=15, alpha=0.2, max_iter=20, batch_size=3, random_state=42
    ... )

    We can check the level of sparsity of `U`:

    >>> np.mean(U == 0)
    np.float64(0.53...)

    We can compare the average squared euclidean norm of the reconstruction
    error of the sparse coded signal relative to the squared euclidean norm of
    the original signal:

    >>> X_hat = U @ V
    >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
    np.float64(0.05...)
    lasso_r]   r7   r2   rh   fit_algorithmr   r   r   r   transform_algorithmtransform_alphar   r   transform_max_iterr3   r   rF   r   NrI   )MiniBatchDictionaryLearningrN   components_	transform)rY   r]   r7   r2   r   r   r   r   r3   r   rh   r$   r   r   r   r   rF   r   r   estr   s                        r&   dict_learning_onliner     s:   z #V+
%   !\e  v	
 f :  ) "\ 0/  $m $m +?   !" C#$ .-%& 
c!ff' *  %}}QS_$$r(   )rY   r$   r   r   :0yE>)r2   rF   r$   rh   r   r   r   r3   r   r   r   r   r   c                    t          ||||||||	||
||||                              d          }|                    |           }|r||j        |j        |j        fS ||j        |j        fS )aa  Solve a dictionary learning matrix factorization problem.

    Finds the best dictionary and the corresponding sparse code for
    approximating the data matrix X by solving::

        (U^*, V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
                     (U,V)
                    with || V_k ||_2 = 1 for all  0 <= k < n_components

    where V is the dictionary and U is the sparse code. ||.||_Fro stands for
    the Frobenius norm and ||.||_1,1 stands for the entry-wise matrix norm
    which is the sum of the absolute values of all the entries in the matrix.

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

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Data matrix.

    n_components : int
        Number of dictionary atoms to extract.

    alpha : int or float
        Sparsity controlling parameter.

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

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

    method : {'lars', 'cd'}, default='lars'
        The method used:

        * `'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.

    dict_init : ndarray of shape (n_components, n_features), default=None
        Initial value for the dictionary for warm restart scenarios. Only used
        if `code_init` and `dict_init` are not None.

    code_init : ndarray of shape (n_samples, n_components), default=None
        Initial value for the sparse code for warm restart scenarios. Only used
        if `code_init` and `dict_init` are not None.

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

    verbose : bool, default=False
        To control the verbosity of the procedure.

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

    return_n_iter : bool, default=False
        Whether or not to return the number of iterations.

    positive_dict : bool, default=False
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    positive_code : bool, default=False
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

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

        .. versionadded:: 0.22

    Returns
    -------
    code : ndarray of shape (n_samples, n_components)
        The sparse code factor in the matrix factorization.

    dictionary : ndarray of shape (n_components, n_features),
        The dictionary factor in the matrix factorization.

    errors : array
        Vector of errors at each iteration.

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to True.

    See Also
    --------
    dict_learning_online : Solve a dictionary learning matrix factorization
        problem online.
    DictionaryLearning : Find a dictionary that sparsely encodes data.
    MiniBatchDictionaryLearning : A faster, less accurate version
        of the dictionary learning algorithm.
    SparsePCA : Sparse Principal Components Analysis.
    MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import make_sparse_coded_signal
    >>> from sklearn.decomposition import dict_learning
    >>> X, _, _ = make_sparse_coded_signal(
    ...     n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
    ...     random_state=42,
    ... )
    >>> U, V, errors = dict_learning(X, n_components=15, alpha=0.1, random_state=42)

    We can check the level of sparsity of `U`:

    >>> np.mean(U == 0)
    np.float64(0.6...)

    We can compare the average squared euclidean norm of the reconstruction
    error of the sparse coded signal relative to the squared euclidean norm of
    the original signal:

    >>> X_hat = U @ V
    >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
    np.float64(0.01...)
    )r]   r7   r2   rF   r   rh   r   r   r   r3   r   r   r   r   default)r   )DictionaryLearning
set_outputfit_transformr   error_n_iter_)rY   r]   r7   r2   rF   r$   rh   r   r   r   r3   r   r   r   r   r   	estimatorr   s                     r&   dict_learningr   u  s    B #!!##*   j9j%%   ""1%%D 
!	
 	
 &	(888r(   c                   $    e Zd ZdZd Zd Zd ZdS )_BaseSparseCodingz>Base class from SparseCoder and DictionaryLearning algorithms.c                 h    || _         || _        || _        || _        || _        || _        || _        d S N)r   transform_n_nonzero_coefsr   r   
split_signrh   r   )selfr   r   r   r   rh   r   r   s           r&   __init__z_BaseSparseCoding.__init__4  s@     $7 )B&."4$*r(   c           
         t          | |d          }t          | d          r| j        | j        }n| j        }t	          ||| j        | j        || j        | j        | j	                  }| j
        rb|j        \  }}t          j        |d|z  f          }t          j        |d          |ddd|f<   t          j        |d           |dd|df<   |}|S )zWPrivate method allowing to accommodate both DictionaryLearning and
        SparseCoder.F)resetr7   N)r.   r@   r7   r2   rh   r%   r   r   )r   hasattrr   r7   rs   r   r   r   rh   r   r   rJ   rL   r}   rU   minimum)r   rY   rZ   r   r   r[   r\   
split_codes           r&   
_transformz_BaseSparseCoding._transformF  s     $///4!! 	3d&:&B"jOO"2O. :!,;'	
 	
 	
 ? 	$(J!Iz9a*n"=>>J)+D!)<)<Jqqq+:+~&*,*T1*=*=)=Jqqq*++~&Dr(   c                 V    t          |            |                     || j                  S )a  Encode the data as a sparse combination of the dictionary atoms.

        Coding method is determined by the object parameter
        `transform_algorithm`.

        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.
        )r   r   r   r   rY   s     r&   r   z_BaseSparseCoding.transforme  s)    " 	q$"2333r(   N)__name__
__module____qualname____doc__r   r   r   rI   r(   r&   r   r   1  sG        HH+ + +$  >4 4 4 4 4r(   r   c                        e Zd ZdZdddddddd fd
ZddZd fd		Z fd
Zed             Z	ed             Z
ed             Z xZS )SparseCodera  Sparse coding.

    Finds a sparse representation of data against a fixed, precomputed
    dictionary.

    Each row of the result is the solution to a sparse coding problem.
    The goal is to find a sparse array `code` such that::

        X ~= code * dictionary

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

    Parameters
    ----------
    dictionary : ndarray of shape (n_components, n_features)
        The dictionary atoms used for sparse coding. Lines are assumed to be
        normalized to unit norm.

    transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp',             'threshold'}, default='omp'
        Algorithm used to transform the data:

        - `'lars'`: uses the least angle regression method
          (`linear_model.lars_path`);
        - `'lasso_lars'`: uses Lars to compute the Lasso solution;
        - `'lasso_cd'`: uses the coordinate descent method to compute the
          Lasso solution (linear_model.Lasso). `'lasso_lars'` will be faster if
          the estimated components are sparse;
        - `'omp'`: uses orthogonal matching pursuit to estimate the sparse
          solution;
        - `'threshold'`: squashes to zero all coefficients less than alpha from
          the projection ``dictionary * X'``.

    transform_n_nonzero_coefs : int, default=None
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
        and is overridden by `alpha` in the `omp` case. If `None`, then
        `transform_n_nonzero_coefs=int(n_features / 10)`.

    transform_alpha : float, default=None
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
        the reconstruction error targeted. In this case, it overrides
        `n_nonzero_coefs`.
        If `None`, default to 1.

    split_sign : bool, default=False
        Whether to split the sparse feature vector into the concatenation of
        its negative part and its positive part. This can improve the
        performance of downstream classifiers.

    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.

    positive_code : bool, default=False
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    transform_max_iter : int, default=1000
        Maximum number of iterations to perform if `algorithm='lasso_cd'` or
        `lasso_lars`.

        .. versionadded:: 0.22

    Attributes
    ----------
    n_components_ : int
        Number of atoms.

    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.
    MiniBatchDictionaryLearning : A faster, less accurate, version of the
        dictionary learning algorithm.
    MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
    SparsePCA : Sparse Principal Components Analysis.
    sparse_encode : Sparse coding where each row of the result is the solution
        to a sparse coding problem.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.decomposition import SparseCoder
    >>> X = np.array([[-1, -1, -1], [0, 0, 3]])
    >>> dictionary = np.array(
    ...     [[0, 1, 0],
    ...      [-1, -1, 2],
    ...      [1, 1, 1],
    ...      [0, 1, 1],
    ...      [0, 2, 1]],
    ...    dtype=np.float64
    ... )
    >>> coder = SparseCoder(
    ...     dictionary=dictionary, transform_algorithm='lasso_lars',
    ...     transform_alpha=1e-10,
    ... )
    >>> coder.transform(X)
    array([[ 0.,  0., -1.,  0.,  0.],
           [ 0.,  1.,  1.,  0.,  0.]])
    r   NFr*   )r   r   r   r   rh   r   r   c          	      d    t                                          |||||||           || _        d S r   )superr   rZ   )
r   rZ   r   r   r   r   rh   r   r   	__class__s
            r&   r   zSparseCoder.__init__  sC     	%	
 	
 	
 %r(   c                     | S )a  Do nothing and return the estimator unchanged.

        This method is just there to implement the usual API and hence
        work in pipelines.

        Parameters
        ----------
        X : Ignored
            Not used, present for API consistency by convention.

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

        Returns
        -------
        self : object
            Returns the instance itself.
        rI   r   rY   ys      r&   rN   zSparseCoder.fit	  s	    & r(   c                 R    t                                          || j                  S )aQ  Encode the data as a sparse combination of the dictionary atoms.

        Coding method is determined by the object parameter
        `transform_algorithm`.

        Parameters
        ----------
        X : ndarray 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 for API consistency by convention.

        Returns
        -------
        X_new : ndarray of shape (n_samples, n_components)
            Transformed data.
        )r   r   rZ   )r   rY   r   r   s      r&   r   zSparseCoder.transform  s!    ( ww!!!T_555r(   c                 r    t                                                      }d|_        ddg|j        _        |S )NFrp   rq   )r   __sklearn_tags__requires_fittransformer_tagspreserves_dtyper   tagsr   s     r&   r   zSparseCoder.__sklearn_tags__4  s5    ww''))!1:I0F-r(   c                 &    | j         j        d         S )zNumber of atoms.r   rZ   rJ   r   s    r&   n_components_zSparseCoder.n_components_:       $Q''r(   c                 &    | j         j        d         S )z%Number of features seen during `fit`.rb   r  r  s    r&   n_features_in_zSparseCoder.n_features_in_?  r	  r(   c                     | j         S )&Number of transformed output features.)r  r  s    r&   _n_features_outzSparseCoder._n_features_outD  s     !!r(   r   )r   r   r   r   r   rN   r   r   propertyr  r  r  __classcell__r   s   @r&   r   r   z  s       u uv ""&% % % % % % %.   *6 6 6 6 6 6,     ( ( X( ( ( X( " " X" " " " "r(   r   c                   F    e Zd ZU dZi d eeddd          dgd eeddd          gd	 eeddd          gd
 eeddd          gd eddh          gd eh d          gd eeddd          dgd eeddd          dgdedgdej	        dgdej	        dgde
dgddgddgddgddgddgd eeddd          giZeed<   	 d*ddddd ddddddd!d!dd!d!dd" fd#Zd*d$Z ed%&          d*d'            Zed(             Z fd)Z xZS )+r   a  Dictionary learning.

    Finds a dictionary (a set of atoms) that performs well at sparsely
    encoding the fitted data.

    Solves the optimization problem::

        (U^*,V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
                    (U,V)
                    with || V_k ||_2 <= 1 for all  0 <= k < n_components

    ||.||_Fro stands for the Frobenius norm and ||.||_1,1 stands for
    the entry-wise matrix norm which is the sum of the absolute values
    of all the entries in the matrix.

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

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

    alpha : float, default=1.0
        Sparsity controlling parameter.

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

    tol : float, default=1e-8
        Tolerance for numerical error.

    fit_algorithm : {'lars', 'cd'}, default='lars'
        * `'lars'`: uses the least angle regression method to solve the lasso
          problem (:func:`~sklearn.linear_model.lars_path`);
        * `'cd'`: uses the coordinate descent method to compute the
          Lasso solution (:class:`~sklearn.linear_model.Lasso`). Lars will be
          faster if the estimated components are sparse.

        .. versionadded:: 0.17
           *cd* coordinate descent method to improve speed.

    transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp',             'threshold'}, default='omp'
        Algorithm used to transform the data:

        - `'lars'`: uses the least angle regression method
          (:func:`~sklearn.linear_model.lars_path`);
        - `'lasso_lars'`: uses Lars to compute the Lasso solution.
        - `'lasso_cd'`: uses the coordinate descent method to compute the
          Lasso solution (:class:`~sklearn.linear_model.Lasso`). `'lasso_lars'`
          will be faster if the estimated components are sparse.
        - `'omp'`: uses orthogonal matching pursuit to estimate the sparse
          solution.
        - `'threshold'`: squashes to zero all coefficients less than alpha from
          the projection ``dictionary * X'``.

        .. versionadded:: 0.17
           *lasso_cd* coordinate descent method to improve speed.

    transform_n_nonzero_coefs : int, default=None
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and
        `algorithm='omp'`. If `None`, then
        `transform_n_nonzero_coefs=int(n_features / 10)`.

    transform_alpha : float, default=None
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `None`, defaults to `alpha`.

        .. versionchanged:: 1.2
            When None, default value changed from 1.0 to `alpha`.

    n_jobs : int or None, 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.

    code_init : ndarray of shape (n_samples, n_components), default=None
        Initial value for the code, for warm restart. Only used if `code_init`
        and `dict_init` are not None.

    dict_init : ndarray of shape (n_components, n_features), default=None
        Initial values for the dictionary, for warm restart. Only used if
        `code_init` and `dict_init` are not None.

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

        .. versionadded:: 1.3

    verbose : bool, default=False
        To control the verbosity of the procedure.

    split_sign : bool, default=False
        Whether to split the sparse feature vector into the concatenation of
        its negative part and its positive part. This can improve the
        performance of downstream classifiers.

    random_state : int, RandomState instance or None, default=None
        Used for initializing the dictionary when ``dict_init`` is not
        specified, randomly shuffling the data when ``shuffle`` is set to
        ``True``, and updating the dictionary. Pass an int for reproducible
        results across multiple function calls.
        See :term:`Glossary <random_state>`.

    positive_code : bool, default=False
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    positive_dict : bool, default=False
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    transform_max_iter : int, default=1000
        Maximum number of iterations to perform if `algorithm='lasso_cd'` or
        `'lasso_lars'`.

        .. versionadded:: 0.22

    Attributes
    ----------
    components_ : ndarray of shape (n_components, n_features)
        dictionary atoms extracted from the data

    error_ : array
        vector of errors at each iteration

    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

    n_iter_ : int
        Number of iterations run.

    See Also
    --------
    MiniBatchDictionaryLearning: A faster, less accurate, version of the
        dictionary learning algorithm.
    MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
    SparseCoder : Find a sparse representation of data from a fixed,
        precomputed dictionary.
    SparsePCA : Sparse Principal Components Analysis.

    References
    ----------

    J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning
    for sparse coding (https://www.di.ens.fr/~fbach/mairal_icml09.pdf)

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import make_sparse_coded_signal
    >>> from sklearn.decomposition import DictionaryLearning
    >>> X, dictionary, code = make_sparse_coded_signal(
    ...     n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
    ...     random_state=42,
    ... )
    >>> dict_learner = DictionaryLearning(
    ...     n_components=15, transform_algorithm='lasso_lars', transform_alpha=0.1,
    ...     random_state=42,
    ... )
    >>> X_transformed = dict_learner.fit(X).transform(X)

    We can check the level of sparsity of `X_transformed`:

    >>> np.mean(X_transformed == 0)
    np.float64(0.52...)

    We can compare the average squared euclidean norm of the reconstruction
    error of the sparse coded signal relative to the squared euclidean norm of
    the original signal:

    >>> X_hat = X_transformed @ dict_learner.components_
    >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
    np.float64(0.05...)
    r]   rb   Nrc   rd   r7   r   r2   rF   r   r    r   r   >   r   r    r<   rA   r)   r   r   rh   r   r   r   r3   r   rf   r   r   r   r   _parameter_constraintsr*   r   r   F)r7   r2   rF   r   r   r   r   rh   r   r   r   r3   r   r   r   r   r   c          	          t                                          |||||	||           || _        || _        || _        || _        || _        |
| _        || _        || _	        || _
        || _        || _        d S r   )r   r   r]   r7   r2   rF   r   r   r   r   r3   r   r   )r   r]   r7   r2   rF   r   r   r   r   rh   r   r   r   r3   r   r   r   r   r   r   s                      r&   r   zDictionaryLearning.__init__"  s    , 	%	
 	
 	
 )
 *"" (*r(   c                 0    |                      |           | S )  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 for API consistency by convention.

        Returns
        -------
        self : object
            Returns the instance itself.
        )r   r   s      r&   rN   zDictionaryLearning.fitM  s    " 	1r(   Tri   c                    t          | j        | j                   d| j        z   }t          | j                  }t          | |          }| j        |j        d         }n| j        }t          ||| j	        | j
        | j        || j        | j        | j        | j        | j        | j        |d| j        | j                  \  }}}| _        || _        || _        |S )a  Fit the model from data in X and return the transformed data.

        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 for API consistency by convention.

        Returns
        -------
        V : ndarray of shape (n_samples, n_components)
            Transformed data.
        r#   r   Nrb   T)r7   rF   r2   r$   r   rh   r   r   r   r3   r   r   r   r   )r'   r   r   r   r   r   r]   rJ   r   r7   rF   r2   r   rh   r   r   r   r3   r   r   r   r   )	r   rY   r   r$   r   r]   VUEs	            r&   r   z DictionaryLearning.fit_transforma  s    $ 	d&84CUVVVVD..)$*;<<$""$71:LL,L .*] 3;nn]L%,,!!
 !
 !
1a$ r(   c                 &    | j         j        d         S r  r   r   rJ   r  s    r&   r  z"DictionaryLearning._n_features_out       %a((r(   c                 d    t                                                      }ddg|j        _        |S Nrp   rq   r   r   r  r  r  s     r&   r   z#DictionaryLearning.__sklearn_tags__  -    ww''))1:I0F-r(   r   )r   r   r   r   r   r   r   r   rL   ndarraycallabler  dict__annotations__r   rN   r   r   r  r  r   r  r  s   @r&   r   r   J  s        ~ ~@$(AtFCCCTJ$((4D8889$ 	XXh4???@$ 	q$v6667	$
 	**fd^445$ 	JMMMNN 
$ 	$hhxD&P&P&PRV%W$ 	HHT1d6BBBDI$ 	8T"$ 	bj$'$ 	bj$'$ 	Xt$$ 	I;$  	yk!$" 	(#$$ 	)%$& 	)'$( 	xx!T&IIIJ)$ $D   2 )+ !"&))+ )+ )+ )+ )+ )+ )+V   ( \5552 2 2 652h ) ) X)        r(   r   c                       e Zd ZU dZi d eeddd          dgd eeddd          gd	 eeddd          gd
 eddh          gddegd eeddd          gddgddej	        gd eh d          gd eeddd          dgd eeddd          dgddgddgddgddgddgd eeddd          gde
g eeddd          g eeddd          dgdZeed<   	 d1dddddd dd!ddd"d"dd"d"ddd#d$d% fd&Zd' Zd( Zd) Zd* Zd+ Z ed ,          d1d-            Z ed ,          d1d.            Zed/             Z fd0Z xZS )2r   a  Mini-batch dictionary learning.

    Finds a dictionary (a set of atoms) that performs well at sparsely
    encoding the fitted data.

    Solves the optimization problem::

       (U^*,V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
                    (U,V)
                    with || V_k ||_2 <= 1 for all  0 <= k < n_components

    ||.||_Fro stands for the Frobenius norm and ||.||_1,1 stands for
    the entry-wise matrix norm which is the sum of the absolute values
    of all the entries in the matrix.

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

    Parameters
    ----------
    n_components : int, default=None
        Number of dictionary elements to extract.

    alpha : float, default=1
        Sparsity controlling parameter.

    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.1

    fit_algorithm : {'lars', 'cd'}, default='lars'
        The algorithm used:

        - `'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.

    batch_size : int, default=256
        Number of samples in each mini-batch.

        .. versionchanged:: 1.3
           The default value of `batch_size` changed from 3 to 256 in version 1.3.

    shuffle : bool, default=True
        Whether to shuffle the samples before forming batches.

    dict_init : ndarray of shape (n_components, n_features), default=None
        Initial value of the dictionary for warm restart scenarios.

    transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp',             'threshold'}, default='omp'
        Algorithm used to transform the data:

        - `'lars'`: uses the least angle regression method
          (`linear_model.lars_path`);
        - `'lasso_lars'`: uses Lars to compute the Lasso solution.
        - `'lasso_cd'`: uses the coordinate descent method to compute the
          Lasso solution (`linear_model.Lasso`). `'lasso_lars'` will be faster
          if the estimated components are sparse.
        - `'omp'`: uses orthogonal matching pursuit to estimate the sparse
          solution.
        - `'threshold'`: squashes to zero all coefficients less than alpha from
          the projection ``dictionary * X'``.

    transform_n_nonzero_coefs : int, default=None
        Number of nonzero coefficients to target in each column of the
        solution. This is only used by `algorithm='lars'` and
        `algorithm='omp'`. If `None`, then
        `transform_n_nonzero_coefs=int(n_features / 10)`.

    transform_alpha : float, default=None
        If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
        penalty applied to the L1 norm.
        If `algorithm='threshold'`, `alpha` is the absolute value of the
        threshold below which coefficients will be squashed to zero.
        If `None`, defaults to `alpha`.

        .. versionchanged:: 1.2
            When None, default value changed from 1.0 to `alpha`.

    verbose : bool or int, default=False
        To control the verbosity of the procedure.

    split_sign : bool, default=False
        Whether to split the sparse feature vector into the concatenation of
        its negative part and its positive part. This can improve the
        performance of downstream classifiers.

    random_state : int, RandomState instance or None, default=None
        Used for initializing the dictionary when ``dict_init`` is not
        specified, randomly shuffling the data when ``shuffle`` is set to
        ``True``, and updating the dictionary. Pass an int for reproducible
        results across multiple function calls.
        See :term:`Glossary <random_state>`.

    positive_code : bool, default=False
        Whether to enforce positivity when finding the code.

        .. versionadded:: 0.20

    positive_dict : bool, default=False
        Whether to enforce positivity when finding the dictionary.

        .. versionadded:: 0.20

    transform_max_iter : int, default=1000
        Maximum number of iterations to perform if `algorithm='lasso_cd'` or
        `'lasso_lars'`.

        .. versionadded:: 0.22

    callback : callable, default=None
        A callable that gets invoked at the end of each iteration.

        .. versionadded:: 1.1

    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, 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)
        Components extracted from the data.

    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

    n_iter_ : int
        Number of iterations over the full dataset.

    n_steps_ : int
        Number of mini-batches processed.

        .. versionadded:: 1.1

    See Also
    --------
    DictionaryLearning : Find a dictionary that sparsely encodes data.
    MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
    SparseCoder : Find a sparse representation of data from a fixed,
        precomputed dictionary.
    SparsePCA : Sparse Principal Components Analysis.

    References
    ----------

    J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning
    for sparse coding (https://www.di.ens.fr/~fbach/mairal_icml09.pdf)

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import make_sparse_coded_signal
    >>> from sklearn.decomposition import MiniBatchDictionaryLearning
    >>> X, dictionary, code = make_sparse_coded_signal(
    ...     n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
    ...     random_state=42)
    >>> dict_learner = MiniBatchDictionaryLearning(
    ...     n_components=15, batch_size=3, transform_algorithm='lasso_lars',
    ...     transform_alpha=0.1, max_iter=20, random_state=42)
    >>> X_transformed = dict_learner.fit_transform(X)

    We can check the level of sparsity of `X_transformed`:

    >>> np.mean(X_transformed == 0) > 0.5
    np.True_

    We can compare the average squared euclidean norm of the reconstruction
    error of the sparse coded signal relative to the squared euclidean norm of
    the original signal:

    >>> X_hat = X_transformed @ dict_learner.components_
    >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
    np.float64(0.052...)
    r]   rb   Nrc   rd   r7   r   r2   r   r   r    rh   r   r   rf   r   r   >   r   r    r<   rA   r)   r   r   r3   r   r   r   r   r   )r   rF   r   r  r*   r   Tr   Fr   ru   )r7   r2   r   rh   r   r   r   r   r   r   r3   r   r   r   r   r   r   rF   r   c          	         t                                          |	|
|||||           || _        || _        || _        || _        || _        || _        || _        || _	        || _
        || _        || _        || _        || _        || _        d S r   )r   r   r]   r7   r2   r   r   r3   r   r   r   r   r   r   r   rF   )r   r]   r7   r2   r   rh   r   r   r   r   r   r   r3   r   r   r   r   r   r   rF   r   r   s                        r&   r   z$MiniBatchDictionaryLearning.__init__  s    0 	%	
 	
 	
 )
 *"$$(* "4r(   c                     | j         | _        | j        |j        d         | _        t          | j        | j                   d| j        z   | _        t          | j        |j        d                   | _	        d S )Nrb   r   r   )
r]   _n_componentsrJ   r'   r   r   _fit_algorithmrz   r   _batch_sizer   s     r&   _check_paramsz)MiniBatchDictionaryLearning._check_params  sn    !.%!"D 	t143EFFF&);; t
;;r(   c           	         | j         | j         }n4t          || j        |          \  }}}|ddt          j        f         |z  }| j        t          |          k    r|d| j        ddf         }nQt          j        |t          j        | j        t          |          z
  |j        d         f|j	                  f          }t          |d|j	        d          }t          j        |d	          }|S )
z!Initialization of the dictionary.N)r   rb   rn   r   F)rm   rn   copyW)requirements)r   r   r*  rL   r   r   concatenater   rJ   rn   r   require)r   rY   r   rZ   _r   s         r&   _initialize_dictz,MiniBatchDictionaryLearning._initialize_dict  s   >%JJ  .4%L     Aq* 111bj=)J6JZ00#$8d&8$8!!!$;<JJH+c*oo=z?OPQ?RS(.   J !3agERRR
Z
===
r(   c                    ||dz
  k     r	|dz   |z  }n|dz  |z   dz   |z
  }|dz   |z
  |dz   z  }| xj         |z  c_         | xj         |j        |z  |z  z  c_         | xj        |z  c_        | xj        |j        |z  |z  z  c_        dS )zUpdate the inner stats inplace.rb   r   N)_ArO   _B)r   rY   r   r   stepthetabetas          r&   _update_inner_statsz/MiniBatchDictionaryLearning._update_inner_stats  s    *q.  AX+EEMD(1,z9E	J&5195446D=:--413:
**r(   c           
         |j         d         }t          ||| j        | j        | j        | j        | j        | j                  }d|||z  z
  dz                                  z  | j        t          j        t          j
        |                    z  z   |z  }|                     ||||           t          |||| j        | j        | j        || j                   |S )z7Perform the update on the dictionary for one minibatch.r   )r.   r7   rh   r%   r2   r3   r   r   r   )rJ   rr   r+  r7   rh   r   r   r3   r   rL   rV   r=  r   r8  r9  r   )r   rY   rZ   r   r:  r   r   
batch_costs           r&   _minibatch_stepz+MiniBatchDictionaryLearning._minibatch_step  s    WQZ
 )*;',L	
 	
 	
 Az))a/44666j26"&,,///0
 	  D*d;;; 	GGL%'		
 		
 		
 		
 r(   c           
         |j         d         }|dz   }|t          d||z            k    r!| j        rt          d| d| d|            dS | j        || _        n0||dz   z  }	t          |	d          }	| j        d|	z
  z  ||	z  z   | _        | j        r t          d| d| d| d	| j                    t          j        ||z
            | j        z  }
| j        dk    r)|
| j        k    r| j        rt          d
| d|            dS | j	        | j        | j	        k     rd| _
        | j        | _	        n| xj
        dz  c_
        | j        .| j
        | j        k    r| j        rt          d| d|            dS dS )a  Helper function to encapsulate the early stopping logic.

        Early stopping is based on two factors:
        - A small change of the dictionary between two minibatch updates. This is
          controlled by the tol parameter.
        - No more improvement on a smoothed estimate of the objective function for a
          a certain number of consecutive minibatch updates. This is controlled by
          the max_no_improvement parameter.
        r   rb   r   zMinibatch step /z: mean batch cost: FNz, ewa cost: z,Converged (small dictionary change) at step Tz>Converged (lack of improvement in objective function) at step )rJ   rz   r3   r   	_ewa_costr   r   r*  rF   _ewa_cost_min_no_improvementr   )r   rY   r?  new_dictold_dictr[   r:  n_stepsr   r7   	dict_diffs              r&   _check_convergencez.MiniBatchDictionaryLearning._check_convergence  s    WQZ
 ax 3sI
23333| YWWWwWW:WWXXX5
 >!'DNN)a-0EqMME!^q5y9J<NNDN< 	<$ < < < << <+/>< <   K8 344t7II	8a<<I11| WUTUUGUUVVV4 %$:L)L)L#$D !%D  A%   #/$(???| 0#0 0&-0 0   4ur(   ri   c           
         t          | |t          j        t          j        gdd          }|                     |           t          | j                  | _        |                     || j                  }|	                                }| j
        r/|	                                }| j        
                    |           n|}|j        \  }}| j        rt          d           t          j        | j        | j        f|j                  | _        t          j        || j        f|j                  | _        d| _        d| _        d| _        t-          || j                  }t1          j        |          }t5          t          j        || j        z                      }	| j        |	z  }
d}t;          t=          |
          |          D ]v\  }}||         }|                     ||| j        |          }|                      |||||||
          r n0| j!        !| !                    tE                                 ||dd<   w|d	z   | _#        t          j        | j#        |	z            | _$        || _%        | S )
r  rl   F)rn   rm   r0  r   r/  Nr   r   rb   )&r   rL   rp   rq   r-  r   r   _random_stater6  r0  r   rJ   r3   r   r   r*  rn   r8  r9  rC  rD  rE  r   r,  	itertoolscyclerS   ceilr2   r   r   r@  rJ  r   r   n_steps_r   r   )r   rY   r   rZ   rG  X_trainr[   r\   batchesn_steps_per_iterrH  ibatchX_batchr?  s                  r&   rN   zMiniBatchDictionaryLearning.fit\  sn   $ !BJ
33U
 
 
 	1/0ABB**1d.@AA
??$$< 	ffhhG&&w////G '	:< 	%#$$$ (!34GM
 
 
 (J(:;7=QQQ ! i)9::/'**rwy43C'CDDEE-"22E'NNG44 	% 	%HAuenG--T%7 J &&Z9a    }(fhh'''$HQQQKKAwt}/??@@%r(   c                 ^   t          | d          }t          | |t          j        t          j        gd|           }|s|                     |           t          | j                  | _        | 	                    || j                  }d| _
        t          j        | j        | j        f|j                  | _        t          j        |j        d         | j        f|j                  | _        n| j        }|                     ||| j        | j
                   || _        | xj
        dz  c_
        | S )a  Update the model using the data in X as a mini-batch.

        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 for API consistency by convention.

        Returns
        -------
        self : object
            Return the instance itself.
        r   rl   )rn   rm   r   r   r/  rb   )r   r   rL   rp   rq   r-  r   r   rL  r6  rP  r   r*  rn   r8  rJ   r9  r   r@  )r   rY   r   has_componentsrZ   s        r&   partial_fitz'MiniBatchDictionaryLearning.partial_fit  s   $ !}55!BJ
33.FX
 
 
  	*q!!!!3D4E!F!FD..q$2DEEJDMh 2D4FGqwWWWDGh
D,>?qwOOODGG)JQ
D,>NNN%r(   c                 &    | j         j        d         S r  r  r  s    r&   r  z+MiniBatchDictionaryLearning._n_features_out  r  r(   c                 d    t                                                      }ddg|j        _        |S r   r!  r  s     r&   r   z,MiniBatchDictionaryLearning.__sklearn_tags__  r"  r(   r   )r   r   r   r   r   r   r   r   rL   r#  r$  r  r%  r&  r   r-  r6  r=  r@  rJ  r   rN   rY  r  r  r   r  r  s   @r&   r   r     s        N N`$(AtFCCCTJ$((4D8889$ 	XXh4???@$ 	**dF^445	$
 	4"$ 	xx!T&AAAB$ 	I;$ 	dBJ'$ 	JMMMNN 
$ 	$hhxD&P&P&PRV%W$ 	HHT1d6BBBDI$ 	I;$ 	yk$  	(!$" 	)#$$ 	)%$& 	xx!T&IIIJ'$( 8$q$v6667'x!T&III4P-$ $ $D   6 . !"&-. . . . . . .`< < <  :+ + +$ $ $LB B BH \555O O O 65Ob \555* * * 65*X ) ) X)        r(   r   )NNFNF)r   )6r   rM  r   r   numbersr   r   numpyrL   joblibr   scipyr   baser   r	   r
   r   linear_modelr   r   r   r   utilsr   r   r   r   utils._param_validationr   r   r   utils.extmathr   r   r   utils.parallelr   r   utils.validationr   r   r'   ra   rs   rr   r   r   r   r   r   r   r   r   rI   r(   r&   <module>rg     s    
     



  " " " " " " " "     # # # # # #                  F E E E E E E E E E E E Q Q Q Q Q Q Q Q Q Q Q Q K K K K K K K K K K ? ? ? ? ? ? ? ? ? ? . . . . . . . . = = = = = = = =
 
 
 
	d5 d5 d5 d5 d5N ^#nt$d#JMMMNN
 %HXq$vFFFM(4D888$?Kt$Xh4???@T"!{;K! $ #''  4 

	e e e e- ,eX 

	M M M M Mh 
M5 M5 M5 M5`n( n( n(b ^!{:tVn--.$HXq$vFFFG	  #(   O% 'O% O% O% O% O%d ^:vtn--.#$HXq$vFFFG	  #(   #p9 p9 p9 p9 p9fF4 F4 F4 F4 F479I F4 F4 F4RM" M" M" M" M"#] M" M" M"`T T T T T*M T T Tn
B	 B	 B	 B	 B	"3] B	 B	 B	 B	 B	r(   