
    -iK                         S r SSKrSSKrSSKJr  SSKJr  SSK	J
r
  SSKJrJrJr  SSKJr  SSKJrJrJrJr  S	S
KJrJr  S	SKJrJrJrJr   " S S5      r " S S\5      rg)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                   0    \ rS rSrSrS rS rS rS rSr	g)	_BisectingTree   zITree structure representing the hierarchical clusters of BisectingKMeans.c                 D    Xl         X l        X0l        SU l        SU l        g)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       R/var/www/html/venv/lib/python3.13/site-packages/sklearn/cluster/_bisect_k_means.py__init___BisectingTree.__init__!   s!     
	
    c                     [        U R                  US:H     US   US   S9U l        [        U R                  US:H     US   US   S9U l        SU l        g)z,Split the cluster node into two subclusters.r   r   r   r   r   N)r   r   r   r   )r   labelscentersscoress       r   split_BisectingTree.split.   s]    "LL1-gajq	
	 $LL1-gajq	


 r"   c                 ~    SnU R                  5        H&  nUb  UR                  U:  d  M  UR                  nUnM(     W$ )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_bisect$_BisectingTree.get_cluster_to_bisect:   sH     	 ,,.L L$6$6$B(..	$0! /
 ! r"   c              #      #    U R                   c  U v   gU R                   R                  5        Sh  vN   U R                  R                  5        Sh  vN   g N' N7f)z0Iterate over all the cluster leaves in the tree.N)r   r+   r   )r   s    r   r+   _BisectingTree.iter_leavesJ   sH     99Jyy,,...zz--/// //s!   0AA!AAAA)r   r   r   r   r   N)
__name__
__module____qualname____firstlineno____doc__r    r(   r/   r+   __static_attributes__ r"   r   r   r      s    S
! 0r"   r   c                     ^  \ rS rSr% Sr0 \R                  E\" SS15      \/\	" \
SSSS9/S	/\" S
S15      /\" SS15      /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S9S S j5       rS rS rU 4S jrSrU =r$ )!BisectingKMeansS   aX  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_constraintsi,  r   g-C6?T)	rD   rE   random_statemax_iterverbosetolrF   rG   rH   c       	   
      P   > [         TU ]  UUUUUUUS9  Xl        Xl        Xl        g )N)
n_clustersrD   rK   rL   rJ   rM   rE   )superr    rF   rG   rH   )r   rO   rD   rE   rJ   rK   rL   rM   rF   rG   rH   	__class__s              r   r    BisectingKMeans.__init__   s>     	!% 	 	
 ""4r"   c                 8    [         R                  " SU S35        g)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_vcompBisectingKMeans._warn_mkl_vcomp   s"    ) *:(:!=	
