
    -iU                         S r SSKJrJr  SSKJr  SSKrSSKJ	r	  SSK
JrJr  SSKJrJr  SS	KJrJrJr  SS
KJrJr  SSKJrJr  SSKJrJrJr  SSKJrJ r   SSK!J"r"J#r#  SS/r$S r%SS jr&S r' " S S\\\S9r( " S S\(5      r) " S S\(5      r*g)z!Spectral biclustering algorithms.    )ABCMetaabstractmethod)IntegralN)norm)
dia_matrixissparse)eigshsvds   )BaseEstimatorBiclusterMixin_fit_context)check_random_statecheck_scalar)Interval
StrOptions)_randomized_svdmake_nonnegativesafe_sparse_dot)assert_all_finitevalidate_data   )KMeansMiniBatchKMeansSpectralBiclusteringSpectralCoclusteringc           	         [        U 5      n [        R                  " S[        R                  " U R	                  SS95      -  5      R                  5       n[        R                  " S[        R                  " U R	                  SS95      -  5      R                  5       n[        R                  " [        R                  " U5      SU5      n[        R                  " [        R                  " U5      SU5      n[        U 5      (       a2  U R                  u  p4[        US/4X34S9n[        US/4XD4S9nXP-  U-  nOUSS2[        R                  4   U -  U-  nXqU4$ )zNormalize ``X`` by scaling rows and columns independently.

Returns the normalized matrix and the row and column scaling
factors.
g      ?r   axisr   )shapeN)r   npasarraysqrtsumsqueezewhereisnanr   r    r   newaxis)Xrow_diagcol_diagn_rowsn_colsrcans           M/var/www/html/venv/lib/python3.13/site-packages/sklearn/cluster/_bicluster.py_scale_normalizer2      s    	Azz#1 667??AHzz#1 667??AHxx*Ax8Hxx*Ax8H{{1#v.>?1#v.>?UQYam$q(83!!    c                     [        U 5      n U n[        U5       Ha  n[        U5      u  n  n[        U 5      (       a#  [	        UR
                  U R
                  -
  5      nO[	        X5-
  5      nUnUc  MY  Xb:  d  M`    U$    U$ )zNormalize rows and columns of ``X`` simultaneously so that all
rows sum to one constant and all columns sum to a different
constant.
)r   ranger2   r   r   data)r)   max_itertolX_scaled_X_newdists          r1   _bistochastic_normalizer=   -   s|     	AH8_&x0q!A;;./D()D
O  Or3   c                    [        U SS9n [        U 5      (       a  [        S5      e[        R                  " U 5      nUR                  SS9SS2[        R                  4   nUR                  SS9nUR                  5       nX-
  U-
  U-   $ )z>Normalize ``X`` according to Kluger's log-interactions scheme.r   )	min_valuez[Cannot compute log of a sparse matrix, because log(x) diverges to -infinity as x goes to 0.r   Nr   )r   r   
ValueErrorr!   logmeanr(   )r)   Lrow_avgcol_avgavgs        r1   _log_normalizerG   B   s    a(A{{
 	

 	q	Aff!fnQ

]+Gff!fnG
&&(C; 3&&r3   c                     ^  \ rS rSr% Sr\" SS15      /\" \SSSS9S/S	/\" S
S15      \R                  /\" \SSSS9/S/S.r
\\S'   \       SS j5       r\S 5       r\" SS9SS j5       rS rS rU 4S jrSrU =r$ )BaseSpectralR   z%Base class for spectral biclustering.
randomizedarpackr   Nleftclosedboolean	k-means++randomr   random_state
svd_method
n_svd_vecs
mini_batchinitn_initrS   _parameter_constraintsc                 X    Xl         X l        X0l        X@l        XPl        X`l        Xpl        g N)
n_clustersrU   rV   rW   rX   rY   rS   )selfr]   rU   rV   rW   rX   rY   rS   s           r1   __init__BaseSpectral.__init__^   s(     %$$$	(r3   c                     g)z0Validate parameters depending on the input data.N r^   	n_sampless     r1   _check_parametersBaseSpectral._check_parametersq   s    r3   T)prefer_skip_nested_validationc                     [        XS[        R                  S9nU R                  UR                  S   5        U R                  U5        U $ )zCreate a biclustering for X.

Parameters
----------
X : array-like of shape (n_samples, n_features)
    Training data.

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

Returns
-------
self : object
    SpectralBiclustering instance.
csr)accept_sparsedtyper   )r   r!   float64re   r    _fit)r^   r)   ys      r1   fitBaseSpectral.fitu   s<    " $bjjIqwwqz*		!r3   c                    U R                   S:X  a;  0 nU R                  b  U R                  US'   [        X4SU R                  0UD6u  pVnGOSU R                   S:X  GaB  [	        XU R                  S9u  pVn[
        R                  " [
        R                  " U5      5      (       am  [        UR                  U5      n[        U R                  5      n	U	R                  SSUR                  S	   5      n
[        XR                  U
S
9u  pkUR                  n[
        R                  " [
        R                  " U5      5      (       a`  [        XR                  5      n[        U R                  5      n	U	R                  SSUR                  S	   5      n
[        XR                  U
S
9u  pe[        W5        [        W5        USS2US24   nXsS nXWR                  4$ )zhReturns first `n_components` left and right singular
vectors u and v, discarding the first `n_discard`.
rK   Nn_oversamplesrS   rL   )kncvr   r   )rt   v0)rU   rV   r   rS   r
   r!   anyr'   r   Tr   uniformr    r	   r   )r^   arrayn_components	n_discardkwargsur:   vtArS   rv   vs               r1   _svdBaseSpectral._svd   s}    ??l*F**.//'&262C2CGMHA" __(EtGHA"vvbhhrl## $EGGU31$2C2CD!))"a<QOO;SSvvbhhqk""#E7731$2C2CD!))"a<QOO;!"am
^$$wr3   c                 &   U R                   (       a+  [        UU R                  U R                  U R                  S9nO*[        UU R                  U R                  U R                  S9nUR                  U5        UR                  nUR                  nXE4$ )N)rX   rY   rS   )	rW   r   rX   rY   rS   r   ro   cluster_centers_labels_)r^   r6   r]   modelcentroidlabelss         r1   _k_meansBaseSpectral._k_means   s}    ??#YY{{!..	E YY{{!..	E 			$))r3   c                 F   > [         TU ]  5       nSUR                  l        U$ )NT)super__sklearn_tags__
input_tagssparse)r^   tags	__class__s     r1   r   BaseSpectral.__sklearn_tags__   s!    w')!%r3   )rX   rW   r]   rY   rV   rS   rU   )   rK   NFrQ   
   Nr\   )__name__
