#! /usr/bin/env python3 # def study_classify_logistic ( ): #*****************************************************************************80 # ## study_classify_logistic() applies logistic regression to student study data. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 17 June 2023 # # Author: # # John Burkardt # import matplotlib.pyplot as plt import numpy as np import platform import sklearn from sklearn import linear_model print ( '' ) print ( 'study_classify_logistic()' ) print ( ' python version: %s' % ( platform.python_version ( ) ) ) print ( ' scikit-learn version %s' % ( sklearn.__version__ ) ) print ( ' Use sklearn LogisticRegression() on the student study-time example.' ) # # Define the data. # xvec = np.array ( [ 0.50, 0.75, 1.00, 1.25, 1.50, 1.75, 1.75, 2.00, 2.25, 2.50, 2.75, 3.00, 3.25, 3.50, 4.00, 4.25, 4.50, 4.75, 5.00, 5.00 ] ) y = np.array ( [ 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 ] ) # # Logistic regression expects the features to be a double-dimensioned array. # x = np.reshape ( xvec, [ 20, 1 ] ) # # Define the model. # lr = linear_model.LogisticRegression ( ) lr.fit ( x, y ) a = np.ndarray.flatten ( lr.coef_ ) b = lr.intercept_ print ( '' ) print ( 'Linear model is y = a * x + b:' ) print ( ' a = ', a, ' b = ', b ) cutoff = - b / a print ( '' ) print ( " cutoff", cutoff ) print ( " score", lr.score ( x, y ) ) print ( " mean", np.mean ( y ) ) # # Plot the results. # plt.clf ( ) plt.scatter ( xvec, y ) x_eval = np.linspace ( 0.0, 6.0, 101 ) y_eval = logistic_fun ( a * x_eval + b ) plt.plot ( x_eval, y_eval ) plt.axvline ( x = cutoff, linestyle = '--', color = 'red' ) plt.title ( 'study logistic regression example' ) plt.grid ( True ) filename = 'study_classify_logistic.png' plt.savefig ( filename ) print ( '' ) print ( ' Graphics saved as "%s"' % ( filename ) ) plt.show ( block = False ) # # Terminate. # print ( '' ) print ( 'study_classify_logistic()' ) print ( ' Normal end of execution.' ) return def logistic_fun ( x ): #*****************************************************************************80 # ## logistic_fun() evaluates the logistic function. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 08 January 2020 # # Author: # # John Burkardt # # Input: # # real x, the arguments. # # Output: # # real value, the logistic function evaluated at x. # import numpy as np value = 1.0 / ( 1.0 + np.exp ( - x ) ); return value def timestamp ( ): #*****************************************************************************80 # ## timestamp() prints the date as a timestamp. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 21 August 2019 # # Author: # # John Burkardt # import time t = time.time ( ) print ( time.ctime ( t ) ) return if ( __name__ == '__main__' ): timestamp ( ) study_classify_logistic ( ) timestamp ( )