
    0PhK                         d Z ddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZ ddlmZ ddlmZmZmZmZ d	d
lmZmZ d	dlmZmZmZmZ  G d d          Z G d de          ZdS )zBisecting K-means clustering.    N   )_fit_context)_openmp_effective_n_threads)IntegralInterval
StrOptions)	row_norms)_check_sample_weightcheck_is_fittedcheck_random_statevalidate_data   )_inertia_dense_inertia_sparse)_BaseKMeans_kmeans_single_elkan_kmeans_single_lloyd _labels_inertia_threadpool_limitc                   *    e Zd ZdZd Zd Zd Zd ZdS )_BisectingTreezITree structure representing the hierarchical clusters of BisectingKMeans.c                 L    || _         || _        || _        d| _        d| _        dS )zCreate a new cluster node in the tree.

        The node holds the center of this cluster and the indices of the data points
        that belong to it.
        N)centerindicesscoreleftright)selfr   r   r   s       _/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_bisect_k_means.py__init__z_BisectingTree.__init__!   s+     
	


    c                     t          | j        |dk             |d         |d                   | _        t          | j        |dk             |d         |d                   | _        d| _        dS )z,Split the cluster node into two subclusters.r   r   r   r   r   N)r   r   r   r   )r   labelscentersscoress       r   splitz_BisectingTree.split.   sq    "L1-gajq	
 
 
	 $L1-gajq	
 
 


 r    c                 d    d}|                                  D ]}||j        |k    r	|j        }|}|S )zReturn the cluster node to bisect next.

        It's based on the score of the cluster, which can be either the number of
        data points assigned to that cluster or the inertia of that cluster
        (see `bisecting_strategy` for details).
        N)iter_leavesr   )r   	max_scorecluster_leafbest_cluster_leafs       r   get_cluster_to_bisectz$_BisectingTree.get_cluster_to_bisect:   sL     	 ,,.. 	1 	1L L$6$B$B(.	$0!  r    c              #      K   | j         | V  dS | j                                         E d{V  | j                                        E d{V  dS )z0Iterate over all the cluster leaves in the tree.N)r   r(   r   )r   s    r   r(   z_BisectingTree.iter_leavesJ   sm      9JJJJJy,,.........z--///////////r    N)__name__
__module____qualname____doc__r   r&   r,   r(    r    r   r   r      sV        SS  
 
 
! ! ! 0 0 0 0 0r    r   c                   &    e Zd ZU dZi ej         eddh          eg ee	ddd          gdg ed	d
h          g eddh          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 ed          dd            Zd Zd Z fdZ xZS ) BisectingKMeansa  Bisecting K-Means clustering.

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

    .. versionadded:: 1.1

    Parameters
    ----------
    n_clusters : int, default=8
        The number of clusters to form as well as the number of
        centroids to generate.

    init : {'k-means++', 'random'} or callable, default='random'
        Method for initialization:

        'k-means++' : selects initial cluster centers for k-mean
        clustering in a smart way to speed up convergence. See section
        Notes in k_init for more details.

        'random': choose `n_clusters` observations (rows) at random from data
        for the initial centroids.

        If a callable is passed, it should take arguments X, n_clusters and a
        random state and return an initialization.

    n_init : int, default=1
        Number of time the inner k-means algorithm will be run with different
        centroid seeds in each bisection.
        That will result producing for each bisection best output of n_init
        consecutive runs in terms of inertia.

    random_state : int, RandomState instance or None, default=None
        Determines random number generation for centroid initialization
        in inner K-Means. Use an int to make the randomness deterministic.
        See :term:`Glossary <random_state>`.

    max_iter : int, default=300
        Maximum number of iterations of the inner k-means algorithm at each
        bisection.

    verbose : int, default=0
        Verbosity mode.

    tol : float, default=1e-4
        Relative tolerance with regards to Frobenius norm of the difference
        in the cluster centers of two consecutive iterations  to declare
        convergence. Used in inner k-means algorithm at each bisection to pick
        best possible clusters.

    copy_x : bool, default=True
        When pre-computing distances it is more numerically accurate to center
        the data first. If copy_x is True (default), then the original data is
        not modified. If False, the original data is modified, and put back
        before the function returns, but small numerical differences may be
        introduced by subtracting and then adding the data mean. Note that if
        the original data is not C-contiguous, a copy will be made even if
        copy_x is False. If the original data is sparse, but not in CSR format,
        a copy will be made even if copy_x is False.

    algorithm : {"lloyd", "elkan"}, default="lloyd"
        Inner K-means algorithm used in bisection.
        The classical EM-style algorithm is `"lloyd"`.
        The `"elkan"` variation can be more efficient on some datasets with
        well-defined clusters, by using the triangle inequality. However it's
        more memory intensive due to the allocation of an extra array of shape
        `(n_samples, n_clusters)`.

    bisecting_strategy : {"biggest_inertia", "largest_cluster"},            default="biggest_inertia"
        Defines how bisection should be performed:

        - "biggest_inertia" means that BisectingKMeans will always check
          all calculated cluster for cluster with biggest SSE
          (Sum of squared errors) and bisect it. This approach concentrates on
          precision, but may be costly in terms of execution time (especially for
          larger amount of data points).

        - "largest_cluster" - BisectingKMeans will always split cluster with
          largest amount of points assigned to it from all clusters
          previously calculated. That should work faster than picking by SSE
          ('biggest_inertia') and may produce similar results in most cases.

    Attributes
    ----------
    cluster_centers_ : ndarray of shape (n_clusters, n_features)
        Coordinates of cluster centers. If the algorithm stops before fully
        converging (see ``tol`` and ``max_iter``), these will not be
        consistent with ``labels_``.

    labels_ : ndarray of shape (n_samples,)
        Labels of each point.

    inertia_ : float
        Sum of squared distances of samples to their closest cluster center,
        weighted by the sample weights if provided.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

    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.

    See Also
    --------
    KMeans : Original implementation of K-Means algorithm.

    Notes
    -----
    It might be inefficient when n_cluster is less than 3, due to unnecessary
    calculations for that case.

    Examples
    --------
    >>> from sklearn.cluster import BisectingKMeans
    >>> import numpy as np
    >>> X = np.array([[1, 1], [10, 1], [3, 1],
    ...               [10, 0], [2, 1], [10, 2],
    ...               [10, 8], [10, 9], [10, 10]])
    >>> bisect_means = BisectingKMeans(n_clusters=3, random_state=0).fit(X)
    >>> bisect_means.labels_
    array([0, 2, 0, 2, 0, 2, 1, 1, 1], dtype=int32)
    >>> bisect_means.predict([[0, 0], [12, 3]])
    array([0, 2], dtype=int32)
    >>> bisect_means.cluster_centers_
    array([[ 2., 1.],
           [10., 9.],
           [10., 1.]])

    For a comparison between BisectingKMeans and K-Means refer to example
    :ref:`sphx_glr_auto_examples_cluster_plot_bisect_kmeans.py`.
    z	k-means++randomr   Nr   )closedbooleanlloydelkanbiggest_inertialargest_cluster)initn_initcopy_x	algorithmbisecting_strategy_parameter_constraints   i,  r   g-C6?T)	r<   r=   random_statemax_iterverbosetolr>   r?   r@   c       	   	          t                                          |||||||           || _        |	| _        |
