#! /usr/bin/env python3 # def faithful_lloyd ( ): #*****************************************************************************80 # ## faithful_lloyd() applies a version of Lloyd's algorithm to data. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 27 September 2023 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np import platform print ( '' ) print ( 'faithful_lloyd():' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' Implement Lloyd algorithm to the Old Faithful data.' ) # # Read the data. # data = np.loadtxt ( 'faithful_normalized.txt' ) x = data[:,0] y = data[:,1] # # Display the data. # plt.clf ( ) 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_lloyd_data.png' plt.savefig ( filename ) plt.show ( ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Determine clusters using arbitrary centers. # Z = np.array ( [ [ 0.4, 0.6 ], [ 0.6, 0.3 ] ] ) for iteration in range ( 0, 4 ): d0 = ( x - Z[0,0] )**2 + ( y - Z[0,1] )**2 d1 = ( x - Z[1,0] )**2 + ( y - Z[1,1] )**2 c0 = np.where ( d0 < d1 ) c1 = np.where ( d1 < d0 ) n0 = len ( d0[c0] ) n1 = len ( d1[c1] ) e0 = sum ( d0[c0] ) e1 = sum ( d1[c1] ) print ( ' Step ', iteration ) print ( ' Cluster energy = ', e0 + e1, '=', e0, '+', e1 ) print ( ' Cluster sizes = ', n0 + n1, '=', n0, '+', n1 ) plt.clf ( ) plt.plot ( x[c0], y[c0], 'c.', markersize = 10 ) plt.plot ( x[c1], y[c1], '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 ) s = ( 'Clusters on iteration ' + str ( iteration ) ) plt.title ( s, fontsize = 16 ) plt.grid ( True ) filename = 'faithful_lloyd_iteration' + str ( iteration ) + '.png' plt.savefig ( filename ) plt.show ( ) # # Prepare for next step by updating cluster centers. # Z[0,0] = np.mean ( x[c0] ) Z[0,1] = np.mean ( y[c0] ) Z[1,0] = np.mean ( x[c1] ) Z[1,1] = np.mean ( y[c1] ) # # Terminate. # print ( '' ) print ( 'faithful_lloyd():' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): faithful_lloyd ( )