
    0PhUU                     8   d Z ddlmZmZ ddlmZ ddlZddlm	Z	 ddl
mZmZ ddl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dlmZmZmZ ddlmZm Z  ddl!m"Z"m#Z# ddgZ$d Z%ddZ&d Z' G d deee          Z( G d de(          Z) G d de(          Z*dS )z!Spectral biclustering algorithms.    )ABCMetaabstractmethod)IntegralN)norm)
dia_matrixissparse)eigshsvds   )BaseEstimatorBiclusterMixin_fit_context)check_random_statecheck_scalar)Interval
StrOptions)make_nonnegativerandomized_svdsafe_sparse_dot)assert_all_finitevalidate_data   )KMeansMiniBatchKMeansSpectralCoclusteringSpectralBiclusteringc                    t          |           } t          j        dt          j        |                     d                    z                                            }t          j        dt          j        |                     d                    z                                            }t          j        t          j        |          d|          }t          j        t          j        |          d|          }t          |           r?| j	        \  }}t          |dgf||f          }t          |dgf||f          }|| z  |z  }n|ddt          j        f         | z  |z  }|||fS )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           Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_bicluster.py_scale_normalizer2      sD    	Az#1 6 6677??AAHz#1 6 6677??AAHx**Ax88Hx**Ax88H{{ 41#vv.>???1#vv.>???UQYaaam$q(83x!!      h㈵>c                    t          |           } | }t          |          D ]_}t          |          \  }}}t          |           rt	          |j        | j        z
            }nt	          ||z
            }|}|||k     r n`|S )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0q!A;; 	*.//DD5())Ds

EOr3   c                 F   t          | d          } t          |           rt          d          t          j        |           }|                    d          ddt          j        f         }|                    d          }|                                }||z
  |z
  |z   S )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_normalizerI   B   s    a(((A{{ 

 
 	

 	q		Aff!fnnQQQ
]+Gff!fnnG
&&((Cw; 3&&r3   c            
       .    e Zd ZU dZ eddh          g eeddd          dgdg ed	d
h          ej        g eeddd          gdgdZ	e
ed<   e	 	 	 	 	 	 	 dd            Zed             Z ed          dd            Zd Zd Z fdZ xZS )BaseSpectralz%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_initrT   _parameter_constraints   F
   c                 h    || _         || _        || _        || _        || _        || _        || _        d S N)
n_clustersrV   rW   rX   rY   rZ   rT   )selfr`   rV   rW   rX   rY   rZ   rT   s           r1   __init__zBaseSpectral.__init__^   s<     %$$$	(r3   c                     dS )z0Validate parameters depending on the input data.N ra   	n_sampless     r1   _check_parameterszBaseSpectral._check_parametersq   s      r3   T)prefer_skip_nested_validationc                     t          | |dt          j                  }|                     |j        d                    |                     |           | S )aW  Create 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!   float64rg   r    _fit)ra   r)   ys      r1   fitzBaseSpectral.fitu   sJ    " $bjIIIqwqz***		!r3   c                 z   | j         dk    r.i }| j        
| j        |d<   t          ||fd| j        i|\  }}}nD| j         dk    r8t	          ||| j                  \  }}}t          j        t          j        |                    rlt          |j	        |          }t          | j                  }	|	                    dd|j        d	                   }
t          || j        |

          \  }}|j	        }t          j        t          j        |                    ret          ||j	                  }t          | j                  }	|	                    dd|j        d	                   }
