#! /usr/bin/env python3 # def blobs_energy ( ): #*****************************************************************************80 # ## blobs_energy() monitors cluster energy as K increases. # # Discussion: # # Clustering data. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 26 September 2023 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np import platform from sklearn.cluster import KMeans from sklearn.datasets import make_blobs print ( '' ) print ( 'blobs_energy():' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' Evaluate cluster energy for increasing K on 6 blobs data.' ) # # Read the data. # Z = np.array ( [ [-7,-5], [-3,-1], [8,-2], [-4,8], [0,4], [6,3] ] ) data, labels = make_blobs ( n_samples = 500, n_features = 2, centers = Z, random_state = 42 ) # # Create x and y. # x = data[:,0] y = data[:,1] n = len ( x ) print ( '' ) print ( ' Number of data values is %d' % ( n ) ) plt.plot ( x, y, 'k.', markersize = 10 ) plt.xlabel ( '<-- X -->', fontsize = 16 ) plt.ylabel ( '<-- Y -->', fontsize = 16 ) plt.title ( 'Six blobs', fontsize = 16 ) plt.grid ( True ) plt.axis ( 'equal' ) filename = 'blobs_data.png' plt.savefig ( filename ) plt.show ( ) plt.clf ( ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Call kmeans() # kmax = 10 kplot = list ( range ( 1, kmax + 1 ) ) eplot = np.zeros ( kmax ) for i in range ( 0, kmax ): k = kplot[i] kmeans = KMeans ( n_clusters = k, n_init = 'auto' ) kmeans.fit ( data ) eplot[i] = kmeans.inertia_ plt.clf ( ) plt.plot ( kplot, eplot, 'r-o', linewidth = 3 ) plt.xlabel ( '<-- K -->', fontsize = 16 ) plt.ylabel ( '<-- Energy(K) -->', fontsize = 16 ) plt.title ( 'Cluster energy with increasing K, blobs data', fontsize = 16 ) plt.grid ( True ) filename = 'blobs_energy.png' plt.savefig ( filename ) plt.show ( ) plt.clf ( ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Terminate. # print ( '' ) print ( 'blobs_energy():' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): blobs_energy ( )