#! /usr/bin/env python3 # def faithful_energy ( ): #*****************************************************************************80 # ## faithful_energy() monitors cluster energy as K increases. # # Discussion: # # Clustering data. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 26 September 2023 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np import platform from sklearn.cluster import KMeans print ( '' ) print ( 'faithful_energy():' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' Evaluate cluster energy with increasing K, for Old Faithful data' ) # # Read the data. # data = np.loadtxt ( 'faithful_data.txt' ) # # Create x and y. # x = data[:,0] y = data[:,1] n = len ( x ) print ( '' ) print ( ' Number of data values is %d' % ( n ) ) # # Normalize the data. # xmin = np.min ( x ) xmax = np.max ( x ) ymin = np.min ( y ) ymax = np.max ( y ) data[:,0] = ( data[:,0] - xmin ) / ( xmax - xmin ) data[:,1] = ( data[:,1] - ymin ) / ( ymax - ymin ) x = data[:,0] y = data[:,1] plt.plot ( x, y, 'k.', markersize = 10 ) plt.xlabel ( '<-- Duration (normalized) -->', fontsize = 16 ) plt.ylabel ( '<-- Wait (normalized) -->', fontsize = 16 ) plt.title ( 'Old Faithful eruption durations and waits', fontsize = 16 ) plt.grid ( True ) plt.axis ( 'equal' ) filename = 'faithful_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, Faithful data', fontsize = 16 ) plt.grid ( True ) filename = 'faithful_energy.png' plt.savefig ( filename ) plt.show ( ) plt.clf ( ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Terminate. # print ( '' ) print ( 'faithful_energy():' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): faithful_energy ( )