t          || j        |

          \  }}t          |           t          |           |dd|df         }||d         }||j	        fS )zxReturns first `n_components` left and right singular
        vectors u and v, discarding the first `n_discard`.
        rL   Nn_oversamplesrT   rM   )kncvr   r   )rt   v0)rV   rW   r   rT   r
   r!   anyr'   r   Tr   uniformr    r	   r   )ra   arrayn_components	n_discardkwargsur<   vtArT   rv   vs               r1   _svdzBaseSpectral._svd   s    ?l**F**./'%| 262CGM HAq"" _((E\tGGGHAq"vbhrll## 	 $EGU331$2CDD!))"a<<QDO;;;1Svbhqkk"" <#E57331$2CDD!))"a<<QDO;;;1!"aaam	

^"$wr3   c                     | j         r#t          || j        | j        | j                  }n"t          || j        | j        | j                  }|                    |           |j        }|j        }||fS )N)rY   rZ   rT   )	rX   r   rY   rZ   rT   r   rp   cluster_centers_labels_)ra   r8   r`   modelcentroidlabelss         r1   _k_meanszBaseSpectral._k_means   s    ? 	#Y{!.	  EE Y{!.	  E 			$)r3   c                 `    t                                                      }d|j        _        |S )NT)super__sklearn_tags__
input_tagssparse)ra   tags	__class__s     r1   r   zBaseSpectral.__sklearn_tags__   s'    ww''))!%r3   )r\   rL   NFrR   r]   Nr_   )__name__
__module____qualname____doc__r   r   r   r!   ndarrayr[   dict__annotations__r   rb   rg   r   rp   r   r   r   __classcell__r   s   @r1   rK   rK   R   sl        // "z<":;;<x!T&AAA4H k[(344bjA8Haf===>'($ $D     ) ) ) ^)$ ? ? ^? \555   65*# # #J     (        r3   rK   )	metaclassc                        e Zd ZU dZi ej        d eeddd          giZee	d<   	 dd	dd
dddd fdZ
d Zd Z xZS )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)
    r`   r   NrN   rO   r[   r\   rL   FrR   r]   rU   c          	      V    t                                          |||||||           d S r_   )r   rb   )	ra   r`   rV   rW   rX   rY   rZ   rT   r   s	           r1   rb   zSpectralCoclustering.__init__=  s:     	
J
D&,	
 	
 	
 	
 	
r3   c                 R    | j         |k    rt          d| d| j          d          d S )N"n_clusters should be <= n_samples=. Got 	 instead.)r`   rB   re   s     r1   rg   z&SpectralCoclustering._check_parametersL  sN    ?Y&&/Y / /O/ / /   '&r3   c                     t          |          \  }}}dt          t          j        t          j         j                                      z   }                     ||d          \  }}t          j        |d d t          j        f         |z  |d d t          j        f         |z  f          } 	                    | j                  \  }	}
|j
        d         }|
d |          _        |
|d           _        t          j         fdt           j                  D                        _        t          j         fdt           j                  D                        _        d S )Nr   )r|   r   c                 &    g | ]}j         |k    S rd   )row_labels_.0r/   ra   s     r1   
<listcomp>z-SpectralCoclustering._fit.<locals>.<listcomp>_  s!    VVV! 0A 5VVVr3   c                 &    g | ]}j         |k    S rd   )column_labels_r   s     r1   r   z-SpectralCoclustering._fit.<locals>.<listcomp>a  s!    FFF!T A%FFFr3   )r2   intr!   ceillog2r`   r   vstackr(   r   r    r   r   r7   rows_columns_)ra   r)   normalized_datar*   r+   n_svr~   r   zr<   r   r,   s   `           r1   rn   zSpectralCoclustering._fitS  sB   .>q.A.A+83rwrwt7788999yy$!y<<1Ix2:.2HQQQ
]4Ka4OPQQMM!T_55	6!'6'?$VWWoYVVVVuT_?U?UVVVWW
	FFFFuT_/E/EFFF
 
r3   r\   )r   r   r   r   rK   r[   r   r   r   r   rb   rg   rn   r   r   s   @r1   r   r      s         k kZ$

-$xx!T&AAAB$ $D    
  
 
 
 
 
 
 
  
 
 
 
 
 
 
r3   c                        e Zd ZU dZi ej         eeddd          eg e	h d          g eeddd          g eeddd          gdZe
ed<   	 dd
dd	ddddddd	 fdZd Zd Zd Zd Z xZS )r   at  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   NrN   rO   >   rC   scalebistochastic)r`   methodr{   n_bestr[   r\   r      rL   FrR   r]   )	r   r{   r   rV   rW   rX   rY   rZ   rT   c       	   	          t                                          ||||||	|
           || _        || _        || _        d S r_   )r   rb   r   r{   r   )ra   r`   r   r{   r   rV   rW   rX   rY   rZ   rT   r   s              r1   rb   zSpectralBiclustering.__init__  sL     	
J
D&,	
 	
 	
 (r3   c                    t          | j        t                    r'| j        |k    rt          d| d| j         d          np	 | j        \  }}t	          |dt          d|           t	          |dt          d|           n2# t          t
          f$ r}t          d| j         d	          |d }~ww xY w| j        | j        k    r t          d