r"   c           
          UR                   S   n[        R                  " U5      (       a  [        O[        n[
        R                  " U5      n[        U5       H  nU" XX#U R                  US9Xx'   M     U$ )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_weightrO   _inertiainertia_per_clusterlabels	            r   _inertia_per_cluster$BisectingKMeans._inertia_per_cluster  sg    , ]]1%
&(kk!nn?. hhz2:&E)1'4??QV*& '
 #"r"   c                 b   XR                      nX$R                      nX4R                      nSn[        U R                  5       H~  nU R                  UUU R                  U R
                  SUS9nU R                  UUUU R                  U R                  U R                  U R                  S9u  ppUb
  XS-  :  d  Mx  UnU
nU	nM     U R                  (       a  [        SW 35        U R                  S:X  a  U R                  UWWU5      nO[        R                  " WSS9nUR!                  UWU5        g)	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_normsrD   rJ   n_centroidsrd   )rK   rL   rM   	n_threadsg!?zNew centroids from bisection: rB   )	minlength)r   ra   rE   _init_centroidsrD   _random_state_kmeans_singlerK   rL   rM   rb   printrH   rh   r_   bincountr(   )r   rc   rk   rd   cluster_to_bisectbest_inertia_centers_initr%   inertiar&   best_labelsbest_centersr'   s                 r   _bisectBisectingKMeans._bisect(  s@   " ''()*C*CD%&?&?@ t{{#A// /YY!//+ 0 L +/*=*=HH// +> +'FW #w1J'J$&&3 $6 <<2<.AB""&77..<mF [[:F\6Br"   )prefer_skip_nested_validationc           
         [        U US[        R                  [        R                  /SU R                  SS9nU R                  U5        [        U R                  5      U l        [        X1UR                  S9n[        5       U l        U R                  S:X  d  U R                  S:X  a*  [        U l        U R#                  XR$                  S   5        O[&        U l        [(        R*                  " U5      (       d"  UR-                  SS	9U l        XR.                  -  n[1        [        R2                  " UR$                  S   5      UR-                  SS	9SS
9U l        [7        USS9n[9        U R                  S-
  5       H/  nU R4                  R;                  5       nU R=                  XX65        M1     [        R>                  " UR$                  S   S[        R@                  S9U l!        [        RD                  " U R                  UR$                  S   4UR                  S9U l#        [I        U R4                  RK                  5       5       HC  u  pxXpRB                  URL                  '   URN                  U RF                  U'   Xxl(        SUl&        ME     [(        R*                  " U5      (       d-  XR.                  -  nU =RF                  U R.                  -  sl#        [(        R*                  " U5      (       a  [R        O[T        n	U	" XU RF                  U RB                  U R                  5      U l+        U RF                  R$                  S   U l,        U $ )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r   r@   r   r   )axisr$   TsquaredN)-r   r_   float64float32rF   _check_params_vs_inputr   rJ   rp   r
   r   r   rb   rG   rO   r   rq   _check_mkl_vcompr\   r   r]   r^   mean_X_meanr   arange_bisecting_treer	   ra   r/   r{   fullint32labels_r`   cluster_centers_	enumerater+   r   r   rg   r   r   inertia__n_features_out)
r   rc   yrd   rk   rv   rt   icluster_nodere   s
             r   fitBisectingKMeans.fitj  s   6 ::rzz* %
 	##A&/0A0AB,]QWWM57>>W$1(<"6D!!!WWQZ0"6D {{1~~66q6>DLA  .IIaggaj)66q6> 
 $At4t*+A $ 4 4 J J L LL]N , wwqwwqz2RXX> "$//1771:)Fagg V()=)=)I)I)KLOA12LL--.'3':':D!!!$!"#'L 	  M {{1~~A!!T\\1!&(kk!nn?. d33T\\4??
  $44::1=r"   c                     [        U 5        U R                  U5      n[        USS9n[        R                  " U5      nU R                  XU R                  5      nU$ )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	   r_   	ones_like_predict_recursiver   )r   rc   rk   rd   r%   s        r   predictBisectingKMeans.predict  sU    ( 	!!!$#At4 _5((4;O;OPr"   c                    UR                   c;  [        R                  " UR                  S   UR                  [        R
                  S9$ [        R                  " UR                   R                  UR                  R                  45      n[        U S5      (       a  X@R                  -  n[        UUUU R                  SS9nUS:H  n[        R                  " UR                  S   S[        R
                  S9nU R                  X   X&   UR                   5      Xv'   U R                  X)    X&)    UR                  5      Xv) '   U$ )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.
r   r   r   F)return_inertiar   )r   r_   r   r\   rg   r   vstackr   r   hasattrr   r   rb   r   )r   rc   rd   r   r&   cluster_labelsmaskr%   s           r   r   "BisectingKMeans._predict_recursive  s   ( $771771:|'9'9JJ ))\..55|7I7I7P7PQR4##||#G9OO 
 " Rrxx8..G](,*;*;
 //eHmE*L,>,>
u r"   c                 l   > [         TU ]  5       nSUR                  l        SS/UR                  l        U$ )NTr   r   )rP   __sklearn_tags__
input_tagssparsetransformer_tagspreserves_dtype)r   tagsrQ   s     r   r    BisectingKMeans.__sklearn_tags__  s4    w')!%1:I0F-r"   )r   r   rq   r   rb   rp   rG   rH   r   rF   r   r   )   )NN)r3   r4   r5   r6   r7   r   rI   r   callabler   r   dict__annotations__r    rX   rh   r{   r   r   r   r   r   r8   __classcell__)rQ   s   @r   r;   r;   S   s    CJ$

,
,$[(34h?Haf=>+ '7!345)+<>O*PQR$D  5 ,5 58
#B@CD 5[ 6[z@1f r"   r;   ) r7   rU   numpyr_   scipy.sparser   r]   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   r;   r9   r"   r   <module>r      sT    #
     ? D D %  = 20 20jLk Lr"   