
    0Ph>                    (   d Z ddlZddlmZmZ ddlmZmZ ddlZ	ddl
mZ ddlmZmZmZmZm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 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( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z>m?Z?  e ddg eeddd          gddgddgdg eeddd          dgdd          dddddd            Z@	 d8d ZAd! ZB e ddgddgeCgd"d#          dd$d%d&d#d'ddd(d#d)
d*            ZD	 	 	 	 d9d+ZE e&dd,-          	 	 	 	 d9d.            ZFd:d/ZG  e&dd,-          eG          ZH G d0 d1eeeee          ZI G d2 d3eI          ZJ	 	 	 	 d;d5ZK G d6 d7eI          ZLdS )<zK-means clustering.    N)ABCabstractmethod)IntegralReal   )BaseEstimatorClassNamePrefixFeaturesOutMixinClusterMixinTransformerMixin_fit_context)ConvergenceWarning)_euclidean_distanceseuclidean_distances)check_arraycheck_random_state)_openmp_effective_n_threads)Interval
StrOptionsvalidate_params)	row_normsstable_cumsum)_get_threadpool_controller _threadpool_controller_decorator)mean_variance_axis)assign_rows_csr)_check_sample_weight_is_arraylike_not_scalarcheck_is_fittedvalidate_data   )
CHUNK_SIZE_inertia_dense_inertia_sparse_is_same_clustering)elkan_iter_chunked_denseelkan_iter_chunked_sparseinit_bounds_denseinit_bounds_sparse)lloyd_iter_chunked_denselloyd_iter_chunked_sparse)_minibatch_update_dense_minibatch_update_sparse
array-likezsparse matrixleftclosedrandom_state)X
n_clusterssample_weightx_squared_normsr1   n_local_trialsTprefer_skip_nested_validation)r4   r5   r1   r6   c                   t          | dt          j        t          j        g           t	          || | j                  }| j        d         |k     r!t          d| j        d          d| d          |t          | d	
          }nt          || j        d          }|j        d         | j        d         k    r,t          d|j        d          d| j        d          d          t          |          }t          | |||||          \  }}||fS )al	  Init n_clusters seeds according to k-means++.

    .. versionadded:: 0.24

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The data to pick seeds from.

    n_clusters : int
        The number of centroids to initialize.

    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 ignored if `init`
        is a callable or a user provided array.

        .. versionadded:: 1.3

    x_squared_norms : array-like of shape (n_samples,), default=None
        Squared Euclidean norm of each data point.

    random_state : int or RandomState instance, default=None
        Determines random number generation for centroid initialization. Pass
        an int for reproducible output across multiple function calls.
        See :term:`Glossary <random_state>`.

    n_local_trials : int, default=None
        The number of seeding trials for each center (except the first),
        of which the one reducing inertia the most is greedily chosen.
        Set to None to make the number of trials depend logarithmically
        on the number of seeds (2+log(k)) which is the recommended setting.
        Setting to 1 disables the greedy cluster selection and recovers the
        vanilla k-means++ algorithm which was empirically shown to work less
        well than its greedy variant.

    Returns
    -------
    centers : ndarray of shape (n_clusters, n_features)
        The initial centers for k-means.

    indices : ndarray of shape (n_clusters,)
        The index location of the chosen centers in the data array X. For a
        given index and center, X[index] = center.

    Notes
    -----
    Selects initial cluster centers for k-mean clustering in a smart way
    to speed up convergence. see: Arthur, D. and Vassilvitskii, S.
    "k-means++: the advantages of careful seeding". ACM-SIAM symposium
    on Discrete algorithms. 2007

    Examples
    --------

    >>> from sklearn.cluster import kmeans_plusplus
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [10, 2], [10, 4], [10, 0]])
    >>> centers, indices = kmeans_plusplus(X, n_clusters=2, random_state=0)
    >>> centers
    array([[10,  2],
           [ 1,  0]])
    >>> indices
    array([3, 2])
    csr)accept_sparsedtyper<   r   
n_samples= should be >= n_clusters=.NTsquaredF)r<   	ensure_2dzThe length of x_squared_norms z, should be equal to the length of n_samples )r   npfloat64float32r   r<   shape
ValueErrorr   r   _kmeans_plusplus)r2   r3   r4   r5   r1   r6   centersindicess           W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_kmeans.pykmeans_plusplusrM   9   sL   n rz2:.FGGGG(IIIMwqzJKKKjKKK
 
 	

 #At444%oQWPUVVVQ171:--A_-B1-E A A3471:A A A
 
 	

 &l33L (	:|^ GW G    c                 d   | j         \  }}t          j        ||f| j                  }|$dt	          t          j        |                    z   }|                    |||                                z            }	t          j        |dt                    }
t          j
        |           r| |	g                                         |d<   n| |	         |d<   |	|
d<   t          |dt          j        f         | |d          }||z  }t          d	|          D ]}|                    |
          |z  }t          j        t#          ||z            |          }t          j        |d|j        d	z
  |           t          | |         | |d          }t          j        |||           ||                    dd	          z  }t          j        |          }||         }||         }||         }t          j
        |           r| |g                                         ||<   n| |         ||<   ||
|<   ||
fS )a  Computational component for initialization of n_clusters by
    k-means++. Prior validation of data is assumed.

    Parameters
    ----------
    X : {ndarray, sparse matrix} of shape (n_samples, n_features)
        The data to pick seeds for.

    n_clusters : int
        The number of seeds to choose.

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

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

    random_state : RandomState instance
        The generator used to initialize the centers.
        See :term:`Glossary <random_state>`.

    n_local_trials : int, default=None
        The number of seeding trials for each center (except the first),
        of which the one reducing inertia the most is greedily chosen.
        Set to None to make the number of trials depend logarithmically
        on the number of seeds (2+log(k)); this is the default.

    Returns
    -------
    centers : ndarray of shape (n_clusters, n_features)
        The initial centers for k-means.

    indices : ndarray of shape (n_clusters,)
        The index location of the chosen centers in the data array X. For a
        given index and center, X[index] = center.
    r=   Nr   )pr   T)Y_norm_squaredrB   r    )size)out)rG   rD   emptyr<   intlogchoicesumfullspissparsetoarrayr   newaxisrangeuniformsearchsortedr   cliprS   minimumreshapeargmin)r2   r3   r5   r4   r1   r6   	n_samples
n_featuresrJ   	center_idrK   closest_dist_sqcurrent_potc	rand_valscandidate_idsdistance_to_candidatescandidates_potbest_candidates                      rL   rI   rI      sh   N GIzh
J/qw???G  S
!3!3444 ##IARARATAT1T#UUIgj"C000G	{1~~ "	{^++--

y\
GAJ +2:/4  O "M1K 1j!! $ $ !((n(==K	-/9::I
 
 	t_%9A%==QQQQ "6ma"
 "
 "

 	
?$:@VWWWW/-2G2GA2N2NN >22$^40@&~6 ;q>> 	+N+,4466GAJJ>*GAJ#