__module____qualname____firstlineno____doc__r   r   r   r!   ndarrayrZ   dict__annotations__r   r_   re   r   ro   r   r   r   __static_attributes____classcell__r   s   @r1   rI   rI   R   s    / "<":;<!T&A4H k[(34bjjAHaf=>'($D   ) )$ ? ? 5 6*#J ( r3   rI   )	metaclassc            	          ^  \ rS rSr% Sr0 \R                  ES\" \SSSS9/0Er\	\
S'    SS	SS
SSSS.U 4S jjjrS rS rSrU =r$ )r      a  Spectral Co-Clustering algorithm (Dhillon, 2001).

Clusters rows and columns of an array `X` to solve the relaxed
normalized cut of the bipartite graph created from `X` as follows:
the edge between row vertex `i` and column vertex `j` has weight
`X[i, j]`.

The resulting bicluster structure is block-diagonal, since each
row and each column belongs to exactly one bicluster.

Supports sparse matrices, as long as they are nonnegative.

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

Parameters
----------
n_clusters : int, default=3
    The number of biclusters to find.

svd_method : {'randomized', 'arpack'}, default='randomized'
    Selects the algorithm for finding singular vectors. May be
    'randomized' or 'arpack'. If 'randomized', use
    :func:`sklearn.utils.extmath.randomized_svd`, which may be faster
    for large matrices. If 'arpack', use
    :func:`scipy.sparse.linalg.svds`, which is more accurate, but
    possibly slower in some cases.

n_svd_vecs : int, default=None
    Number of vectors to use in calculating the SVD. Corresponds
    to `ncv` when `svd_method=arpack` and `n_oversamples` when
    `svd_method` is 'randomized`.

mini_batch : bool, default=False
    Whether to use mini-batch k-means, which is faster but may get
    different results.

init : {'k-means++', 'random'}, or ndarray of shape             (n_clusters, n_features), default='k-means++'
    Method for initialization of k-means algorithm; defaults to
    'k-means++'.

n_init : int, default=10
    Number of random initializations that are tried with the
    k-means algorithm.

    If mini-batch k-means is used, the best initialization is
    chosen and the algorithm runs once. Otherwise, the algorithm
    is run for each initialization and the best solution chosen.

random_state : int, RandomState instance, default=None
    Used for randomizing the singular value decomposition and the k-means
    initialization. Use an int to make the randomness deterministic.
    See :term:`Glossary <random_state>`.

Attributes
----------
rows_ : array-like of shape (n_row_clusters, n_rows)
    Results of the clustering. `rows[i, r]` is True if
    cluster `i` contains row `r`. Available only after calling ``fit``.

columns_ : array-like of shape (n_column_clusters, n_columns)
    Results of the clustering, like `rows`.

row_labels_ : array-like of shape (n_rows,)
    The bicluster label of each row.

column_labels_ : array-like of shape (n_cols,)
    The bicluster label of each column.

biclusters_ : tuple of two ndarrays
    The tuple contains the `rows_` and `columns_` arrays.

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
--------
SpectralBiclustering : Partitions rows and columns under the assumption
    that the data has an underlying checkerboard structure.

References
----------
* :doi:`Dhillon, Inderjit S, 2001. Co-clustering documents and words using
  bipartite spectral graph partitioning.
  <10.1145/502512.502550>`

Examples
--------
>>> from sklearn.cluster import SpectralCoclustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
...               [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralCoclustering(n_clusters=2, random_state=0).fit(X)
>>> clustering.row_labels_ #doctest: +SKIP
array([0, 1, 1, 0, 0, 0], dtype=int32)
>>> clustering.column_labels_ #doctest: +SKIP
array([0, 0], dtype=int32)
>>> clustering
SpectralCoclustering(n_clusters=2, random_state=0)

For a more detailed example, see the following:
:ref:`sphx_glr_auto_examples_bicluster_plot_spectral_coclustering.py`.
r]   r   NrM   rN   rZ   rK   FrQ   r   rT   c          	      *   > [         TU ]  XX4XVU5        g r\   )r   r_   )	r^   r]   rU   rV   rW   rX   rY   rS   r   s	           r1   r_   SpectralCoclustering.__init__@  s     	JD,	
r3   c                 \    U R                   U:  a  [        SU SU R                    S35      eg )N"n_clusters should be <= n_samples=. Got 	 instead.)r]   r@   rc   s     r1   re   &SpectralCoclustering._check_parametersO  s>    ??Y&4YK @OO$I/  'r3   c                    [        U5      u  p#nS[        [        R                  " [        R                  " U R
                  5      5      5      -   nU R                  X%SS9u  pg[        R                  " US S 2[        R                  4   U-  US S 2[        R                  4   U-  45      nU R                  XR
                  5      u  pUR                  S   nU
S U U l        XS  U l        [        R                  " [        U R
                  5       Vs/ s H  oR                  U:H  PM     sn5      U l        [        R                  " [        U R
                  5       Vs/ s H  oR                  U:H  PM     sn5      U l        g s  snf s  snf )Nr   )r|   r   )r2   intr!   ceillog2r]   r   vstackr(   r   r    row_labels_column_labels_r5   rows_columns_)r^   r)   normalized_datar*   r+   n_svr~   r   zr:   r   r,   r/   s                r1   rm   SpectralCoclustering._fitV  s.   .>q.A+83rwwrwwt7899yy!y<IIx2::.2HQ

]4Ka4OPQMM!__5	!'6?$WoYYuT__?UV?U! 0 0A 5?UVW
		/4T__/EF/E!  A%/EF
  WFs   E?F)r   r   r   r   r   )r   r   r   r   r   rI   rZ   r   r   r   r   r_   re   rm   r   r   r   s   @r1   r   r      sv    n`$

-
-$x!T&AB$D  
  
 

 
r3   c                      ^  \ rS rSr% Sr0 \R                  E\" \SSSS9\	/\
" 1 Sk5      /\" \SSSS9/\" \SSSS9/S.Er\\S	'    SSSS
SSSSSSS.	U 4S jjjrS rS rS rS rSrU =r$ )r   ih  a  Spectral biclustering (Kluger, 2003).

Partitions rows and columns under the assumption that the data has
an underlying checkerboard structure. For instance, if there are
two row partitions and three column partitions, each row will
belong to three biclusters, and each column will belong to two
biclusters. The outer product of the corresponding row and column
label vectors gives this checkerboard structure.

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

Parameters
----------
n_clusters : int or tuple (n_row_clusters, n_column_clusters), default=3
    The number of row and column clusters in the checkerboard
    structure.

method : {'bistochastic', 'scale', 'log'}, default='bistochastic'
    Method of normalizing and converting singular vectors into
    biclusters. May be one of 'scale', 'bistochastic', or 'log'.
    The authors recommend using 'log'. If the data is sparse,
    however, log normalization will not work, which is why the
    default is 'bistochastic'.

    .. warning::
       if `method='log'`, the data must not be sparse.

n_components : int, default=6
    Number of singular vectors to check.

n_best : int, default=3
    Number of best singular vectors to which to project the data
    for clustering.

svd_method : {'randomized', 'arpack'}, default='randomized'
    Selects the algorithm for finding singular vectors. May be
    'randomized' or 'arpack'. If 'randomized', uses
    :func:`~sklearn.utils.extmath.randomized_svd`, which may be faster
    for large matrices. If 'arpack', uses
    `scipy.sparse.linalg.svds`, which is more accurate, but
    possibly slower in some cases.

n_svd_vecs : int, default=None
    Number of vectors to use in calculating the SVD. Corresponds
    to `ncv` when `svd_method=arpack` and `n_oversamples` when
    `svd_method` is 'randomized`.

