code: def k_means(data, k, dist=np.mean):
      """
      k-means methods
      Args:
          data: 需要聚类的data
          k: 簇数(聚成几类)
          dist: 更新簇坐标的方法
      """
      data_number = data.shape[0]
      last_nearest = np.zeros((data_number,))
  
      # init k clusters
      clusters = data[np.random.choice(data_number, k, replace=False)]
      print(f"random cluster: \n {clusters}")
      # plot
      plot_clusters(data, None, clusters, "random clusters")
  
      step = 0
      while True:
          d = distances(data, clusters)
          current_nearest = np.argmin(d, axis=1)
  
          # plot
          plot_clusters(data, current_nearest, clusters, f"step {step}")
  
          if (last_nearest == current_nearest).all():
              break  # clusters won't change
          for cluster in range(k):
              # update clusters
              clusters[cluster] = dist(
                  data[current_nearest == cluster], axis=0
              )
          last_nearest = current_nearest
          step += 1
  
      return clusters
  
imports: import numpy
  from matplotlib import pyplot
label_desc: Use image node_id 3 for calling a global function with example usage: k_means(data, k, dist) and returns: clusters