GrN   c                     |dk    rdS t          j        |           rt          | d          d         }nt          j        | d          }t          j        |          |z  S )z5Return a tolerance which is dependent on the dataset.r   axisr    )r[   r\   r   rD   varmean)r2   tol	variancess      rL   
_tolerancerx     sb    
axxq	{1~~ &&qq111!4		F11%%%	79##rN   )r2   r4   return_n_iterF	k-means++auto,  -C6?lloyd)
r4   initn_initmax_iterverboserv   r1   copy_x	algorithmry   c       
             t          ||||||||	|
	  	                            | |          }|r|j        |j        |j        |j        fS |j        |j        |j        fS )a'  Perform K-means clustering algorithm.

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

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The observations to cluster. It must be noted that the data
        will be converted to C ordering, which will cause a memory copy
        if the given data is not C-contiguous.

    n_clusters : int
        The number of clusters to form as well as the number of
        centroids to generate.

    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 or a user provided array.

    init : {'k-means++', 'random'}, callable or array-like of shape             (n_clusters, n_features), default='k-means++'
        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 an array is passed, it should be of shape `(n_clusters, n_features)`
          and gives the initial centers.
        - If a callable is passed, it should take arguments `X`, `n_clusters` and a
          random state and return an initialization.

    n_init : 'auto' or int, default="auto"
        Number of time the k-means algorithm will be run with different
        centroid seeds. The final results will be the best output of
        n_init consecutive runs in terms of inertia.

        When `n_init='auto'`, the number of runs depends on the value of init:
        10 if using `init='random'` or `init` is a callable;
        1 if using `init='k-means++'` or `init` is an array-like.

        .. versionadded:: 1.2
           Added 'auto' option for `n_init`.

        .. versionchanged:: 1.4
           Default value for `n_init` changed to `'auto'`.

    max_iter : int, default=300
        Maximum number of iterations of the k-means algorithm to run.

    verbose : bool, default=False
        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.

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

    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"
        K-means algorithm to use. 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)`.

        .. versionchanged:: 0.18
            Added Elkan algorithm

        .. versionchanged:: 1.1
            Renamed "full" to "lloyd", and deprecated "auto" and "full".
            Changed "auto" to use "lloyd" instead of "elkan".

    return_n_iter : bool, default=False
        Whether or not to return the number of iterations.

    Returns
    -------
    centroid : ndarray of shape (n_clusters, n_features)
        Centroids found at the last iteration of k-means.

    label : ndarray of shape (n_samples,)
        The `label[i]` is the code or index of the centroid the
        i'th observation is closest to.

    inertia : float
        The final value of the inertia criterion (sum of squared distances to
        the closest centroid for all observations in the training set).

    best_n_iter : int
        Number of iterations corresponding to the best results.
        Returned only if `return_n_iter` is set to True.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import k_means
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [10, 2], [10, 4], [10, 0]])
    >>> centroid, label, inertia = k_means(
    ...     X, n_clusters=2, n_init="auto", random_state=0
    ... )
    >>> centroid
    array([[10.,  2.],
           [ 1.,  2.]])
    >>> label
    array([1, 1, 1, 0, 0, 0], dtype=int32)
    >>> inertia
    16.0
    )	r3   r   r   r   r   rv   r1   r   r   r4   )KMeansfitcluster_centers_labels_inertia_n_iter_)r2   r3   r4   r   r   r   r   rv   r1   r   r   ry   ests                rL   k_meansr   "  s    j !
 
 
 
c!=c))   ?#S[#,KK#S[#,>>rN   c                 8   | j         d         }|j         d         }|}	t          j        |	          }
t          j        || j                  }t          j        |dt          j                  }|                                }t          |	          dz  }t          j	        t          j
        |          dd          d         }t          j        || j                  }t          j        ||f| j                  }t          j        || j                  }t          j        |           rt          }t          }t          }nt           }t"          }t$          } || |	|||||           d}t'          |          D ]} || ||	|
||||||||           t          |
          dz  }t          j	        t          j
        |          dd          d         }|r$ || ||	||          }t)          d	| d
|            |
|	}
}	t          j        ||          r|rt)          d| d           d} nB|dz                                  }||k    r|rt)          d| d| d| d            n||dd<   |s || ||	|	||||||||d            || ||	||          }|||	|dz   fS )a  A single run of k-means elkan, assumes preparation completed prior.

    Parameters
    ----------
    X : {ndarray, sparse matrix} of shape (n_samples, n_features)
        The observations to cluster. If sparse matrix, must be in CSR format.

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

    centers_init : ndarray of shape (n_clusters, n_features)
        The initial centers.

    max_iter : int, default=300
        Maximum number of iterations of the k-means algorithm to run.

    verbose : bool, default=False
        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.
        It's not advised to set `tol=0` since convergence might never be
        declared due to rounding errors. Use a very small number instead.

    n_threads : int, default=1
        The number of OpenMP threads to use for the computation. Parallelism is
        sample-wise on the main cython loop which assigns each sample to its
        closest center.

    Returns
    -------
    centroid : ndarray of shape (n_clusters, n_features)
        Centroids found at the last iteration of k-means.

    label : ndarray of shape (n_samples,)
        label[i] is the code or index of the centroid the
        i'th observation is closest to.

    inertia : float
        The final value of the inertia criterion (sum of squared distances to
        the closest centroid for all observations in the training set).

    n_iter : int
        Number of iterations run.
    r   r=   rQ   r   r    )kthrs   	n_threadsF
Iteration 
, inertia Converged at iteration : strict convergence.T: center shift  within tolerance r@   Nupdate_centers)rG   rD   
zeros_likezerosr<   rZ   int32copyr   	partitionasarrayr[   r\   r(   r&   r#   r'   r%   r"   r_   printarray_equalrY   )r2   r4   centers_initr   r   rv   r   rf   r3   rJ   centers_newweight_in_clusterslabels
labels_oldcenter_half_distancesdistance_next_centerupper_boundslower_boundscenter_shiftinit_bounds
elkan_iter_inertiastrict_convergenceiinertiacenter_shift_tots                             rL   _kmeans_single_elkanr     s   p 
I#A&J G-((K*AG<<<WY"(333FJ/881<<

())qq  	 8IQW555L8Y
317CCCL8Jag666L	{1~~ "(.
"'-
!K	    8__ . .
! 	
 	
 	
" !4K @ @1 D!|J,--11 
  
  

   	7hq-&)LLG5q55G55666*G>&*-- 	 JHHHHIII!%E !-a44663&& F! F F+F F?BF F F   
111 

!  	
 	
 	
 	
  hq-&)DDG7GQU**rN   blaslimitsuser_apic                 r   |j         d         }|}t          j        |          }	t          j        | j         d         dt          j                  }
|
                                }t          j        || j                  }t          j        || j                  }t          j	        |           rt          }t          }nt          }t          }d}t          |          D ]} || |||	||
||           |r% || |||
|          }t          d| d| d           |	|}	}t          j        |
|          r|rt          d| d	           d
} nB|dz                                  }||k    r|rt          d| d| d| d            n|
|dd<   |s || |||||
||d	  	          || |||
|          }|
|||dz   fS )a}  A single run of k-means lloyd, assumes preparation completed prior.

    Parameters
    ----------
    X : {ndarray, sparse matrix} of shape (n_samples, n_features)
        The observations to cluster. If sparse matrix, must be in CSR format.

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

    centers_init : ndarray of shape (n_clusters, n_features)
        The initial centers.

    max_iter : int, default=300
        Maximum number of iterations of the k-means algorithm to run.

    verbose : bool, default=False
        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.
        It's not advised to set `tol=0` since convergence might never be
        declared due to rounding errors. Use a very small number instead.

    n_threads : int, default=1
        The number of OpenMP threads to use for the computation. Parallelism is
        sample-wise on the main cython loop which assigns each sample to its
        closest center.

    Returns
    -------
    centroid : ndarray of shape (n_clusters, n_features)
        Centroids found at the last iteration of k-means.

    label : ndarray of shape (n_samples,)
        label[i] is the code or index of the centroid the
        i'th observation is closest to.

    inertia : float
        The final value of the inertia criterion (sum of squared distances to
        the closest centroid for all observations in the training set).

    n_iter : int
        Number of iterations run.
    r   rQ   r=   Fr   r   r@   r   r   Tr   r   r   Nr   r    )rG   rD   r   rZ   r   r   r   r<   r[   r\   r*   r#   r)   r"   r_   r   r   rY   )r2   r4   r   r   r   rv   r   r3   rJ   r   r   r   r   r   
lloyd_iterr   r   r   r   r   s                       rL   _kmeans_single_lloydr   o  sn   r #A&J G-((KWQWQZ28444FJ*AG<<<8Jag666L	{1~~ ".
"-
!8__ # #
		
 		
 		
  	8hq-&)LLG6q66G666777*G>&*-- 	 JHHHHIII!%E !-a44663&& F! F F+F F?BF F F   
111 

 
	
 
	
 
	
 
	
 hq-&)DDG7GQU**rN   c                 f   | j         d         }|j         d         }t          j        |dt          j                  }t          j        ||j                  }t          j        |           rt          }	t          }
nt          }	t          }
 |	| ||dd|||d	  	         |r |
| ||||          }||fS |S )a  E step of the K-means EM algorithm.

    Compute the labels and the inertia of the given samples and centers.

    Parameters
    ----------
    X : {ndarray, sparse matrix} of shape (n_samples, n_features)
        The input samples to assign to the labels. If sparse matrix, must
        be in CSR format.

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

    x_squared_norms : ndarray of shape (n_samples,)
        Precomputed squared euclidean norm of each data point, to speed up
        computations.

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

    n_threads : int, default=1
        The number of OpenMP threads to use for the computation. Parallelism is
        sample-wise on the main cython loop which assigns each sample to its
        closest center.

    return_inertia : bool, default=True
        Whether to compute and return the inertia.

    Returns
    -------
    labels : ndarray of shape (n_samples,)
        The resulting assignment.

    inertia : float
        Sum of squared distances of samples to their closest cluster center.
        Inertia is only returned if return_inertia is True.
    r   rQ   r=   NF)r   r   r   r   r   r   )rG   rD   rZ   r   r   r<   r[   r\   r*   r#   r)   r"   )r2   r4   rJ   r   return_inertiarf   r3   r   r   _labelsr   r   s               rL   _labels_inertiar     s    L 
Iq!JWY"(333F8Jgm<<<L	{1~~ "+"*!G	!
 
 
 
  (1mWfiHHwMrN   c            
       T    e Zd ZU dZ eeddd          g eddh          edg ed	h           eeddd          g eeddd          g eed
dd          gdgdgdZ	e
ed<   d ZddZed             Zd Zd Zd Z	 	 ddZddZd ZddZd Zd ZddZ fdZ xZS )_BaseKMeansz)Base class for KMeans and MiniBatchKMeansr    Nr.   r/   rz   randomr-   r{   r   r   r1   r3   r   r   r   rv   r   r1   _parameter_constraintsc                h    || _         || _        || _        || _        || _        || _        || _        d S N)r3   r   r   rv   r   r   r1   )selfr3   r   r   r   rv   r   r1   s           rL   __init__z_BaseKMeans.__init__Q  s<     %	 (rN   c                    |j         d         | j        k     r&t          d|j         d          d| j         d          t          || j                  | _        | j        dk    r~t          | j        t                    r| j        dk    rd| _
        n]t          | j        t                    r| j        dk    r|| _
        n0t          | j                  r|| _
        nd| _
        n| j        | _
        t          | j                  rF| j
        dk    r=t          j        d	| j        j         d
| j
         dt"          d           d| _
        d S d S d S )Nr   r>   r?   r@   r{   rz   r    r   zEExplicit initial center position passed: performing only one init in z instead of n_init=r   
stacklevel)rG   r3   rH   rx   rv   _tolr   
isinstancer   str_n_initcallabler   warningswarn	__class____name__RuntimeWarning)r   r2   default_n_inits      rL   _check_params_vs_inputz"_BaseKMeans._check_params_vs_inputd  so   71:''TQWQZTT$/TTT  
 q$(++	 ;&  $)S)) !di;.F.F DIs++ !	X0E0E-$)$$ !- ;DL#DI.. 
	4<13D3DM.$(N$;. ."l. . .     DLLL
	 
	3D3DrN   c                     dS )zIssue an estimator specific warning when vcomp and mkl are both present

        This method is called by `_check_mkl_vcomp`.
        N r   n_active_threadss     rL   _warn_mkl_vcompz_BaseKMeans._warn_mkl_vcomp  s      rN   c                 P   t          j        |          rdS t          t          j        |t
          z                      }|| j        k     rWt                                                      }dd |D             v }dd |D             v }|r|r| 	                    |           dS dS dS dS )z)Check when vcomp and mkl are both presentNvcompc                     g | ]
}|d          S )prefixr   .0modules     rL   
<listcomp>z0_BaseKMeans._check_mkl_vcomp.<locals>.<listcomp>  s    #K#K#KF8$4#K#K#KrN   )mklintelc                 J    g | ] }|d          |                     dd          f!S )internal_apithreading_layerN)getr   s     rL   r   z0_BaseKMeans._check_mkl_vcomp.<locals>.<listcomp>  sA     + + + '4Et)L)LM+ + +rN   )
r[   r\   rV   rD   ceilr!   
_n_threadsr   infor   )r   r2   rf   r   modules	has_vcomphas_mkls          rL   _check_mkl_vcompz_BaseKMeans._check_mkl_vcomp  s     ;q>> 	Frwy:'=>>??do--0227799G#K#K7#K#K#KKI& + +%+ + + G  7W 7$$%566666 .-7 7 7 7rN   c                     |j         d         | j        k    r t          d|j          d| j         d          |j         d         |j         d         k    r&t          d|j          d|j         d          d          dS )z5Check if centers is compatible with X and n_clusters.r   z!The shape of the initial centers z' does not match the number of clusters r@   r    z3 does not match the number of features of the data N)rG   r3   rH   )r   r2   rJ   s      rL   _validate_center_shapez"_BaseKMeans._validate_center_shape  s    =t..CGM C C04C C C   =qwqz))JGM J J<=GAJJ J J   *)rN   c           	      ^    t          | |ddt          j        t          j        gdd          }|S )Nr:   FC)r;   resetr<   orderaccept_large_sparse)r   rD   rE   rF   r   r2   s     rL   _check_test_dataz_BaseKMeans._check_test_data  s;    :rz* %
 
 
 rN   c                    |j         d         }|| j        n|}	|B||k     r<|                    d||          }
||
         }||
         }|j         d         }||
         }t          |t                    r|dk    rt          ||	|||          \  }}nt          |t                    r=|dk    r7|                    ||	d||                                z            }||         }nbt          | j	                  r|}nKt          |          r< |||	|          }t          ||j        dd	
          }|                     ||           t          j        |          r|                                }|S )a  Compute the initial centroids.

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

        x_squared_norms : ndarray of shape (n_samples,)
            Squared euclidean norm of each data point. Pass it if you have it
            at hands already to avoid it being recomputed here.

        init : {'k-means++', 'random'}, callable or ndarray of shape                 (n_clusters, n_features)
            Method for initialization.

        random_state : RandomState instance
            Determines random number generation for centroid initialization.
            See :term:`Glossary <random_state>`.

        sample_weight : ndarray of shape (n_samples,)
            The weights for each observation in X. `sample_weight` is not used
            during initialization if `init` is a callable or a user provided
            array.

        init_size : int, default=None
            Number of samples to randomly sample for speeding up the
            initialization (sometimes at the expense of accuracy).

        n_centroids : int, default=None
            Number of centroids to initialize.
            If left to 'None' the number of centroids will be equal to
            number of clusters to form (self.n_clusters).

        Returns
        -------
        centers : ndarray of shape (n_clusters, n_features)
            Initial centroids of clusters.
        r   Nrz   )r1   r5   r4   r   F)rS   replacerP   )r1   r   r<   r   r   )rG   r3   randintr   r   rI   rX   rY   r   r   r   r   r<   r   r[   r\   r]   )r   r2   r5   r   r1   r4   	init_sizen_centroidsrf   r3   init_indicesrJ   _seedss                 rL   _init_centroidsz_BaseKMeans._init_centroids  s   ` GAJ	(3(;T__
 Y%:%:'//9iHHL,A-l;O
I),7MdC   	4T[%8%8)) /+  JGQQ c"" 	4tx'7'7 ''-"3"3"5"55	 (  E hGG%di00 	4GGd^^ 	4d1j|DDDG!'uCPPPG''7333;w 	(oo''GrN   c                 :    |                      ||          j        S )a  Compute cluster centers and predict cluster index for each sample.

        Convenience method; equivalent to calling fit(X) followed by
        predict(X).

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

        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.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Index of the cluster each sample belongs to.
        r   )r   r   r   r2   yr4   s       rL   fit_predictz_BaseKMeans.fit_predict  s    . xxx77??rN   c                     t          |            |                     |          }t          j        |j        d         |j                  }t          ||| j        | j        d          }|S )a  Predict the closest cluster each sample in X belongs to.

        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.
        r   r=   F)r   r   )	r   r   rD   onesrG   r<    _labels_inertia_threadpool_limitr   r   )r   r2   r4   r   s       rL   predictz_BaseKMeans.predict*  sr    " 	!!!$$ 