| _        d S )N)
n_clustersr<   rD   rE   rC   rF   r=   )superr   r>   r?   r@   )r   rH   r<   r=   rC   rD   rE   rF   r>   r?   r@   	__class__s              r   r   zBisectingKMeans.__init__   sY     	!% 	 	
 	
 	
 ""4r    c                 6    t          j        d| d           dS )z(Warn when vcomp and mkl are both presentzBisectingKMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can avoid it by setting the environment variable OMP_NUM_THREADS=.N)warningswarn)r   n_active_threadss     r   _warn_mkl_vcompzBisectingKMeans._warn_mkl_vcomp   s9    = *:= = =	
 	
 	
 	
 	
r    c           	          |j         d         }t          j        |          rt          nt          }t          j        |          }t          |          D ]} |||||| j        |          ||<   |S )a  Calculate the sum of squared errors (inertia) per cluster.

        Parameters
        ----------
        X : {ndarray, csr_matrix} of shape (n_samples, n_features)
            The input samples.

        centers : ndarray of shape (n_clusters=2, n_features)
            The cluster centers.

        labels : ndarray of shape (n_samples,)
            Index of the cluster each sample belongs to.

        sample_weight : ndarray of shape (n_samples,)
            The weights for each observation in X.

        Returns
        -------
        inertia_per_cluster : ndarray of shape (n_clusters=2,)
            Sum of squared errors (inertia) for each cluster.
        r   )single_label)	shapespissparser   r   npemptyrange
