
    -i                     <   S r SSKrSSKJr  SSKJr  SSKrSSKJ	r	J
r
  SSKJrJrJr  SS	KJrJrJrJrJr  SS
KJr  SSKJrJr  S rS8S jrS rS rSS.S jrSSS.S jrSSS.S jr \" SS/\" \SSSS9/\" \SSSS9/\" \SSSS9\" S15      /\" 1 Sk5      /S\" S15      /S/S/\" SS15      /S .	S!S"9S#SSSS!SSS$.S% j5       r!S#SSSS!SSS$.S& jr"S#SSS'SS(.S) jr#SS*.S+ jr$S9S, jr%S:S- jr&S:S. jr'S;S/ jr(S0 r) S9S1 jr*S2 r+S<S3 jr,S9S4 jr-S!S5.S6 jr.S7 r/g)=zEUtilities to perform optimal mathematical operations in scikit-learn.    N)partial)Integral)linalgsparse   )Interval
StrOptionsvalidate_params   )_average_is_numpy_namespace_nanmeandeviceget_namespace)csr_row_norms)check_arraycheck_random_statec                     [         R                  " U SS9n [         R                  " U R                  [         R                  5      (       a  [
        R                  " S[        5        [         R                  " X 5      $ )a4  Squared Euclidean or Frobenius norm of x.

Faster than norm(x) ** 2.

Parameters
----------
x : array-like
    The input array which could be either be a vector or a 2 dimensional array.

Returns
-------
float
    The Euclidean norm when x is a vector, the Frobenius norm when x
    is a matrix (2-d array).
K)orderzYArray type is integer, np.dot may overflow. Data should be float type to avoid this issue)	npravel
issubdtypedtypeintegerwarningswarnUserWarningdotxs    H/var/www/html/venv/lib/python3.13/site-packages/sklearn/utils/extmath.pysquared_normr#      sT      	#A	}}QWWbjj))@ 	
 66!<    Fc                    [         R                  " U 5      (       a:  U R                  5       n [        U 5      nU(       d  [        R
                  " U5      nU$ [        U 5      u  p4[        U5      (       a?  [        R                  " U 5      n [        R                  " SX 5      nUR                  U5      nOUR                  UR                  X 5      SS9nU(       d  UR                  U5      nU$ )a  Row-wise (squared) Euclidean norm of X.

Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
matrices and does not create an X.shape-sized temporary.

Performs no input validation.

Parameters
----------
X : array-like
    The input array.
squared : bool, default=False
    If True, return squared norms.

Returns
-------
array-like
    The row-wise (squared) Euclidean norm of X.
zij,ij->ir   axis)r   issparsetocsrr   r   sqrtr   r   asarrayeinsumsummultiply)Xsquarednormsxp_s        r"   	row_normsr4   /   s    ( qGGIa GGENE L a r""

1AIIj!/EJJu%EFF2;;q,1F5EGGENELr$   c                     [        U 5      u  pUR                  R                  U 5      u  p4US:  d  UR                  * $ U$ )a0  Compute logarithm of determinant of a square matrix.

The (natural) logarithm of the determinant of a square matrix
is returned if det(A) is non-negative and well defined.
If the determinant is zero or negative returns -Inf.

Equivalent to : np.log(np.det(A)) but more robust.

Parameters
----------
A : array_like of shape (n, n)
    The square matrix.

Returns
-------
logdet : float
    When det(A) is strictly positive, log(det(A)) is returned.
    When det(A) is non-positive or not defined, then -inf is returned.

See Also
--------
numpy.linalg.slogdet : Compute the sign and (natural) logarithm of the determinant
    of an array.

Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import fast_logdet
>>> a = np.array([[5, 1], [2, 8]])
>>> fast_logdet(a)
np.float64(3.6375861597263857)
r   )r   r   slogdetinf)Ar2   r3   signlds        r"   fast_logdetr;   U   s>    B !EByy  #HD!8wIr$   c                     [        U S5      (       a7  [        U R                  5      U R                  S   U R                  S   -  -  nU$ U c  SO([        U S:g  R	                  5       5      U R
                  -  nU$ )a  Compute density of a sparse vector.

Parameters
----------
w : {ndarray, sparse matrix}
    The input data can be numpy ndarray or a sparse matrix.

Returns
-------
float
    The density of w, between 0 and 1.