!':::1!o 
 
 
 rN   c                 V    |                      ||                              |          S )a  Compute clustering and transform X to cluster-distance space.

        Equivalent to fit(X).transform(X), but more efficiently implemented.

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

        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.

        Returns
        -------
        X_new : ndarray of shape (n_samples, n_clusters)
            X transformed in the new space.
        r   )r   
_transformr  s       rL   fit_transformz_BaseKMeans.fit_transformL  s(    , xxx77BB1EEErN   c                 t    t          |            |                     |          }|                     |          S )a  Transform X to a cluster-distance space.

        In the new space, each dimension is the distance to the cluster
        centers. Note that even if X is sparse, the array returned by
        `transform` will typically be dense.

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

        Returns
        -------
        X_new : ndarray of shape (n_samples, n_clusters)
            X transformed in the new space.
        )r   r   r  r   s     rL   	transformz_BaseKMeans.transformd  s7    " 	!!!$$q!!!rN   c                 ,    t          || j                  S )z.Guts of transform method; no input validation.)r   r   r   s     rL   r  z_BaseKMeans._transformz  s    "1d&;<<<rN   c                     t          |            |                     |          }t          |||j                  }t	          ||| j        | j                  \  }}| S )aR  Opposite of the value of X on the K-means objective.

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

        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.

        Returns
        -------
        score : float
            Opposite of the value of X on the K-means objective.
        r=   )r   r   r   r<   r  r   r   )r   r2   r  r4   r  scoress         rL   scorez_BaseKMeans.score~  se    ( 	!!!$$,]AQWMMM4}d3T_
 
	6 wrN   c                 `    t                                                      }d|j        _        |S )NT)super__sklearn_tags__
input_tagssparse)r   tagsr   s     rL   r  z_BaseKMeans.__sklearn_tags__  s'    ww''))!%rN   r   NN)r   
__module____qualname____doc__r   r   r   r   r   r   dict__annotations__r   r   r   r   r   r   r   r  r  r  r  r  r  r  r  __classcell__r   s   @rL   r   r   ?  s         43  x!T&AAAB[(344hMJx  HXq$v666
 Xh4???@q$v6667;'($ $D   ) ) )&! ! ! !F   ^7 7 7(  
 
 
& T T T Tl@ @ @ @2     DF F F F0" " ",= = =   <        rN   r   c            
            e Zd ZU dZi ej        dg eddh          gdZeed<   	 ddd	d
dddddd fdZ	 fdZ
d Z ed          dd            Z xZS )r   a  K-Means clustering.

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

    Parameters
    ----------

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

        For an example of how to choose an optimal value for `n_clusters` refer to
        :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_silhouette_analysis.py`.

    init : {'k-means++', 'random'}, callable or array-like of shape             (n_clusters, n_features), default='k-means++'
        Method for initialization:

        * 'k-means++' : selects initial cluster centroids using sampling             based on an empirical probability distribution of the points'             contribution to the overall inertia. This technique speeds up             convergence. The algorithm implemented is "greedy k-means++". It             differs from the vanilla k-means++ by making several trials at             each sampling step and choosing the best centroid among them.

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

        * If an array is passed, it should be of shape (n_clusters, n_features)        and gives the initial centers.

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

        For an example of how to use the different `init` strategies, see
        :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_digits.py`.

        For an evaluation of the impact of initialization, see the example
        :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_stability_low_dim_dense.py`.

    n_init : 'auto' or int, default='auto'
        Number of times the k-means algorithm is run with different centroid
        seeds. The final results is the best output of `n_init` consecutive runs
        in terms of inertia. Several runs are recommended for sparse
        high-dimensional problems (see :ref:`kmeans_sparse_high_dim`).

        When `n_init='auto'`, the number of runs depends on the value of init:
        10 if using `init='random'` or `init` is a callable;
        1 if using `init='k-means++'` or `init` is an array-like.

        .. versionadded:: 1.2
           Added 'auto' option for `n_init`.

        .. versionchanged:: 1.4
           Default value for `n_init` changed to `'auto'`.

    max_iter : int, default=300
        Maximum number of iterations of the k-means algorithm for a
        single run.

    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.

    verbose : int, default=0
        Verbosity mode.

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

    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"
        K-means algorithm to use. 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)`.

        .. versionchanged:: 0.18
            Added Elkan algorithm

        .. versionchanged:: 1.1
            Renamed "full" to "lloyd", and deprecated "auto" and "full".
            Changed "auto" to use "lloyd" instead of "elkan".

    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_iter_ : int
        Number of iterations run.

    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
    --------
    MiniBatchKMeans : Alternative online implementation that does incremental
        updates of the centers positions using mini-batches.
        For large scale learning (say n_samples > 10k) MiniBatchKMeans is
        probably much faster than the default batch implementation.

    Notes
    -----
    The k-means problem is solved using either Lloyd's or Elkan's algorithm.

    The average complexity is given by O(k n T), where n is the number of
    samples and T is the number of iteration.

    The worst case complexity is given by O(n^(k+2/p)) with
    n = n_samples, p = n_features.
    Refer to :doi:`"How slow is the k-means method?" D. Arthur and S. Vassilvitskii -
    SoCG2006.<10.1145/1137856.1137880>` for more details.

    In practice, the k-means algorithm is very fast (one of the fastest
    clustering algorithms available), but it falls in local minima. That's why
    it can be useful to restart it several times.

    If the algorithm stops before fully converging (because of ``tol`` or
    ``max_iter``), ``labels_`` and ``cluster_centers_`` will not be consistent,
    i.e. the ``cluster_centers_`` will not be the means of the points in each
    cluster. Also, the estimator will reassign ``labels_`` after the last
    iteration to make ``labels_`` consistent with ``predict`` on the training
    set.

    Examples
    --------

    >>> from sklearn.cluster import KMeans
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [10, 2], [10, 4], [10, 0]])
    >>> kmeans = KMeans(n_clusters=2, random_state=0, n_init="auto").fit(X)
    >>> kmeans.labels_
    array([1, 1, 1, 0, 0, 0], dtype=int32)
    >>> kmeans.predict([[0, 0], [12, 3]])
    array([1, 0], dtype=int32)
    >>> kmeans.cluster_centers_
    array([[10.,  2.],
           [ 1.,  2.]])

    For examples of common problems with K-Means and how to address them see
    :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_assumptions.py`.

    For a demonstration of how K-Means can be used to cluster text documents see
    :ref:`sphx_glr_auto_examples_text_plot_document_clustering.py`.

    For a comparison between K-Means and MiniBatchKMeans refer to example
    :ref:`sphx_glr_auto_examples_cluster_plot_mini_batch_kmeans.py`.

    For a comparison between K-Means and BisectingKMeans refer to example
    :ref:`sphx_glr_auto_examples_cluster_plot_bisect_kmeans.py`.
    booleanr~   elkan)r   r   r      rz   r{   r|   r}   r   NT)r   r   r   rv   r   r1   r   r   c          	      t    t                                          |||||||           || _        |	| _        d S )Nr   )r  r   r   r   )r   r3   r   r   r   rv   r   r1   r   r   r   s             rL   r   zKMeans.__init__a  sO     	!% 	 	
 	
 	
 "rN   c                     t                                          |d           | j        | _        | j        dk    r.| j        dk    r%t          j        dt                     d| _        d S d S d S )N
   r   r&  r    zQalgorithm='elkan' doesn't make sense for a single cluster. Using 'lloyd' instead.r~   )r  r   r   
