#! /usr/bin/env python3 # def comfort ( ): #*****************************************************************************80 # ## comfort does an exercise in logistic regression. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 11 October 2019 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np from logistic_regression import logistic_regression print ( '' ) print ( 'comfort:' ) print ( ' Seek parameters for logistic regression example.' ) print ( ' We have M examples of N-dimensional data X.' ) print ( ' For a model' ) print ( ' h(x) = 1 / ( 1 + exp ( - ( w(0) + w(1)*h + w(2)*t ) ) )' ) print ( ' determine the weights w.' ) print ( '' ) print ( ' Use gradient descent' ) # # Read the data file. # data = np.loadtxt ( 'comfort_data.txt' ) # # First two columns are humidity and temperature. # Third column is Y (comfortable = 1, no = 0). # h = data[:,0] t = data[:,1] y = data[:,2] m = len ( h ) # # Normalize the X data. # h = ( h - np.min ( h ) ) / ( np.max ( h ) - np.min ( h ) ) t = ( t - np.min ( t ) ) / ( np.max ( t ) - np.min ( t ) ) # # Create a data array x = [ 1 | h | t ]. # x = np.zeros ( [ m, 3 ] ) x[:,0] = 1 x[:,1] = h x[:,2] = t # # Request logistic regression weights. # alpha = 1.0 kmax = 10000 w = logistic_regression ( x, y, alpha, kmax ) print ( '' ) print ( ' Estimated weights W = (%g,%g,%g)' % ( w[0], w[1], w[2] ) ) # # Display the data. # plt.plot ( x[y==0,1], x[y==0,2], 'r.', markersize = 15 ) plt.plot ( x[y==1,1], x[y==1,2], 'b.', markersize = 15 ) plt.xlabel ( '<-- Humidity -->' ) plt.ylabel ( '<-- Temperature -->' ) plt.title ( 'Blue = Comfortable, Red = Not' ) plt.plot ( [-w[0]/w[1], (-w[0]-w[2])/w[1]], [0,1], 'k-', linewidth = 3 ) plt.grid ( True ) filename = 'comfort.png' plt.savefig ( filename ) plt.show ( ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) # # Terminate. # print ( '' ) print ( 'comfort:' ) print ( ' Normal end of execution.' ) return if ( __name__ == '__main__' ): comfort ( )