#! /usr/bin/env python3 # def blob_cluster_kmeans ( ): #*****************************************************************************80 # ## blob_cluster_kmeans() clusters blob data using kmeans. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 08 July 2023 # # Author: # # John Burkardt # from sklearn.cluster import KMeans from sklearn.datasets import make_blobs import matplotlib.pyplot as plt import platform import sklearn print ( "" ) print ( "blob_cluster_kmeans():" ) print ( ' python version: %s' % ( platform.python_version ( ) ) ) print ( ' scikit-learn version: %s' % ( sklearn.__version__ ) ) # # Generate sample data # n_samples = 4000 n_components = 4 X, y_true = make_blobs ( n_samples = n_samples, centers = n_components, cluster_std = 0.60, random_state = 0 ) X = X[:, ::-1] # # Now apply kmeans. # kmeans = KMeans ( init = 'k-means++', n_clusters = 4, random_state = 0, n_init = "auto" ) kmeans.fit ( X ) # # Display data and computed cluster centers. # plt.clf ( ) colors = [ '#4EACC5', '#FF9C34', '#4E9A06', 'm' ] for k, col in enumerate(colors): cluster_data = ( y_true == k ) plt.scatter ( X[cluster_data, 0], X[cluster_data, 1], c = col, marker = '.', s = 10 ) plt.scatter ( kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], c = 'b', s = 50 ) plt.title ( "K-Means++" ) plt.xticks([]) plt.yticks([]) plt.grid ( True ) filename = 'blob_cluster_kmeans.png' plt.savefig ( filename ) print ( ' Graphics saved as "' + filename + '"' ) plt.close() # # Terminate. # print ( '' ) print ( 'blob_cluster_kmeans()' ) print ( ' Normal end of execution.' ) return def timestamp ( ): #*****************************************************************************80 # ## timestamp() prints the date as a timestamp. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 21 August 2019 # # Author: # # John Burkardt # import time t = time.time ( ) print ( time.ctime ( t ) ) return if ( __name__ == '__main__' ): timestamp ( ) blob_cluster_kmeans ( ) timestamp ( )