_algorithmr3   r   r   r   r   r2   r   s     rL   r   zKMeans._check_params_vs_input{  s{    &&q&<<<.?g%%$/Q*>*>M6    &DOOO &%*>*>rN   c                 6    t          j        d| d           dS )(Warn when vcomp and mkl are both presentzKMeans 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=r@   N)r   r   r   s     rL   r   zKMeans._warn_mkl_vcomp  s9    = *:= = =	
 	
 	
 	
 	
rN   r7   c           
      @   t          | |dt          j        t          j        gd| j        d          }|                     |           t          | j                  }t          |||j	                  }t                      | _        | j        }t          |          }|r.t          ||j	        dd          }|                     ||           t!          j        |          s"|                    d	          }||z  }|r||z  }t'          |d
          }| j        dk    rt*          }	n(t,          }	|                     ||j        d                    d\  }
}t3          | j                  D ]}|                     |||||          }| j        rt;          d            |	|||| j        | j        | j        | j                  \  }}}}|
||
k     rtA          ||| j!                  s|}|}|}
|}t!          j        |          s| j        s||z  }||z  }tE          tG          |                    }|| j!        k     r5tI          j%        d&                    || j!                  tN          d           || _(        | j(        j        d         | _)        || _*        |
| _+        || _,        | S )a  Compute k-means clustering.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training instances to cluster. It must be noted that the data
            will be converted to C ordering, which will cause a memory
            copy if the given data is not C-contiguous.
            If a sparse matrix is passed, a copy will be made if it's not in
            CSR format.

        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 or a user provided array.

            .. versionadded:: 0.20

        Returns
        -------
        self : object
            Fitted estimator.
        r:   r   F)r;   r<   r   r   r   r=   Tr   r   rr   rA   r&  r  )r5   r   r1   r4   zInitialization complete)r   r   rv   r   NzkNumber of distinct clusters ({}) found smaller than n_clusters ({}). Possibly due to duplicate points in X.r   r   )-r   rD   rE   rF   r   r   r   r1   r   r<   r   r   r   r   r   r   r[   r\   ru   r   r,  r   r   r   rG   r_   r   r  r   r   r   r   r$   r3   lensetr   r   formatr   r   _n_features_outr   r   r   )r   r2   r  r4   r1   r   init_is_array_likeX_meanr5   kmeans_singlebest_inertiabest_labelsr   r   r   r   rJ   r   best_centersbest_n_iterdistinct_clusterss                        rL   r   z
