#! /usr/bin/env python3 # def faithful_kmeans2 ( ): #*****************************************************************************80 # ## faithful_kmeans2 does a simple clustering exercise. # # Discussion: # # Clustering data. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 19 September 2019 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np import platform from scipy.cluster.vq import kmeans2 print ( '' ) print ( 'faithful_kmeans2:' ) print ( ' Python version: %s' % ( platform.python_version ( ) ) ) print ( ' MATH1900 Selected Topics in Mathematics: Machine Learning' ) # # 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 kmeans2() # k = 2 c, label = kmeans2 ( data, k ) print ( ' Kmeans2 cluster centers C:' ) print ( c ) plt.plot ( x[label==0], y[label==0], 'c.', markersize = 10 ) plt.plot ( x[label==1], y[label==1], 'm.', markersize = 10 ) plt.plot ( c[0,0], c[0,1], 'bo', markersize = 15 ) plt.plot ( c[1,0], c[1,1], 'ro', markersize = 15 ) plt.xlabel ( '<-- Duration -->', fontsize = 16 ) plt.ylabel ( '<-- Wait -->', fontsize = 16 ) plt.title ( 'Clusters using kmeans2()', fontsize = 16 ) plt.grid ( True ) filename = 'faithful_kmeans2.png' plt.savefig ( filename ) plt.show ( ) plt.clf ( ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Terminate. # print ( '' ) print ( 'faithful_kmeans2:' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): faithful_kmeans2 ( )