due to the iterative nature of -means and random initialization of centroidskmeans may stick in local optimum and may not converge to global optimum that is why it is recommended to use different initializations of centroids implementation in python the following two examples of implementing -means clustering algorithm will help us in its better understandingexample it is simple example to understand how -means works in this examplewe are going to first generate dataset containing different blobs and after that will apply -means algorithm to see the result firstwe will start by importing the necessary packages%matplotlib inline import matplotlib pyplot as plt import seaborn as snssns set(import numpy as np from sklearn cluster import kmeans the following code will generate the dcontaining four blobsfrom sklearn datasets samples_generator import make_blobs xy_true make_blobs(n_samples= centers= cluster_std= random_state= nextthe following code will help us to visualize the datasetplt scatter( [: ] [: ] = )plt show(