KMeans.fit  s   8 :rz* %
 
 
 	##A&&&)$*;<<,]AQWMMM577 y5d;; 	1t17SIIID''4000 {1~~ 	VVV^^FKA!  $At444?g%%0MM0M!!!QWQZ000$.!kt|$$ #	& #	&A// /)+ 0  L | 1/000 1>I/1 1 1-FGWg #,&&+FKQQ ' %&&%{1~~ 	#; VF"LK 0 011t..M0$/BB"    !-#4:1="$"rN   r'  r  )r   r  r  r  r   r   r   r   r!  r   r   r   r   r   r"  r#  s   @rL   r   r     s         v vp$

,$+ j'7!3445$ $ $D    # # # # # # # #4& & & & &
 
 
 \555   65    rN   r   {Gz?c
           	         t          | |||	          \  }
}t          j        |           rt          | |||||
|	           nt	          | |||||
|	           |rx|dk    rq|||                                z  k     }|                                d| j        d         z  k    r<t          j	        |          t          d| j        d         z            d         }d||<   |                                }|r|                    | j        d         d|          }|rt          d| d           t          j        |           rit          | |                    t          j        d	          t          j        |          d                             t          j        d	          |           n| |         ||<   t          j        ||                    ||<   |S )
as  Incremental update of the centers for the Minibatch K-Means algorithm.

    Parameters
    ----------

    X : {ndarray, sparse matrix} of shape (n_samples, n_features)
        The original data array. If sparse, must be in CSR format.

    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`.

    centers : ndarray of shape (n_clusters, n_features)
        The cluster centers before the current iteration

    centers_new : ndarray of shape (n_clusters, n_features)
        The cluster centers after the current iteration. Modified in-place.

    weight_sums : ndarray of shape (n_clusters,)
        The vector in which we keep track of the numbers of points in a
        cluster. This array is modified in place.

    random_state : RandomState instance
        Determines random number generation for low count centers reassignment.
        See :term:`Glossary <random_state>`.

    random_reassign : boolean, default=False
        If True, centers with very low counts are randomly reassigned
        to observations.

    reassignment_ratio : float, default=0.01
        Control the fraction of the maximum number of counts for a
        center to be reassigned. A higher value means that low count
        centers are more likely to be reassigned, which means that the
        model will take longer to converge, but should converge in a
        better clustering.

    verbose : bool, default=False
        Controls the verbosity.

    n_threads : int, default=1
        The number of OpenMP threads to use for the computation.

    Returns
    -------
    inertia : float
        Sum of squared distances of samples to their closest cluster center.
        The inertia is computed after finding the labels and before updating
        the centers.
    r   r   g      ?NF)r   rS   z[MiniBatchKMeans] Reassigning z cluster centers.)r   )r   r[   r\   r,   r+   maxrY   rG   rD   argsortrV   rX   r   r   astypeintpwheremin)r2   r4   rJ   r   weight_sumsr1   random_reassignreassignment_ratior   r   r   r   to_reassignindices_dont_reassignn_reassignsnew_centerss                   rL   _mini_batch_steprM    s   F &a9UUUOFG 
{1~~ 
 }g{K	
 	
 	
 	
 	 	
 	
 	
  E-11!$69J9J$JJ ??sQWQZ///$&J{$;$;Cagaj@P<Q<Q<S<S$T!16K-.!oo'' 	:&--
E .  K  WU{UUUVVV{1~~ :&&rwU&;;H[))!,33BG%3HH	    ,-[>K(
 $&6+{l*C#D#DK NrN   c                   X    e Zd ZU dZi ej         eeddd          gdg eeddd          dg eed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dd fdZ fdZd Zd Zd Z ed          dd            Z ed          dd            Z xZS )MiniBatchKMeansa.  
    Mini-Batch K-Means clustering.

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

    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'}, callable or array-like of shape             (n_clusters, n_features), default='k-means++'
        Method for initialization:

        'k-means++' : selects initial cluster centroids using sampling based on
        an empirical probability distribution of the points' contribution to the
        overall inertia. This technique speeds up convergence. The algorithm
        implemented is "greedy k-means++". It differs from the vanilla k-means++
        by making several trials at each sampling step and choosing the best centroid
        among them.

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

        If an array is passed, it should be of shape (n_clusters, n_features)
        and gives the initial centers.

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

        For an evaluation of the impact of initialization, see the example
        :ref:`sphx_glr_auto_examples_cluster_plot_kmeans_stability_low_dim_dense.py`.

    max_iter : int, default=100
        Maximum number of iterations over the complete dataset before
        stopping independently of any early stopping criterion heuristics.

    batch_size : int, default=1024
        Size of the mini batches.
        For faster computations, you can set the ``batch_size`` greater than
        256 * number of cores to enable parallelism on all cores.

        .. versionchanged:: 1.0
           `batch_size` default changed from 100 to 1024.

    verbose : int, default=0
        Verbosity mode.

    compute_labels : bool, default=True
        Compute label assignment and inertia for the complete dataset
        once the minibatch optimization has converged in fit.

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

    tol : float, default=0.0
        Control early stopping based on the relative center changes as
        measured by a smoothed, variance-normalized of the mean center
        squared position changes. This early stopping heuristics is
        closer to the one used for the batch variant of the algorithms
        but induces a slight computational and memory overhead over the
        inertia heuristic.

        To disable convergence detection based on normalized center
        change, set tol to 0.0 (default).

    max_no_improvement : int, default=10
        Control early stopping based on the consecutive number of mini
        batches that does not yield an improvement on the smoothed inertia.

        To disable convergence detection based on inertia, set
        max_no_improvement to None.

    init_size : int, default=None
        Number of samples to randomly sample for speeding up the
        initialization (sometimes at the expense of accuracy): the
        only algorithm is initialized by running a batch KMeans on a
        random subset of the data. This needs to be larger than n_clusters.

        If `None`, the heuristic is `init_size = 3 * batch_size` if
        `3 * batch_size < n_clusters`, else `init_size = 3 * n_clusters`.

    n_init : 'auto' or int, default="auto"
        Number of random initializations that are tried.
        In contrast to KMeans, the algorithm is only run once, using the best of
        the `n_init` initializations as measured by inertia. Several runs are
        recommended for sparse high-dimensional problems (see
        :ref:`kmeans_sparse_high_dim`).

        When `n_init='auto'`, the number of runs depends on the value of init:
        3 if using `init='random'` or `init` is a callable;
        1 if using `init='k-means++'` or `init` is an array-like.

        .. versionadded:: 1.2
           Added 'auto' option for `n_init`.

        .. versionchanged:: 1.4
           Default value for `n_init` changed to `'auto'` in version.

    reassignment_ratio : float, default=0.01
        Control the fraction of the maximum number of counts for a center to
        be reassigned. A higher value means that low count centers are more
        easily reassigned, which means that the model will take longer to
        converge, but should converge in a better clustering. However, too high
        a value may cause convergence issues, especially with a small batch
        size.

    Attributes
    ----------

    cluster_centers_ : ndarray of shape (n_clusters, n_features)
        Coordinates of cluster centers.

    labels_ : ndarray of shape (n_samples,)
        Labels of each point (if compute_labels is set to True).

    inertia_ : float
        The value of the inertia criterion associated with the chosen
        partition if compute_labels is set to True. If compute_labels is set to
        False, it's an approximation of the inertia based on an exponentially
        weighted average of the batch inertiae.
        The inertia is defined as the sum of square distances of samples to
        their cluster center, weighted by the sample weights if provided.

    n_iter_ : int
        Number of iterations over the full dataset.

    n_steps_ : int
        Number of minibatches processed.

        .. versionadded:: 1.0

    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
    --------
    KMeans : The classic implementation of the clustering method based on the
        Lloyd's algorithm. It consumes the whole set of input data at each
        iteration.

    Notes
    -----
    See https://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf

    When there are too few points in the dataset, some centers may be
    duplicated, which means that a proper clustering in terms of the number
    of requesting clusters and the number of returned clusters will not
    always match. One solution is to set `reassignment_ratio=0`, which
    prevents reassignments of clusters that are too small.

    See :ref:`sphx_glr_auto_examples_cluster_plot_birch_vs_minibatchkmeans.py` for a
    comparison with :class:`~sklearn.cluster.BIRCH`.

    Examples
    --------
    >>> from sklearn.cluster import MiniBatchKMeans
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [4, 2], [4, 0], [4, 4],
    ...               [4, 5], [0, 1], [2, 2],
    ...               [3, 2], [5, 5], [1, -1]])
    >>> # manually fit on batches
    >>> kmeans = MiniBatchKMeans(n_clusters=2,
    ...                          random_state=0,
    ...                          batch_size=6,
    ...                          n_init="auto")
    >>> kmeans = kmeans.partial_fit(X[0:6,:])
    >>> kmeans = kmeans.partial_fit(X[6:12,:])
    >>> kmeans.cluster_centers_
    array([[3.375, 3.  ],
           [0.75 , 0.5 ]])
    >>> kmeans.predict([[0, 0], [4, 4]])
    array([1, 0], dtype=int32)
    >>> # fit on the whole data
    >>> kmeans = MiniBatchKMeans(n_clusters=2,
    ...                          random_state=0,
    ...                          batch_size=6,
    ...                          max_iter=10,
    ...                          n_init="auto").fit(X)
    >>> kmeans.cluster_centers_
    array([[3.55102041, 2.48979592],
           [1.06896552, 1.        ]])
    >>> kmeans.predict([[0, 0], [4, 4]])
    array([1, 0], dtype=int32)
    r    Nr.   r/   r%  r   )
batch_sizecompute_labelsmax_no_improvementr   rH  r   r'  rz   d   i   T        r*  r{   r>  )r   r   rP  r   rQ  r1   rv   rR  r   r   rH  c          	          t                                          |||||||           |	| _        || _        || _        |
| _        || _        d S )N)r3   r   r   r   r1   rv   r   )r  r   rR  rP  rQ  r   rH  )r   r3   r   r   rP  r   rQ  r1   rv   rR  r   r   rH  r   s                rL   r   zMiniBatchKMeans.__init___  si      	!% 	 	
 	
 	
 #5$,""4rN   c                 D   t                                          |d           t          | j        |j        d                   | _        | j        | _        | j        /d| j        z  | _        | j        | j        k     rd| j        z  | _        nL| j        | j        k     r<t          j
        d| j         d| j         dt          d           d| j        z  | _        t          | j        |j        d                   | _        | j        dk     rt          d	| j         d
          d S )N   r+  r   z
init_size=z" should be larger than n_clusters=z,. Setting it to min(3*n_clusters, n_samples)r   r   z'reassignment_ratio should be >= 0, got z	 instead.)r  r   rE  rP  rG   _batch_sizer   
_init_sizer3   r   r   r   rH  rH   r-  s     rL   r   z&MiniBatchKMeans._check_params_vs_input  s>   &&q&;;;t
;; .?"$"22DO00"#do"5_t..M3 3 3"&/3 3 3      $/1DOdoqwqz:: "Q&&6*6 6 6   '&rN   c                 T    t          j        d| j        t          z   d|            dS )r/  zMiniBatchKMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can prevent it by setting batch_size >= z8 or by setting the environment variable OMP_NUM_THREADS=N)r   r   r   r!   r   s     rL   r   zMiniBatchKMeans._warn_mkl_vcomp  sJ    2 "_z92 2
  02 2	
 	
 	
 	
 	
rN   c           
         || j         z  }|dz   }|dk    r!| j        rt          d| d| d|            dS | j        || _        n8| j         dz  |dz   z  }t	          |d          }| j        d|z
  z  ||z  z   | _        | j        r t          d| d| d| d| j                    | j        d	k    r)|| j        k    r| j        rt          d
| d|            dS | j        | j        | j        k     rd| _        | j        | _        n| xj        dz  c_        | j        .| j        | j        k    r| j        rt          d| d|            dS dS )z7Helper function to encapsulate the early stopping logicr    zMinibatch step /z: mean batch inertia: FNg       @z, ewa inertia: rT  z)Converged (small centers change) at step Tr   z3Converged (lack of improvement in inertia) at step )	rX  r   r   _ewa_inertiarE  r   _ewa_inertia_min_no_improvementrR  )r   stepn_stepsrf   centers_squared_diffbatch_inertiaalphas          rL   _mini_batch_convergencez'MiniBatchKMeans._mini_batch_convergence  s    	)) ax 199| 0d 0 0W 0 0 -0 0   5
 $ -D$s*i!m<EqMME $ 1QY ?-RWBW WD < 	E$ E E E E E E151BE E   9s??3ty@@| TR$RRRRSSS4  (D,=@U,U,U#$D $($5D!!  A%   #/$(???| (( (%( (   4urN   c                     | xj         | j        z  c_         | j        dk                                    s| j         d| j        z  k    r	d| _         dS dS )zCheck if a random reassignment needs to be done.

        Do random reassignments each time 10 * n_clusters samples have been
        processed.

        If there are empty clusters we always want to reassign.
        r   r*  TF)_n_since_last_reassignrX  _countsanyr3   )r   s    rL   _random_reassignz MiniBatchKMeans._random_reassign  sc     	##t'77##LA""$$ 	(C )
 )
 +,D'4urN   r7   c                    t          | |dt          j        t          j        gdd          }|                     |           t          | j                  }t          |||j                  }t                      | _
        |j        \  }}| j        }t          |          r.t          ||j        dd          }|                     ||           |                     || j                   t%          |d          }|                    d	|| j                  }	||	         }
||	         }d
}t+          | j                  D ]}| j        r t1          d|dz    d| j         d|            |                     ||||| j        |          }t5          |
||| j
                  \  }}| j        r t1          d|dz    d| j         d|            |||k     r|}|}|}t          j        |          }t          j        | j        |j                  | _        d
| _        d
| _         d	| _!        d	| _"        | j#        |z  | j        z  }tI                      %                    dd          5  t+          |          D ]}|                    d	|| j                  }tM          ||         ||         ||| j        || '                                | j(        | j        | j
        
  
        }| j)        dk    rt          j*        ||z
  dz            }nd	}||}}| +                    |||||          r nd
d
d
           n# 1 swxY w Y   || _,        | j,        j        d	         | _-        |dz   | _.        t_          t          j0        |dz   | j        z  |z                      | _1        | j2        r+t5          ||| j,        | j
                  \  | _3        | _4        n| j        |z  | _4        | S )a  Compute the centroids on X by chunking it into mini-batches.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training instances to cluster. It must be noted that the data
            will be converted to C ordering, which will cause a memory copy
            if the given data is not C-contiguous.
            If a sparse matrix is passed, a copy will be made if it's not in
            CSR format.

        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 or a user provided array.

            .. versionadded:: 0.20

        Returns
        -------
        self : object
            Fitted estimator.
        r:   r   F)r;   r<   r   r   r=   Tr   rA   r   NzInit r    r\  z with method r5   r   r1   r   r4   r   zInertia for init z: r   r   )
r2   r4   rJ   r   rF  r1   rG  rH  r   r   rT  r   )5r   rD   rE   rF   r   r   r1   r   r<   r   r   rG   r   r   r   r   r   rX  r   r   rY  r_   r   r   r   r  r  
empty_liker   r3   rh  r]  r^  r_  rg  r   r   limitrM  rj  rH  r   rY   re  r   r4  n_steps_rV   r   r   rQ  r   r   )r   r2   r  r4   r1   rf   rg   r   r5   validation_indicesX_validsample_weight_validr8  init_idxcluster_centersr  r   init_centersrJ   r   ra  r   minibatch_indicesrc  rb  s                            rL   r   zMiniBatchKMeans.fit  s   8 :rz* %
 
 
 	##A&&&)$*;<<,]AQWMMM577 !	: y#D)) 	1t17SIIID''4000a!1222 $At444 *11!YPP&'+,>? dl++ 	' 	'H| PNhlNNT\NNNNOOO #22 /)/+ 3  O :#/	  JAw | TR(Q,RRRRRRSSS#w'='=.&mG,, xqw??? ! $  '(#=9,1AA'))//q6/JJ 	 	7^^  $0$8$8ItGW$X$X! !1)*"/0A"B# + $!-$($9$9$;$;'+'> L"o! ! ! 9s??+-6;3HQ2N+O+O((+,('2G //w	+?   E9	 	 	 	 	 	 	 	 	 	 	 	 	 	 	B !(#4:1=A27QUd.>$>)#KLLMM 	:*J%/	+ + +'DL$-- !-	9DMs   CL,,L03L0c                    t          | d          }t          | |dt          j        t          j        gdd|           }t          | dt          | j                            | _        t          |||j
                  }t          | dd	          | _        t          |d
          }|s|                     |           t                      | _        | j        }t#          |          r.t%          ||j
        d
d          }|                     ||           |                     ||j        d	                    |                     |||| j        | j        |          | _        t          j        | j        |j
                  | _        d	| _        t;                                          dd          5  t?          ||| j        | j        | j        | j        |                                  | j!        | j"        | j        
  
         ddd           n# 1 swxY w Y   | j#        r*tI          ||| j        | j                  \  | _%        | _&        | xj        dz  c_        | j        j        d	         | _'        | S )a  Update k means estimate on a single mini-batch X.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            Training instances to cluster. It must be noted that the data
            will be converted to C ordering, which will cause a memory copy
            if the given data is not C-contiguous.
            If a sparse matrix is passed, a copy will be made if it's not in
            CSR format.

        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 or a user provided array.

        Returns
        -------
        self : object
            Return updated estimator.
        r   r:   r   F)r;   r<   r   r   r   _random_stater=   ro  r   TrA   r   rl  r    r   r   )	r4   rJ   r   rF  r1   rG  rH  r   r   Nr   )(hasattrr   rD   rE   rF   getattrr   r1   rx  r   r<   ro  r   r   r   r   r   r   r   r   r   rG   r  rY  r   r   r3   rh  rg  r   rn  rM  rj  rH  r   rQ  r  r   r   r4  )r   r2   r  r4   has_centersr5   r   s          rL   partial_fitzMiniBatchKMeans.partial_fit  s   4 d$677:rz* %!/
 
 
 %/#5d6G#H#H
 
 -]AQWMMMj!44 $At444 	,''***9;;DO 9D'-- 5"4qwTMMM++At444!!!QWQZ000 %)$8$8 /!//+ %9 % %D! 8DO17CCCDL +,D''))//q6/JJ 	 	+- 1 L!/ $ 5 5 7 7#'#:/   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	*J%/	+ + +'DL$- 	#4:1=s   ,AHHHr=  r  )r   r  r  r  r   r   r   r   r   r   r!  r   r   r   re  rj  r   r   r|  r"  r#  s   @rL   rO  rO    s        E EN$

,$x!T&AAAB$+'x!T&III4PhxD@@@$G'xafEEEF$ $ $D    5 5 5 5 5 5 5 5@    >	
 	
 	
? ? ?B    \555Z Z Z 65Zx \555d d d 65d d d d drN   rO  r   )r|   Fr}   r    )r    T)Fr>  Fr    )Mr  r   abcr   r   numbersr   r   numpyrD   scipy.sparser  r[   baser   r	   r
   r   r   
exceptionsr   metrics.pairwiser   r   utilsr   r   utils._openmp_helpersr   utils._param_validationr   r   r   utils.extmathr   r   utils.parallelr   r   utils.sparsefuncsr   utils.sparsefuncs_fastr   utils.validationr   r   r   r   _k_means_commonr!   r"   r#   r$   _k_means_elkanr%   r&   r'   r(   _k_means_lloydr)   r*   _k_means_minibatchr+   r,   rM   rI   rx   boolr   r   r   r   r  r   r   rM  rO  r   rN   rL   <module>r     sT    
  # # # # # # # # " " " " " " " "                        , + + + + + H H H H H H H H 3 3 3 3 3 3 3 3 ? ? ? ? ? ? K K K K K K K K K K 4 4 4 4 4 4 4 4        3 2 2 2 2 2 4 4 4 4 4 4                                  P O O O O O O O Q Q Q Q Q Q Q Q O,x!T&AAAB&-($/'(#8HafEEEtL  #'
 
 
 g g g g
 
gV QUb b b bR$ $ $ O,&- 
 #(   	[? [? [? [? [?D b+ b+ b+ b+N "!V<<<
 @+ @+ @+ =<@+FC C C CN$#C#Cv$ $ $$ $  
` ` ` ` `#%5|]TW` ` `Fp p p p p[ p p pt v v v vrn	 n	 n	 n	 n	k n	 n	 n	 n	 n	rN   