code: def k_means(
      X,
      n_clusters,
      *,
      sample_weight=None,
      init="k-means++",
      n_init="warn",
      max_iter=300,
      verbose=False,
      tol=1e-4,
      random_state=None,
      copy_x=True,
      algorithm="lloyd",
      return_n_iter=False,
  ):
      """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=10
          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` will change from 10 to `'auto'` in version 1.4.
  
      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", "auto", "full"}, 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)`.
  
          `"auto"` and `"full"` are deprecated and they will be removed in
          Scikit-Learn 1.3. They are both aliases for `"lloyd"`.
  
          .. 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.
      """
      est = KMeans(
          n_clusters=n_clusters,
          init=init,
          n_init=n_init,
          max_iter=max_iter,
          verbose=verbose,
          tol=tol,
          random_state=random_state,
          copy_x=copy_x,
          algorithm=algorithm,
      ).fit(X, sample_weight=sample_weight)
      if return_n_iter:
          return (
              est.cluster_centers_,
              est.labels_,
              est.inertia_,
              est.n_iter_,
          )
      else:
          return est.cluster_centers_, est.labels_, est.inertia_
  
imports: import warnings
  from abc import ABC, abstractmethod
  from numbers import Integral, Real
  import numpy
  import scipy.sparse
  from ..base import BaseEstimator, ClassNamePrefixFeaturesOutMixin, ClusterMixin, TransformerMixin, _fit_context
  from ..exceptions import ConvergenceWarning
  from ..metrics.pairwise import _euclidean_distances, euclidean_distances
  from ..utils import check_array, check_random_state
  from ..utils._openmp_helpers import _openmp_effective_n_threads
  from ..utils._param_validation import Hidden, Interval, StrOptions, validate_params
  from ..utils.extmath import row_norms, stable_cumsum
  from ..utils.fixes import threadpool_info, threadpool_limits
  from ..utils.sparsefuncs import mean_variance_axis
  from ..utils.sparsefuncs_fast import assign_rows_csr
  from ..utils.validation import _check_sample_weight, _is_arraylike_not_scalar, check_is_fitted
  from ._k_means_common import CHUNK_SIZE, _inertia_dense, _inertia_sparse, _is_same_clustering
  from ._k_means_elkan import elkan_iter_chunked_dense, elkan_iter_chunked_sparse, init_bounds_dense, init_bounds_sparse
  from ._k_means_lloyd import lloyd_iter_chunked_dense, lloyd_iter_chunked_sparse
  from ._k_means_minibatch import _minibatch_update_dense, _minibatch_update_sparse
label_desc: Use image node_id 4 for calling a global function with example usage: k_means(X, n_clusters) and returns: est,  est,  est,  est, est,  est,  est