#! /usr/bin/env python3 # def faithful_kmeans ( ): #*****************************************************************************80 # ## faithful_kmeans() does a simple clustering exercise using sklearn kmeans(). # # 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 print ( '' ) print ( 'faithful_kmeans():' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' Cluster Old Faithful data using scikit-learn kmeans().' ) # # Read the data. # data = np.loadtxt ( 'faithful_normalized.txt' ) # # Create x and y. # x = data[:,0] y = data[:,1] n = len ( x ) print ( '' ) print ( ' Number of data values is %d' % ( n ) ) # # Call kmeans() # k = 2 kmeans = KMeans ( n_clusters = k, n_init = 'auto' ) kmeans.fit ( data ) Z = kmeans.cluster_centers_ C = kmeans.labels_ E = kmeans.inertia_ n0 = np.sum ( C == 0 ) n1 = np.sum ( C == 1 ) print ( ' Kmeans cluster centers Z:' ) print ( Z ) print ( ' Cluster energy = ', E ) print ( ' Cluster size = ', n0 + n1, '=', n0, '+', n1 ) plt.clf ( ) plt.plot ( x[C==0], y[C==0], 'c.', markersize = 10 ) plt.plot ( x[C==1], y[C==1], 'm.', markersize = 10 ) plt.plot ( Z[0,0], Z[0,1], 'bo', markersize = 15 ) plt.plot ( Z[1,0], Z[1,1], 'ro', markersize = 15 ) plt.xlabel ( '<-- Duration -->', fontsize = 16 ) plt.ylabel ( '<-- Wait -->', fontsize = 16 ) plt.title ( 'Clusters using kmeans()', fontsize = 16 ) plt.grid ( True ) filename = 'faithful_kmeans.png' plt.savefig ( filename ) plt.show ( ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Terminate. # print ( '' ) print ( 'faithful_kmeans():' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): faithful_kmeans ( )