| j         d| j         d          d S )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   rB   r   	TypeErrorr   r{   )ra   rf   r   r   es        r1   rg   z&SpectralBiclustering._check_parameters  sa   dox00 	** 3 3 33 3 3   +48O1 1"$ (%    %' (%     	*    -- - -   ;***T$+TT@QTTT   +*s   <B   B/B**B/c                 V     j         } j        dk    rt          |          }|dz  }n> j        dk    rt          |          \  }}}|dz  }n j        dk    rt	          |          } j        dk    rdnd}                     |||          \  }}|j        }|j        }		  j        \  }
n# t          $ r  j        x}
Y nw xY w 	                    | j
        |
          } 	                    |	 j
                  }                     ||j        |
           _                             |j        |j                   _        t          j         fdt!          |
          D                        _        t          j         fdt!          |
          D                        _        d S )Nr   r   r   rC   r   c                 J    g | ]}t                    D ]}j        |k     S rd   )r7   r   )r   labelr<   n_col_clustersra   s      r1   r   z-SpectralBiclustering._fit.<locals>.<listcomp>F  sP       ~..    E)   r3   c                 J    g | ]}t                    D ]}j        |k     S rd   )r7   r   )r   r<   r   r   ra   s      r1   r   z-SpectralBiclustering._fit.<locals>.<listcomp>M  sP       ">22   #u,   r3   )r{   r   r?   r2   rI   r   rx   r`   r   _fit_best_piecewiser   _project_and_clusterr   r   r!   r   r7   r   r   )ra   r)   r   r   r<   r|   r~   r   utr   r   best_utbest_vtr   s   `            @r1   rn   zSpectralBiclustering._fit)  s    ;.((5a88OAIDD[G##$4Q$7$7!OQAIDD[E!!,Q//O--AA1	yy$	::1SS	>-1_*NNN 	> 	> 	>.2o=N^^^	> **2t{NKK**2t{NKK44Q	>RR"77WYWWY    ">22  
 

 	    ~..  
 
s    
B+ +C Cc                       fd}t          j        |d|          }t          j        t          d||z
            }|t          j        |          d|                  }|S )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                                          |                     dd                    \  }}||                                         S )Nru   r   )r   reshaperavel)r   r   r   r`   ra   s      r1   make_piecewisez@SpectralBiclustering._fit_best_piecewise.<locals>.make_piecewise]  s@    #}}QYYr1-=-=zJJHfF#))+++r3   r   )r   arrN)r!   apply_along_axisr   argsort)ra   vectorsr   r`   r   piecewise_vectorsdistsresults   `  `    r1   r   z(SpectralBiclustering._fit_best_piecewiseT  s{    	, 	, 	, 	, 	, 	, /QGTTT#DqwAR7RTTTE**7F734r3   c                 X    t          ||          }|                     ||          \  }}|S )z7Project ``data`` to ``vectors`` and cluster the result.)r   r   )ra   r8   r   r`   	projectedr<   r   s          r1   r   z)SpectralBiclustering._project_and_clusterf  s-    #D'22	MM)Z88	6r3   r   )r   r   r   r   rK   r[   r   r   tupler   r   r   rb   rg   rn   r   r   r   r   s   @r1   r   r   e  sM        } }~$

-$x!T&AAA5I:>>>??@!(AtFCCCD8Haf===>$ $ $D           *% % %N)
 )
 )
V  $      r3   )r4   r5   )+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?   rI   rK   r   r   rd   r3   r1   <module>r      s   ' '
 ( ' ' ' ' ' ' '                 - - - - - - - - + + + + + + + + > > > > > > > > > > 4 4 4 4 4 4 4 4 : : : : : : : : M M M M M M M M M M ? ? ? ? ? ? ? ? , , , , , , , ,!#9
:" " "*   *' ' ' u u u u u>=G u u u upX
 X
 X
 X
 X
< X
 X
 X
vE E E E E< E E E E Er3   