_n_threads)	r   Xr$   r#   sample_weightrH   _inertiainertia_per_clusterlabels	            r   _inertia_per_clusterz$BisectingKMeans._inertia_per_cluster  s    , ]1%
&(k!nnH??. hz22:&& 	 	E)1='64?QV* * *&& #"r    c           
      0   ||j                  }||j                  }||j                  }d}t          | j                  D ]m}|                     ||| j        | j        d|          }|                     |||| j        | j        | j	        | j
                  \  }}	}
}|	|	|dz  k     r|}|
}|	}n| j        rt          d|            | j        dk    r|                     ||||          }nt          j        |d          }|                    |||           dS )	a  Split a cluster into 2 subsclusters.

        Parameters
        ----------
        X : {ndarray, csr_matrix} of shape (n_samples, n_features)
            Training instances to cluster.

        x_squared_norms : ndarray of shape (n_samples,)
            Squared euclidean norm of each data point.

        sample_weight : ndarray of shape (n_samples,)
            The weights for each observation in X.

        cluster_to_bisect : _BisectingTree node object
            The cluster node to split.
        Nr   )x_squared_normsr<   rC   n_centroidsr[   )rD   rE   rF   	n_threadsg!?zNew centroids from bisection: r:   )	minlength)r   rX   r=   _init_centroidsr<   _random_state_kmeans_singlerD   rE   rF   rY   printr@   r_   rV   bincountr&   )r   rZ   ra   r[   cluster_to_bisectbest_inertia_centers_initr#   inertiar$   best_labelsbest_centersr%   s                 r   _bisectzBisectingKMeans._bisect(  sm   " '()*;*CD%&7&?@ t{## 	' 	'A// /Y!/+ 0  L +/*=*=H/ +> + +'FGWa #w1J'J'J$&&< 	CA<AABBB"&777..<m FF [:::F\6BBBBBr    )prefer_skip_nested_validationc           	         t          | |dt          j        t          j        gd| j        d          }|                     |           t          | j                  | _        t          |||j
                  }t                      | _        | j        dk    s| j        dk    r.t          | _        |                     ||j        d                    nt&          | _        t)          j        |          s%|                    d	          | _        || j        z  }t1          t          j        |j        d                   |                    d	          d
          | _        t7          |d          }t9          | j        dz
            D ]3}| j                                        }|                     ||||           4t          j        |j        d         dt          j                   | _!        t          j"        | j        |j        d         f|j
                  | _#        tI          | j        %                                          D ]1\  }}|| j!        |j&        <   |j'        | j#        |<   ||_(        d|_&        2t)          j        |          s|| j        z  }| xj#        | j        z  c_#        t)          j        |          rtR          ntT          }	 |	||| j#        | j!        | j                  | _+        | j#        j        d         | _,        | S )a+  Compute bisecting k-means clustering.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)

            Training instances to cluster.

            .. note:: The data will be converted to C ordering,
                which will cause a memory copy
                if the given data is not C-contiguous.

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

        sample_weight : array-like of shape (n_samples,), default=None
            The weights for each observation in X. If None, all observations
            are assigned equal weight. `sample_weight` is not used during
            initialization if `init` is a callable.

        Returns
        -------
        self
            Fitted estimator.
        csrCF)accept_sparsedtypeordercopyaccept_large_sparserw   r8   r   r   )axisr"   TsquaredN)-r   rV   float64float32r>   _check_params_vs_inputr   rC   rf   r
   rw   r   rY   r?   rH   r   rg   _check_mkl_vcomprS   r   rT   rU   mean_X_meanr   arange_bisecting_treer	   rX   r,   rq   fullint32labels_rW   cluster_centers_	enumerater(   r   r   r^   r   r   inertia__n_features_out)