mini_batch : bool, default=False
    Whether to use mini-batch k-means, which is faster but may get
    different results.

init : {'k-means++', 'random'} or ndarray of shape (n_clusters, n_features),             default='k-means++'
    Method for initialization of k-means algorithm; defaults to
    'k-means++'.

n_init : int, default=10
    Number of random initializations that are tried with the
    k-means algorithm.

    If mini-batch k-means is used, the best initialization is
    chosen and the algorithm runs once. Otherwise, the algorithm
    is run for each initialization and the best solution chosen.

random_state : int, RandomState instance, default=None
    Used for randomizing the singular value decomposition and the k-means
    initialization. Use an int to make the randomness deterministic.
    See :term:`Glossary <random_state>`.

Attributes
----------
rows_ : array-like of shape (n_row_clusters, n_rows)
    Results of the clustering. `rows[i, r]` is True if
    cluster `i` contains row `r`. Available only after calling ``fit``.

columns_ : array-like of shape (n_column_clusters, n_columns)
    Results of the clustering, like `rows`.

row_labels_ : array-like of shape (n_rows,)
    Row partition labels.

column_labels_ : array-like of shape (n_cols,)
    Column partition labels.

biclusters_ : tuple of two ndarrays
    The tuple contains the `rows_` and `columns_` arrays.

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
--------
SpectralCoclustering : Spectral Co-Clustering algorithm (Dhillon, 2001).