Examples
--------
>>> from scipy import sparse
>>> from sklearn.utils.extmath import density
>>> X = sparse.random(10, 10, density=0.25, random_state=0)
>>> density(X)
0.25
toarrayr   r   )hasattrfloatnnzshaper-   size)wds     r"   densityrE   }   si    * q)!%%LAGGAJ34 H AqAvlln 5 >Hr$   )dense_outputc                V   [        X5      u  p4U R                  S:  d  UR                  S:  Ga  [        R                  " U 5      (       ai  [        R
                  " US5      nUR                  UR                  S   S45      nX-  nUR                  " U R                  S   /UR                  SS Q76 nO[        R                  " U5      (       aR  U R                  SU R                  S   5      nX-  nUR                  " / U R                  SS QUR                  S   P76 nO+UR                  S:X  a  SOSn	UR                  XSU	/S9nOX-  n[        R                  " U 5      (       aC  [        R                  " U5      (       a(  U(       a!  [        US5      (       a  UR                  5       $ U$ )	a  Dot product that handle the sparse matrix case correctly.

Parameters
----------
a : {ndarray, sparse matrix}
b : {ndarray, sparse matrix}
dense_output : bool, default=False
    When False, ``a`` and ``b`` both being sparse will yield sparse output.
    When True, output will always be a dense array.

Returns
-------
dot_product : {ndarray, sparse matrix}
    Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``.

Examples
--------
>>> from scipy.sparse import csr_matrix
>>> from sklearn.utils.extmath import safe_sparse_dot
>>> X = csr_matrix([[1, 2], [3, 4], [5, 6]])
>>> dot_product = safe_sparse_dot(X, X.T)
>>> dot_product.toarray()
array([[ 5, 11, 17],
       [11, 25, 39],
       [17, 39, 61]])
r   r   r   N)axesr=   )r   ndimr   r(   r   rollaxisreshaperA   	tensordotr>   r=   )
abrF   r2   r3   b_b_2dreta_2db_axiss
             r"   safe_sparse_dotrV      sV   6 !EBvvzQVVaZ??1 Q#B::qwwr{B/0D(C++aggaj8288AB<8C__Q 99R-D(C++8qwws|8QWWQZ8C 66Q;RBF,,q2v,,7Ce 	OOAC##{{}Jr$   auto)power_iteration_normalizerrandom_statec                0    [        U SS9n [        U UUUUS9$ )aN  Compute an orthonormal matrix whose range approximates the range of A.

Parameters
----------
A : {array-like, sparse matrix} of shape (n_samples, n_features)
    The input data matrix.

size : int
    Size of the return array.

n_iter : int
    Number of power iterations used to stabilize the result.

power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
    Whether the power iterations are normalized with step-by-step
    QR factorization (the slowest but most accurate), 'none'
    (the fastest but numerically unstable when `n_iter` is large, e.g.
    typically 5 or larger), or 'LU' factorization (numerically stable
    but can lose slightly in accuracy). The 'auto' mode applies no
    normalization if `n_iter` <= 2 and switches to LU otherwise.

    .. versionadded:: 0.18

random_state : int, RandomState instance or None, default=None
    The seed of the pseudo random number generator to use when shuffling
    the data, i.e. getting the random vectors to initialize the algorithm.
    Pass an int for reproducible results across multiple function calls.
    See :term:`Glossary <random_state>`.

Returns
-------
Q : ndarray of shape (size, size)
    A projection matrix, the range of which approximates well the range of the
    input matrix A.

Notes
-----

Follows Algorithm 4.3 of
:arxiv:`"Finding structure with randomness:
Stochastic algorithms for constructing approximate matrix decompositions"
<0909.4061>`
Halko, et al. (2009)

An implementation of a randomized algorithm for principal component
analysis
A. Szlam et al. 2014

Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import randomized_range_finder
>>> A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> randomized_range_finder(A, size=2, n_iter=2, random_state=42)
array([[-0.214,  0.887],
       [-0.521,  0.249],
       [-0.826, -0.388]])
Taccept_sparserB   n_iterrX   rY   )r   _randomized_range_finder)r8   rB   r^   rX   rY   s        r"   randomized_range_finderr`      s-    z 	AT*A#	#=! r$   c                P   [        U 5      u  pV[        U5      nUR                  UR                  U R                  S   U4S95      n[        U S5      (       a9  UR                  U R                  SS9(       a  UR                  XpR                  SS9nU(       a  UR                  U[        U 5      S9nUS	:X  a,  US
::  a  SnO;U(       a  [        R                  " S5        SnOSnOUS:X  a  U(       a  [        S5      eU(       a  [        UR                  R                  SS9nO[        [        R                  SSS9nUS:X  a  Un	O#US:X  a  [        [        R                   SSS9n	OS n	[#        U5       H&  n
U	" X-  5      u  pzU	" U R$                  U-  5      u  pzM(     U" X-  5      u  pzU$ )z9Body of randomized_range_finder without input validation.r   )rB   r   zreal floating)kindFcopyr   rW   r   nonezArray API does not support LU factorization, falling back to QR instead. Set `power_iteration_normalizer='QR'` explicitly to silence this warning.QRLUz[Array API does not support LU factorization. Set `power_iteration_normalizer='QR'` instead.reduced)modeeconomic)rj   check_finiteT)	permute_lrl   c                 
    U S 4$ N r    s    r"   <lambda>*_randomized_range_finder.<locals>.<lambda>Y  s    4yr$   )r   r   r+   normalrA   r>   isdtyper   astyper   r   r   
ValueErrorr   r   qrlurangeT)r8   rB   r^   rX   rY   r2   is_array_api_compliantQqr_normalizer
normalizerr3   s              r"   r_   r_     s    "/q!1B%l3L
 	

<&&QWWQZ,>&?@Aq'rzz!''zHIIauI- JJqJ+ "V+Q;)/&#MM!
 *.&)-&	#t	+0F9
 	

 		9=  		
O!T)"
	#t	+VYY$UK
(
 6]!% !##'"1  DAHr$   z
array-likezsparse matrixleft)closed>   rh   rg   rW   rf   booleanrY   gesddgesvd	Mn_componentsn_oversamplesr^   rX   	transpose	flip_signrY   svd_lapack_driverT)prefer_skip_nested_validation
   )r   r^   rX   r   r   rY   r   c                8    [        U SS9n [        U UUUUUUUUS9	$ )a  Compute a truncated randomized SVD.

This method solves the fixed-rank approximation problem described in [1]_
(problem (1.5), p5).

Refer to
:ref:`sphx_glr_auto_examples_applications_wikipedia_principal_eigenvector.py`
for a typical example where the power iteration algorithm is used to rank web pages.
This algorithm is also known to be used as a building block in Google's PageRank
algorithm.

Parameters
----------
M : {array-like, sparse matrix} of shape (n_samples, n_features)
    Matrix to decompose.

n_components : int
    Number of singular values and vectors to extract.

n_oversamples : int, default=10
    Additional number of random vectors to sample the range of `M` so as
    to ensure proper conditioning. The total number of random vectors
    used to find the range of `M` is `n_components + n_oversamples`. Smaller
    number can improve speed but can negatively impact the quality of
    approximation of singular vectors and singular values. Users might wish
    to increase this parameter up to `2*k - n_components` where k is the
    effective rank, for large matrices, noisy problems, matrices with
    slowly decaying spectrums, or to increase precision accuracy. See [1]_
    (pages 5, 23 and 26).

n_iter : int or 'auto', default='auto'
    Number of power iterations. It can be used to deal with very noisy
    problems. When 'auto', it is set to 4, unless `n_components` is small
    (< .1 * min(X.shape)) in which case `n_iter` is set to 7.
    This improves precision with few components. Note that in general
    users should rather increase `n_oversamples` before increasing `n_iter`
    as the principle of the randomized method is to avoid usage of these
    more costly power iterations steps. When `n_components` is equal
    or greater to the effective matrix rank and the spectrum does not
    present a slow decay, `n_iter=0` or `1` should even work fine in theory
    (see [1]_ page 9).

    .. versionchanged:: 0.18

power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
    Whether the power iterations are normalized with step-by-step
    QR factorization (the slowest but most accurate), 'none'
    (the fastest but numerically unstable when `n_iter` is large, e.g.
    typically 5 or larger), or 'LU' factorization (numerically stable
    but can lose slightly in accuracy). The 'auto' mode applies no
    normalization if `n_iter` <= 2 and switches to LU otherwise.

    .. versionadded:: 0.18

transpose : bool or 'auto', default='auto'
    Whether the algorithm should be applied to M.T instead of M. The
    result should approximately be the same. The 'auto' mode will
    trigger the transposition if M.shape[1] > M.shape[0] since this
    implementation of randomized SVD tend to be a little faster in that
    case.

    .. versionchanged:: 0.18

flip_sign : bool, default=True
    The output of a singular value decomposition is only unique up to a
    permutation of the signs of the singular vectors. If `flip_sign` is
    set to `True`, the sign ambiguity is resolved by making the largest
    loadings for each component in the left singular vectors positive.

random_state : int, RandomState instance or None, default='warn'
    The seed of the pseudo random number generator to use when
    shuffling the data, i.e. getting the random vectors to initialize
    the algorithm. Pass an int for reproducible results across multiple
    function calls. See :term:`Glossary <random_state>`.

    .. versionchanged:: 1.2
        The default value changed from 0 to None.

svd_lapack_driver : {"gesdd", "gesvd"}, default="gesdd"
    Whether to use the more efficient divide-and-conquer approach
    (`"gesdd"`) or more general rectangular approach (`"gesvd"`) to compute
    the SVD of the matrix B, which is the projection of M into a low
    dimensional subspace, as described in [1]_.

    .. versionadded:: 1.2

Returns
-------
u : ndarray of shape (n_samples, n_components)
    Unitary matrix having left singular vectors with signs flipped as columns.
s : ndarray of shape (n_components,)
    The singular values, sorted in non-increasing order.
vh : ndarray of shape (n_components, n_features)
    Unitary matrix having right singular vectors with signs flipped as rows.

Notes
-----
This algorithm finds a (usually very good) approximate truncated
singular value decomposition using randomization to speed up the
computations. It is particularly fast on large matrices on which
you wish to extract only a small number of components. In order to
obtain further speed up, `n_iter` can be set <=2 (at the cost of
loss of precision). To increase the precision it is recommended to
increase `n_oversamples`, up to `2*k-n_components` where k is the
effective rank. Usually, `n_components` is chosen to be greater than k
so increasing `n_oversamples` up to `n_components` should be enough.

References
----------
.. [1] :arxiv:`"Finding structure with randomness:
  Stochastic algorithms for constructing approximate matrix decompositions"
  <0909.4061>`
  Halko, et al. (2009)

.. [2] A randomized algorithm for the decomposition of matrices
  Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert

.. [3] An implementation of a randomized algorithm for principal component
  analysis A. Szlam et al. 2014

Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import randomized_svd
>>> a = np.array([[1, 2, 3, 5],
...               [3, 4, 5, 6],
...               [7, 8, 9, 10]])
>>> U, s, Vh = randomized_svd(a, n_components=2, random_state=0)
>>> U.shape, s.shape, Vh.shape
((3, 2), (2,), (2, 4))
Tr[   )r   r   r^   rX   r   r   rY   r   )r   _randomized_svdr   s	            r"   randomized_svdr   h  s9    z 	AT*A	!##=!+
 
r$   c                z   [        U 5      u  p[        R                  " U 5      (       aW  U R                  S;   aG  [        R
                  " SR                  [        U 5      R                  5      [        R                  5        [        U5      nX-   nU R                  u  pUS:X  a   US[        U R                  5      -  :  a  SOSnUS:X  a  X:  nU(       a  U R                  n [        U UUUUS9nUR                  U -  nU
(       a  U	R                  R                  USS	9u  nnnO[        R                  " USUS
9u  nnnAUU-  nU(       a%  U(       d  [!        UU5      u  nnO[!        UUSS9u  nnU(       a.  USU2SS24   R                  USU USS2SU24   R                  4$ USS2SU24   USU USU2SS24   4$ )z0Body of randomized_svd without input validation.)lildokzCCalculating SVD of a {} is expensive. csr_matrix is more efficient.rW   g?      r]   F)full_matrices)r   lapack_driver)u_based_decisionN)r   r   r(   formatr   r   type__name__SparseEfficiencyWarningr   rA   minrz   r_   r   svdsvd_flip)r   r   r   r^   rX   r   r   rY   r   r2   r{   n_random	n_samples
n_featuresr|   BUhatsVtUs                       r"   r   r     s    "/q!1Bqahh.8,,2F473C3C,D**	
 &l3L+HGGI #S3qww<%77QF*	CC 	#=!	A 	
aA iimmAUm;a
 jjU2C
a 	
	DAQOEAr QU;EAr-<-"#%%q,'71m|m;K9L9N9NNNM\M!"Am|$4b,9I6JJJr$   module)r   r^   rX   	selectionrY   c          
         US:X  a
  [        5       eUS:X  ai  [        U UUUUSUS9u  pxn	USS2SU24   n
USU n[        R                  " SU	SU2SS24   USS2SU24   5      n[        R                  " U5      nX-  nX4$ [        SU-  5      e)aK  Computes a truncated eigendecomposition using randomized methods

This method solves the fixed-rank approximation problem described in the
Halko et al paper.

The choice of which components to select can be tuned with the `selection`
parameter.

.. versionadded:: 0.24

Parameters
----------
M : ndarray or sparse matrix
    Matrix to decompose, it should be real symmetric square or complex
    hermitian

n_components : int
    Number of eigenvalues and vectors to extract.

n_oversamples : int, default=10
    Additional number of random vectors to sample the range of M so as
    to ensure proper conditioning. The total number of random vectors
    used to find the range of M is n_components + n_oversamples. Smaller
    number can improve speed but can negatively impact the quality of
    approximation of eigenvectors and eigenvalues. Users might wish
    to increase this parameter up to `2*k - n_components` where k is the
    effective rank, for large matrices, noisy problems, matrices with
    slowly decaying spectrums, or to increase precision accuracy. See Halko
    et al (pages 5, 23 and 26).

n_iter : int or 'auto', default='auto'
    Number of power iterations. It can be used to deal with very noisy
    problems. When 'auto', it is set to 4, unless `n_components` is small
    (< .1 * min(X.shape)) in which case `n_iter` is set to 7.
    This improves precision with few components. Note that in general
    users should rather increase `n_oversamples` before increasing `n_iter`
    as the principle of the randomized method is to avoid usage of these
    more costly power iterations steps. When `n_components` is equal
    or greater to the effective matrix rank and the spectrum does not
    present a slow decay, `n_iter=0` or `1` should even work fine in theory
    (see Halko et al paper, page 9).

power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
    Whether the power iterations are normalized with step-by-step
    QR factorization (the slowest but most accurate), 'none'
    (the fastest but numerically unstable when `n_iter` is large, e.g.
    typically 5 or larger), or 'LU' factorization (numerically stable
    but can lose slightly in accuracy). The 'auto' mode applies no
    normalization if `n_iter` <= 2 and switches to LU otherwise.

selection : {'value', 'module'}, default='module'
    Strategy used to select the n components. When `selection` is `'value'`
    (not yet implemented, will become the default when implemented), the
    components corresponding to the n largest eigenvalues are returned.
    When `selection` is `'module'`, the components corresponding to the n
    eigenvalues with largest modules are returned.

random_state : int, RandomState instance, default=None
    The seed of the pseudo random number generator to use when shuffling
    the data, i.e. getting the random vectors to initialize the algorithm.
    Pass an int for reproducible results across multiple function calls.
    See :term:`Glossary <random_state>`.

Notes
-----
This algorithm finds a (usually very good) approximate truncated
eigendecomposition using randomized methods to speed up the computations.

This method is particularly fast on large matrices on which
you wish to extract only a small number of components. In order to
obtain further speed up, `n_iter` can be set <=2 (at the cost of
loss of precision). To increase the precision it is recommended to
increase `n_oversamples`, up to `2*k-n_components` where k is the
effective rank. Usually, `n_components` is chosen to be greater than k
so increasing `n_oversamples` up to `n_components` should be enough.

Strategy 'value': not implemented yet.
Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good
candidates for a future implementation.

Strategy 'module':
The principle is that for diagonalizable matrices, the singular values and
eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a
singular value of A. This method relies on a randomized SVD to find the n
singular components corresponding to the n singular values with largest
modules, and then uses the signs of the singular vectors to find the true
sign of t: if the sign of left and right singular vectors are different
then the corresponding eigenvalue is negative.

Returns
-------
eigvals : 1D array of shape (n_components,) containing the `n_components`
    eigenvalues selected (see ``selection`` parameter).
eigvecs : 2D array of shape (M.shape[0], n_components) containing the
    `n_components` eigenvectors corresponding to the `eigvals`, in the
    corresponding order. Note that this follows the `scipy.linalg.eigh`
    convention.

See Also
--------
:func:`randomized_svd`

References
----------
* :arxiv:`"Finding structure with randomness:
  Stochastic algorithms for constructing approximate matrix decompositions"
  (Algorithm 4.3 for strategy 'module') <0909.4061>`
  Halko, et al. (2009)
valuer   F)r   r   r^   rX   r   rY   Nzji,ij->jzInvalid `selection`: %r)NotImplementedErrorr   r   r,   r9   rv   )r   r   r   r^   rX   r   rY   r   Sr   eigvecseigvalsdiag_VtUsignss                 r"   _randomized_eigshr   _  s    n G!##	h	 "%''A%
b A}}$%M\" 99ZM\M1,<)=qM\MAQ?RS!/
  2Y>??r$   r&   c                H   Uc/  [         R                  " U 5      n [         R                  " U5      nSnO,[         R                  " U 5      n [         R                  " U5      nU R                  UR                  :w  a)  [         R                  " U R                  XR
                  S9n[         R                  " [         R                  " U 5      5      n[        U R                  5      nSXB'   [         R                  " U5      n[         R                  " U5      nU H  n[         R                  " U R                  5      nX:H  n	X   X'   [         R                  " [         R                  " X5      U5      n
[         R                  " X:  Xu5      n[         R                  " X5      nUnM     WU4$ )a  Return an array of the weighted modal (most common) value in the passed array.

If there is more than one such value, only the first is returned.
The bin-count for the modal bins is also returned.

This is an extension of the algorithm in scipy.stats.mode.

Parameters
----------
a : array-like of shape (n_samples,)
    Array of which values to find mode(s).
w : array-like of shape (n_samples,)
    Array of weights for each value.
axis : int, default=0
    Axis along which to operate. Default is 0, i.e. the first axis.

Returns
-------
vals : ndarray
    Array of modal values.
score : ndarray
    Array of weighted counts for each mode.

See Also
--------
scipy.stats.mode: Calculates the Modal (most common) value of array elements
    along specified axis.

Examples
--------
>>> from sklearn.utils.extmath import weighted_mode
>>> x = [4, 1, 4, 2, 4, 2]
>>> weights = [1, 1, 1, 1, 1, 1]
>>> weighted_mode(x, weights)
(array([4.]), array([3.]))

The value 4 appears three times: with uniform weights, the result is
simply the mode of the distribution.

>>> weights = [1, 3, 0.5, 1.5, 1, 2]  # deweight the 4's
>>> weighted_mode(x, weights)
(array([2.]), array([3.5]))

The value 2 has the highest score: it appears twice with weights of
1.5 and 2: the sum of these is 3.5.
r   r   r   )r   r   r+   rA   fullr   uniquelistzerosexpand_dimsr-   wheremaximum)rO   rC   r'   scores	testshapeoldmostfreq	oldcountsscoretemplateindcountsmostfrequents               r"   weighted_moder     s)   ^ |HHQKHHQKJJqMJJqMww!''GGAGGQgg.YYrxx{#FQWWIIO((9%K#I88AGG$jx 6=xx 2EGJJv1	"  ""r$   c                    U  Vs/ s H  n[         R                  " U5      PM     n nS U  5       n[         R                  " U5      nUR                  [	        U 5      S5      R
                  nUc'  [         R                  " U 6 n[         R                  " XES9n[        U 5       H  u  pgX   USS2U4      USS2U4'   M     U$ s  snf )a  Generate a cartesian product of input arrays.

Parameters
----------
arrays : list of array-like
    1-D arrays to form the cartesian product of.
out : ndarray of shape (M, len(arrays)), default=None
    Array to place the cartesian product in.

Returns
-------
out : ndarray of shape (M, len(arrays))
    Array containing the cartesian products formed of input arrays.
    If not provided, the `dtype` of the output array is set to the most
    permissive `dtype` of the input arrays, according to NumPy type
    promotion.

    .. versionadded:: 1.2
       Add support for arrays of different types.

Notes
-----
This function may not be used on more than 32 arrays
because the underlying numpy functions do not support it.

Examples
--------
>>> from sklearn.utils.extmath import cartesian
>>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
array([[1, 4, 6],
       [1, 4, 7],
       [1, 5, 6],
       [1, 5, 7],
       [2, 4, 6],
       [2, 4, 7],
       [2, 5, 6],
       [2, 5, 7],
       [3, 4, 6],
       [3, 4, 7],
       [3, 5, 6],
       [3, 5, 7]])
c              3   8   #    U  H  n[        U5      v   M     g 7fro   )len).0r!   s     r"   	<genexpr>cartesian.<locals>.<genexpr>p  s     $VSVVVs   rI   Nr   )	r   r+   indicesrM   r   rz   result_type
empty_like	enumerate)arraysoutr!   rA   ixr   narrs           r"   	cartesianr   D  s    V &,,VbjjmVF,$V$E	E	B	CK	$	&	&B
{'mmB,F#IbAh'AqD	 $ J -s    C c                    [        X4 Vs/ s H	  o3c  M  UPM     sn6 u  pEU(       a  UR                  UR                  U R                  5      SS9nUR	                  U R                  R
                  S   [        U 5      S9nXgU R                  R
                  S   -  -   nUR                  UR                  UR                  U R                  S5      USS95      n	X	[        R                  SS24   -  n Ub  XSS2[        R                  4   -  nX4$ UR                  UR                  U5      SS9n
UR	                  UR
                  S   [        U5      S9nXUR
                  S   -  -   nUR                  UR                  UR                  US5      USS95      n	U b  X	[        R                  SS24   -  n XSS2[        R                  4   -  nX4$ s  snf )aP  Sign correction to ensure deterministic output from SVD.

Adjusts the columns of u and the rows of v such that the loadings in the
columns in u that are largest in absolute value are always positive.

If u_based_decision is False, then the same sign correction is applied to
so that the rows in v that are largest in absolute value are always
positive.

Parameters
----------
u : ndarray
    Parameters u and v are the output of `linalg.svd` or
    :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner
    dimensions so one can compute `np.dot(u * s, v)`.
    u can be None if `u_based_decision` is False.

v : ndarray
    Parameters u and v are the output of `linalg.svd` or
    :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner
    dimensions so one can compute `np.dot(u * s, v)`. The input v should
    really be called vt to be consistent with scipy's output.
    v can be None if `u_based_decision` is True.

u_based_decision : bool, default=True
    If True, use the columns of u as the basis for sign flipping.
    Otherwise, use the rows of v. The choice of which variable to base the
    decision on is generally algorithm dependent.

Returns
-------
u_adjusted : ndarray
    Array u with adjusted columns and the same dimensions as u.

v_adjusted : ndarray
    Array v with adjusted rows and the same dimensions as v.
Nr   r&   r   re   )rI   )r   argmaxabsrz   arangerA   r   r9   takerM   r   newaxis)uvr   rO   r2   r3   max_abs_u_colsshiftr   r   max_abs_v_rowss              r"   r   r     s   L v?v!Av?@EB266!##;Q7		!##))A,vay	9 13399Q<#77

133 6aHI	2::q=!!=q"**}%%A 4K 266!915		!''!*VAY	7 1771:#55

1e 4gAFG=rzz1}%%A	1bjj=!!4K) @s
   GGc                 t   [        U 5      u  p#U(       a  UR                  U SS9n UR                  UR                  U SS9S5      nX-  n [	        U5      (       a*  [
        R                  " U [
        R                  " U 5      S9  OUR                  U 5      n UR                  UR                  U SS9S5      nX-  n U $ )a  
Calculate the softmax function.

The softmax function is calculated by
np.exp(X) / np.sum(np.exp(X), axis=1)

This will cause overflow when large values are exponentiated.
Hence the largest value in each row is subtracted from each data
point to prevent this.

Parameters
----------
X : array-like of float of shape (M, N)
    Argument to the logistic function.

copy : bool, default=True
    Copy X or not.

Returns
-------
out : ndarray of shape (M, N)
    Softmax function evaluated at every point in x.
Trc   r   r&   )rI   r   )r   )r   r+   rM   maxr   r   expr-   )r/   rd   r2   r{   max_probsum_probs         r"   softmaxr     s    0 "/q!1BJJqtJ$zz"&&&+W5HMA2
qbjjm$ FF1Izz"&&&+W5HMAHr$   c                     U R                  5       nX!:  a-  [        R                  " U 5      (       a  [        S5      eXU-
  -   n U $ )a	  Ensure `X.min()` >= `min_value`.

Parameters
----------
X : array-like
    The matrix to make non-negative.
min_value : float, default=0
    The threshold value.

Returns
-------
array-like
    The thresholded array.

Raises
------
ValueError
    When X is sparse.
z{Cannot make the data matrix nonnegative because it is sparse. Adding a value to every entry would make it no longer sparse.)r   r   r(   rv   )r/   	min_valuemin_s      r"   make_nonnegativer     sJ    ( 557D??1-  T!"Hr$   c                     [         R                  " UR                  [         R                  5      (       a:  UR                  R                  S:  a   U " U/UQ70 UDS[         R
                  0D6nU$ U " U/UQ70 UD6nU$ )ax  
This function provides numpy accumulator functions with a float64 dtype
when used on a floating point input. This prevents accumulator overflow on
smaller floating point dtypes.

Parameters
----------
op : function
    A numpy accumulator function such as np.mean or np.sum.
x : ndarray
    A numpy array to apply the accumulator function.
*args : positional arguments
    Positional arguments passed to the accumulator function after the
    input x.
**kwargs : keyword arguments
    Keyword arguments passed to the accumulator function.

Returns
-------
result
    The output of the accumulator function passed to this function.
   r   )r   r   r   floatingitemsizefloat64)opr!   argskwargsresults        r"   _safe_accumulator_opr   
  sm    . 
}}QWWbkk**qww/?/?!/CA999bjj9 M A'''Mr$   c           	         X-  n[         R                  " U 5      n[         R                  " U5      (       a  [         R                  nO[         R                  nUbV  [        [         R                  U[         R                  " USU 5      5      n[        [         R                  USS2S4   U) -  SS9n	O1[        XpSS9nU R                  S   n
U
[         R                  " USS9-
  n	X9-   nXX-   U-  nUc  SnOX-  nX-
  nUbh  [        [         R                  U[         R                  " USU5      5      nUS-  n[        [         R                  U[         R                  " USU5      5      nO[        XSS9nUS-  n[        XSS9nUUS-  U	-  -  nX#-  n[         R                  " SSS9   X9-  nUU-   UU-  UU-  U-
  S-  -  -   nSSS5        US:H  nUU   WU'   UU-  nXU4$ ! , (       d  f       N$= f)aF  Calculate mean update and a Youngs and Cramer variance update.

If sample_weight is given, the weighted mean and variance is computed.

Update a given mean and (possibly) variance according to new data given
in X. last_mean is always required to compute the new mean.
If last_variance is None, no variance is computed and None return for
updated_variance.

From the paper "Algorithms for computing the sample variance: analysis and
recommendations", by Chan, Golub, and LeVeque.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Data to use for variance update.

last_mean : array-like of shape (n_features,)

last_variance : array-like of shape (n_features,)

last_sample_count : array-like of shape (n_features,)
    The number of samples encountered until now if sample_weight is None.
    If sample_weight is not None, this is the sum of sample_weight
    encountered.

sample_weight : array-like of shape (n_samples,) or None
    Sample weights. If None, compute the unweighted mean/variance.

Returns
-------
updated_mean : ndarray of shape (n_features,)

updated_variance : ndarray of shape (n_features,)
    None if last_variance was None.

updated_sample_count : ndarray of shape (n_features,)

Notes
-----
NaNs are ignored during the algorithm.

References
----------
T. Chan, G. Golub, R. LeVeque. Algorithms for computing the sample
    variance: recommendations, The American Statistician, Vol. 37, No. 3,
    pp. 242-247

Also, see the sparse implementation of this in
`utils.sparsefuncs.incr_mean_variance_axis` and
`utils.sparsefuncs_fast.incr_mean_variance_axis0`
Nr   r&   r   ignore)divideinvalid)
r   isnananynansumr-   r   matmulr   rA   errstate)r/   	last_meanlast_variancelast_sample_countsample_weightlast_sum
X_nan_masksum_opnew_sumnew_sample_countr   updated_sample_countupdated_meanupdated_variancerz   temp
correctionnew_unnormalized_variancelast_unnormalized_variancelast_over_new_countupdated_unnormalized_variancer   s                         r"   _incremental_mean_and_varr  (  s    t ,H!J	vvj  'II}bhhz1a&@
 0FFM!T'*zk:
 'vq9GGAJ	$rvvjq'AA,?&*>>L&u$ .		="((:q$*GJ QJD(<		="((:q$*G)% .fCJQJD(<VPQ(R%
 	"Z]5E%EE!%2%F"[[(;"3"F*+,%&'11G;ABB * < "Q&/H/O%e,8;OO+??? <;s   "G
G*c                     [         R                  " [         R                  " U 5      SS9n[         R                  " U [	        U R
                  S   5      U4   5      nXSS2[         R                  4   -  n U $ )ad  Modify the sign of vectors for reproducibility.

Flips the sign of elements of all the vectors (rows of u) such that
the absolute maximum element of each vector is positive.

Parameters
----------
u : ndarray
    Array with vectors as its rows.

Returns
-------
u_flipped : ndarray with same shape as u
    Array with the sign flipped vectors as its rows.
r   r&   r   N)r   r   r   r9   ry   rA   r   )r   max_abs_rowsr   s      r"   _deterministic_vector_sign_flipr    s[      99RVVAYQ/LGGAeAGGAJ'567Eq"**}	AHr$   c                    [         R                  " X[         R                  S9n[         R                  " X[         R                  S9n[         R                  " UR                  SUS9XRUSS9(       d  [        R                  " S[        5        U$ )ap  Use high precision for cumsum and check that final value matches sum.

Warns if the final cumulative sum does not match the sum (up to the chosen
tolerance).

Parameters
----------
arr : array-like
    To be cumulatively summed as flat.
axis : int, default=None
    Axis along which the cumulative sum is computed.
    The default (None) is to compute the cumsum over the flattened array.
rtol : float, default=1e-05
    Relative tolerance, see ``np.allclose``.
atol : float, default=1e-08
    Absolute tolerance, see ``np.allclose``.

Returns
-------
out : ndarray
    Array with the cumulative sums along the chosen axis.
)r'   r   rI   r&   T)rtolatol	equal_nanzLcumsum was found to be unstable: its last element does not correspond to sum)	r   cumsumr   r-   allcloser   r   r   RuntimeWarning)r   r'   r  r  r   expecteds         r"   stable_cumsumr    sm    . ))C"**
5CvvcBJJ7H;;$44 	> 	
 Jr$   c                 V   [        U 5      u  p#U R                  S   S:X  a  UR                  $ UR                  U 5      nUR	                  U5      (       a  UR                  $ Uc	  [        XS9$ UR                  U5      nX)    X)    p [        XS9$ ! [         a    [        U 5      s $ f = f)a  Compute the weighted average, ignoring NaNs.

Parameters
----------
a : ndarray
    Array containing data to be averaged.
weights : array-like, default=None
    An array of weights associated with the values in a. Each value in a
    contributes to the average according to its associated weight. The
    weights array can either be 1-D of the same shape as a. If `weights=None`,
    then all data in a are assumed to have a weight equal to one.

Returns
-------
weighted_average : float
    The weighted average.

Notes
-----
This wrapper to combine :func:`numpy.average` and :func:`numpy.nanmean`, so
that :func:`np.nan` values are ignored from the average and weights can
be passed. Note that when possible, we delegate to the prime methods.
r   )r2   )weights)	r   rA   nanr   allr   r+   r   ZeroDivisionError)rO   r  r2   r3   masks        r"   _nanaverager"    s    0 !EBwwqzQvv88A;D	vvd||vv!!jj!G575>w++ {s   B B('B(rc   c                    [        U / SQSS9n [        R                  " U 5      (       a.  U(       a  U R                  5       n U =R                  S-  sl        U $ U(       a  U S-  n U $ U S-  n U $ )a  Element wise squaring of array-likes and sparse matrices.

Parameters
----------
X : {array-like, ndarray, sparse matrix}

copy : bool, default=True
    Whether to create a copy of X and operate on it or to perform
    inplace computation (default behaviour).

Returns
-------
X ** 2 : element wise square
     Return the element-wise square of the input.

Examples
--------
>>> from sklearn.utils import safe_sqr
>>> safe_sqr([1, 2, 3])
array([1, 4, 9])
)csrcsccooF)r\   	ensure_2dr   )r   r   r(   rd   data)r/   rd   s     r"   safe_sqrr)    si    , 	A%:eLAqA	1 H	 1A H !GAHr$   c                    [        U5      nX R                  5       -  U-  n[        R                  " U5      n[	        XR                  5       -
  5      nUS:  a  X4-
  n[        R
                  " [        R                  " U5      5      SSS2   nU HZ  n[        R                  " Xh:H  5      u  n	[        [        U	5      U5      n
UR                  XSS9n	XI==   S-  ss'   XZ-  nUS:X  d  MZ    O   UR                  [        5      $ )a  Computes approximate mode of multivariate hypergeometric.

This is an approximation to the mode of the multivariate
hypergeometric given by class_counts and n_draws.
It shouldn't be off by more than one.

It is the mostly likely outcome of drawing n_draws many
samples from the population given by class_counts.

Parameters
----------
class_counts : ndarray of int
    Population per class.
n_draws : int
    Number of draws (samples to draw) from the overall population.
rng : random state
    Used to break ties.

Returns
-------
sampled_classes : ndarray of int
    Number of samples drawn from each class.
    np.sum(sampled_classes) == n_draws

Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import _approximate_mode
>>> _approximate_mode(class_counts=np.array([4, 2]), n_draws=3, rng=0)
array([2, 1])
>>> _approximate_mode(class_counts=np.array([5, 2]), n_draws=4, rng=0)
array([3, 1])
>>> _approximate_mode(class_counts=np.array([2, 2, 2, 1]),
...                   n_draws=2, rng=0)
array([0, 1, 1, 0])
>>> _approximate_mode(class_counts=np.array([2, 2, 2, 1]),
...                   n_draws=2, rng=42)
array([1, 1, 0, 0])
r   NrI   F)rB   replacer   )r   r-   r   floorintsortr   r   r   r   choiceru   )class_countsn_drawsrng
continuousflooredneed_to_add	remaindervaluesr   indsadd_nows              r"   _approximate_moder:  1  s    P S
!C  0 0 22W<Jhhz"G g-.KQ(	9-.tt4 Ehhy12GT
 #d)[1G::d%:@DMQM"Ka  >>#r$   )Fro   )T)r   )Ngh㈵>g:0yE>)0__doc__r   	functoolsr   numbersr   numpyr   scipyr   r   utils._param_validationr   r	   r
   
_array_apir   r   r   r   r   sparsefuncs_fastr   
validationr   r   r#   r4   r;   rE   rV   r`   r_   r   r   r   r   r   r   r   r   r   r  r  r  r"  r)  r:  rp   r$   r"   <module>rD     s   K
       K K V V + 78#L%P8 +0 ;~ 4:ER 4:FR O,!(AtFCD"8QVDEHaf=z6(?ST'12N'O&PVH!56['(('7);<=
 #'$ %ZZB %IK` %Xv !" G#T8v:z'TH> CG{@|,#L)X   FBr$   