r   rZ   yr[   ra   rl   rj   icluster_noder\   s
             r   fitzBisectingKMeans.fitj  s   6 :rz* %
 
 
 	##A&&&/0ABB,]AQWMMM577>W$$1(<(<"6D!!!QWQZ0000"6D {1~~ 	66q6>>DLA  .Iagaj))66q6>> 
  
  
 $At444t*++ 	O 	OA $ 4 J J L L LLO]<MNNNN wqwqz2RX>>> "$/171:)Fag V V V()=)I)I)K)KLL 	( 	(OA|12DL-.'3':D!!$!"L#'L   {1~~ 	2A!!T\1!!&(k!nnH??. }d3T\4?
 
  $4:1=r    c                     t          |            |                     |          }t          |d          }t          j        |          }|                     ||| j                  }|S )a  Predict which cluster each sample in X belongs to.

        Prediction is made by going down the hierarchical tree
        in searching of closest leaf cluster.

        In the vector quantization literature, `cluster_centers_` is called
        the code book and each value returned by `predict` is the index of
        the closest code in the code book.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            New data to predict.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Index of the cluster each sample belongs to.
        Tr}   )r   _check_test_datar	   rV   	ones_like_predict_recursiver   )r   rZ   ra   r[   r#   s        r   predictzBisectingKMeans.predict  sg    ( 	!!!$$#At444 _55((M4;OPPr    c                 F   |j         1t          j        |j        d         |j        t          j                  S t          j        |j         j        |j        j        f          }t          | d          r
|| j
        z  }t          |||| j        d          }|dk    }t          j        |j        d         dt          j                  }|                     ||         ||         |j                   ||<   |                     ||          ||          |j                  || <   |S )a  Predict recursively by going down the hierarchical tree.

        Parameters
        ----------
        X : {ndarray, csr_matrix} of shape (n_samples, n_features)
            The data points, currently assigned to `cluster_node`, to predict between
            the subclusters of this node.

        sample_weight : ndarray of shape (n_samples,)
            The weights for each observation in X.

        cluster_node : _BisectingTree node object
            The cluster node of the hierarchical tree.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Index of the cluster each sample belongs to.
        Nr   r{   r   F)return_inertiar   )r   rV   r   rS   r^   r   vstackr   r   hasattrr   r   rY   r   )r   rZ   r[   r   r$   cluster_labelsmaskr#   s           r   r   z"BisectingKMeans._predict_recursive  s'   ( $7171:|'9JJJJ )\.5|7I7PQRR4## 	$t|#G9O 
 
 
 " Rrx888..dG]4(,*;
 
t //teHmTE*L,>
 
u r    c                 |    t                                                      }d|j        _        ddg|j        _        |S )NTr   r   )rI   __sklearn_tags__
input_tagssparsetransformer_tagspreserves_dtype)r   tagsrJ   s     r   r   z BisectingKMeans.__sklearn_tags__  s7    ww''))!%1:I0F-r    )rB   )NN)r.   r/   r0   r1   r   rA   r   callabler   r   dict__annotations__r   rP   r_   rq   r   r   r   r   r   __classcell__)rJ   s   @r   r4   r4   S   s        C CJ$

,$[(344h?8Haf===>+ j'7!3445)z+<>O*PQQR$ $ $D    5 ,5 5 5 5 5 5 58
 
 
# # #B@C @C @CD \555[ [ [ 65[z  @1 1 1f        r    r4   ) r1   rM   numpyrV   scipy.sparser   rT   baser   utils._openmp_helpersr   utils._param_validationr   r   r   utils.extmathr	   utils.validationr
   r   r   r   _k_means_commonr   r   _kmeansr   r   r   r   r   r4   r2   r    r   <module>r      s   # #
                  ? ? ? ? ? ? D D D D D D D D D D % % % % % %            = < < < < < < <           20 20 20 20 20 20 20 20jL L L L Lk L L L L Lr    