References
----------

* :doi:`Kluger, Yuval, et. al., 2003. Spectral biclustering of microarray
  data: coclustering genes and conditions.
  <10.1101/gr.648603>`

Examples
--------
>>> from sklearn.cluster import SpectralBiclustering
>>> import numpy as np
>>> X = np.array([[1, 1], [2, 1], [1, 0],
...               [4, 7], [3, 5], [3, 6]])
>>> clustering = SpectralBiclustering(n_clusters=2, random_state=0).fit(X)
>>> clustering.row_labels_
array([1, 1, 1, 0, 0, 0], dtype=int32)
>>> clustering.column_labels_
array([1, 0], dtype=int32)
>>> clustering
SpectralBiclustering(n_clusters=2, random_state=0)

For a more detailed example, see
:ref:`sphx_glr_auto_examples_bicluster_plot_spectral_biclustering.py`
r   NrM   rN   >   rA   scalebistochastic)r]   methodr{   n_bestrZ   r   r      rK   FrQ   r   )	r   r{   r   rU   rV   rW   rX   rY   rS   c       	   	      N   > [         TU ]  XXgXU
5        X l        X0l        X@l        g r\   )r   r_   r   r{   r   )r^   r]   r   r{   r   rU   rV   rW   rX   rY   rS   r   s              r1   r_   SpectralBiclustering.__init__  s-     	JD,	
 (r3   c                    [        U R                  [        5      (       a-  U R                  U:  a  [        SU SU R                   S35      eO1 U R                  u  p#[	        US[        SUS9  [	        US[        SUS9  U R                  U R                  :  a&  [        S
U R                   SU R                   S35      eg ! [        [
        4 a  n[        SU R                   S	35      UeS nAff = f)Nr   r   r   n_row_clustersr   )target_typemin_valmax_valn_column_clustersz*Incorrect parameter n_clusters has value: z. It should either be a single integer or an iterable with two integers: (n_row_clusters, n_column_clusters) And the values are should be in the range: (1, n_samples)zn_best=z must be <= n_components=.)
isinstancer]   r   r@   r   	TypeErrorr   r{   )r^   rd   r   r   es        r1   re   &SpectralBiclustering._check_parameters  s   doox00* 8 D(	3  +48OO1"$ (% %' (%" ;;***$++&?@Q@Q?RRST  + 	*  ( )-- s   0B? ?C.C))C.c           	      6   U R                   nU R                  S:X  a  [        U5      nUS-  nO@U R                  S:X  a  [        U5      u  n  nUS-  nOU R                  S:X  a  [	        U5      nU R                  S:X  a  SOSnU R                  WX%5      u  pgUR                  nUR                  n	 U R                  u  pU R                  XR                  U
5      nU R                  XR                  U5      nU R                  XR                  U
5      U l        U R                  UR                  UR                  U5      U l        [        R                  " [!        U
5       VVs/ s H%  n[!        U5        H  nU R                  U:H  PM     M'     snn5      U l        [        R                  " [!        U
5       VVs/ s H%  n[!        U5        H  nU R                  U:H  PM     M'     snn5      U l        g ! [         a    U R                  =p GNNf = fs  snnf s  snnf )Nr   r   r   rA   r   )r{   r   r=   r2   rG   r   rx   r]   r   _fit_best_piecewiser   _project_and_clusterr   r   r!   r   r5   r   r   )r^   r)   r   r   r:   r|   r~   r   utr   r   n_col_clustersbest_utbest_vtlabels                  r1   rm   SpectralBiclustering._fit,  s     ;;.(5a8OAID[[G#$4Q$7!OQAID[[E!,Q/O-A1	yy$:SSSS	>-1__*N **2{{NK**2{{NK44Q		>R"77WYYWYY #>22E~.A   E). *2

 		 ~..A">2E ##u,2 -.
%  	>.2oo=N^	>s   /G1  ,H
7,H
1HHc                    ^ ^ UU 4S jn[         R                  " USUS9n[         R                  " [        SX-
  S9nU[         R                  " U5      SU    nU$ )zFind the ``n_best`` vectors that are best approximated by piecewise
constant vectors.

The piecewise vectors are found by k-means; the best is chosen
according to Euclidean distance.

c                 p   > TR                  U R                  SS5      T5      u  pX   R                  5       $ )Nru   r   )r   reshaperavel)r   r   r   r]   r^   s      r1   make_piecewise@SpectralBiclustering._fit_best_piecewise.<locals>.make_piecewise`  s3    #}}QYYr1-=zJH#))++r3   r   )r   arrN)r!   apply_along_axisr   argsort)r^   vectorsr   r]   r   piecewise_vectorsdistsresults   `  `    r1   r   (SpectralBiclustering._fit_best_piecewiseW  sU    	, //QGT##Dqw7RTE*7F34r3   c                 B    [        X5      nU R                  XC5      u  pVU$ )z7Project ``data`` to ``vectors`` and cluster the result.)r   r   )r^   r6   r   r]   	projectedr:   r   s          r1   r   )SpectralBiclustering._project_and_clusteri  s!    #D2	MM)8	r3   )r   r   r   r   r{   r   r   r   )r   r   r   r   r   rI   rZ   r   r   tupler   r   r   r_   re   rm   r   r   r   r   r   s   @r1   r   r   h  s    }~$

-
-$!T&A5I>?@!(AtFCDHaf=>$D    *%N)
V$ r3   )i  gh㈵>)+r   abcr   r   numbersr   numpyr!   scipy.linalgr   scipy.sparser   r   scipy.sparse.linalgr	   r
   baser   r   r   utilsr   r   utils._param_validationr   r   utils.extmathr   r   r   utils.validationr   r   _kmeansr   r   __all__r2   r=   rG   rI   r   r   rb   r3   r1   <module>r      s~    '
 (    - + > > 4 : N N ? ,!#9
:"**' u>=G up[
< [
|E< Er3   