#!/usr/bin/env python # coding: utf-8 # # No Shows By Chase Kregor # # ## Notebook Bookmarks: # # ### - Go to The Top of The Notebook # ### - Go to Clean and EDA # ### - Go to Feature Selection and Creation # ### - Go to Train Models # In[64]: import pandas as pd import numpy as np import matplotlib.pyplot as plt #import matplotlib.style as style #style.use('fivethirtyeight') import seaborn as sb # ## Start of Clean and EDA # In[65]: data = pd.read_csv("../data/KaggleV2-May-2016.csv") data.head() # In[66]: data.rename(columns = {'Hipertension':'Hypertension', 'PatientId': 'PatientID', 'Handcap': 'Handicap', 'No-show': 'NoShow', 'Alcoholism':'Alcoholism' }, inplace = True) data.head() # Now trying to understand the data set. It's distributions and unique values. Also attempting to find funky and incorrect data points. I want to understand and check the integrity of the dataset # In[67]: data.PatientID.value_counts() # making sure there arent duplicate appointment IDs # In[68]: data.AppointmentID.value_counts() # In[69]: data.Gender.unique() # In[70]: data.Gender.value_counts() # trying to understand my timeline # In[71]: data.AppointmentDay.unique() # In[72]: data.Age.value_counts() # need to get rid of negative value. It is impossible for someone to be -1. # # In[73]: data['Age'][data['Age'] < 0] = 1 # In[74]: data.Age.value_counts() # In[75]: data.Scholarship.value_counts() # In[76]: data.Hypertension.value_counts() # In[77]: data.Diabetes.value_counts() # In[78]: data.Handicap.value_counts() # In[79]: data.SMS_received.value_counts() # In[80]: data.NoShow.value_counts() # making sure there aren't any values missing in the dataset # In[81]: data.isnull().sum() # In[82]: print('Age:',sorted(data.Age.unique())) print('Gender:',data.Gender.unique()) #print('DayOfTheWeek:',data.DayOfTheWeek.unique()) #print('Status:',data.Status.unique()) print('Diabetes:',data.Diabetes.unique()) print('Alchoholism:',data.Alcoholism.unique()) print('Hypertension:',data.Hypertension.unique()) print('Handicap:',data.Handicap.unique()) #print('Smokes:',data.Smokes.unique()) print('Scholarship:',data.Scholarship.unique()) #print('Tuberculosis:',data.Tuberculosis.unique()) print('SMS_received:',data.SMS_received.unique()) #print('AwaitingTime:',sorted(data.AwaitingTime.unique())) #print('HourOfTheDay:', sorted(data.HourOfTheDay.unique())) # In[83]: data.head() # ## Feature Selection and Creation # In[84]: data.drop(data.columns[[0]], axis=1) data.head() # Creating two binary columns for the gender # In[85]: data['Male'] = data['Gender'].replace(['F','M'], [0,1]) data['Female'] = data['Gender'].replace(['F','M'], [1,0]) data.head() # changing NoShow column to be binary # In[86]: data['NoShow'] = data['NoShow'].replace(['Yes','No'], [1,0]) data.head() # dropping uneeded columns # In[87]: data = data[['PatientID','ScheduledDay','AppointmentDay', 'Age','Neighbourhood', 'Scholarship','Hypertension','Diabetes','Alcoholism','Handicap','SMS_received','NoShow','Male','Female']] data.head() # cleaning up dates # In[88]: data['ScheduledDay'] = pd.to_datetime(data['ScheduledDay']) data['AppointmentDay'] = pd.to_datetime(data['AppointmentDay']) data.head() # In[89]: #original features that I was using, got rid of. """ data['ScheduledYear'], data['ScheduledMonth'], data['ScheduleDay'] = data['ScheduledDay'].dt.year, data['ScheduledDay'].dt.month, data['ScheduledDay'].dt.day data['AppointmentYear'], data['AppointmentMonth'], data['AppointmentDayy'] = data['AppointmentDay'].dt.year, data['AppointmentDay'].dt.month, data['AppointmentDay'].dt.day data.head """ # Probably have to get rid of Neighbourhood column given we don't have the specefic hospital for all these NoShows. If we did we could have used distance from hospital as a feature. # Creating a feature that calculates the wait time of a particular patient from when they schedule the appointment to when they actually have the appointment. I believe this will be a really great feature to have. One would assume that the longer the wait time the more likely people are to no show for their appointments # ## Creating Waiting Time # In[90]: data.ScheduledDay = pd.DatetimeIndex(data.ScheduledDay).normalize() data['WaitingTime'] = data['AppointmentDay'] - data['ScheduledDay'] data.head() # In[91]: data['WaitingTime'] = data['WaitingTime'].apply(lambda x: x.days) data.head(20) # In[92]: data['WaitingTime'].mean() # Need to make one last clean dataset picking which features I will actually use in the model. # In[93]: data = data[['NoShow','ScheduledDay','AppointmentDay','Age','Scholarship','Hypertension','Diabetes','Alcoholism','Handicap','SMS_received','Male','Female','WaitingTime']] data.head() # ## Train Models # Here is probably the most interesting and complex part to this analysis. # # I will run a bunch of different models to see what their various testing/training accuracies are in order to pick the best one and then try and optomize that particular model. # In[94]: data.head() # In[95]: #the features we are going to train our model on showfeatures = data.iloc[:,3:19] showfeatures.head() # ## Splitting # In[96]: from sklearn.cross_validation import train_test_split, cross_val_score from sklearn.metrics import accuracy_score # In[97]: # TRAIN/TEST PARTITION #create the feature vectors and class labels features = np.array(showfeatures) labels = np.array(data['NoShow']) features # In[98]: data['NoShow'].value_counts() # In[99]: #split the data into training and testing sets(67% training, 33% into testing) training_features, testing_features, training_labels, testing_labels = train_test_split(features,labels, test_size = 0.2,random_state = 42 ) # ## Logistic regression # In[100]: from sklearn import linear_model lg = linear_model.LogisticRegression() lg.fit(training_features,training_labels) # In[101]: # hold out cross validation #print(accuracy_score(testing_labels, predictions)) score = cross_val_score(lg, training_features,training_labels, cv = 10, scoring= 'accuracy') print(score) predictions = lg.predict(testing_features) print(predictions) score = accuracy_score(testing_labels, predictions) print(score) # ## Multi Layer Perceptron just for fun, takes forever to run # In[102]: """from sklearn.neural_network import MLPClassifier mlp = MLPClassifier(alpha=0.01, hidden_layer_sizes = (100,100)) mlp.fit(training_features,training_labels)""" # In[103]: """# hold out cross validation #print(accuracy_score(testing_labels, predictions)) score = cross_val_score(mlp, training_features,training_labels, cv = 10, scoring= 'accuracy') print(score) predictions = mlp.predict(testing_features) print(predictions) score = accuracy_score(testing_labels, predictions) print(score)""" # ## Random Forrest # In[104]: from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(max_depth=2,n_estimators=100) rf.fit(training_features,training_labels) # In[105]: # hold out cross validation #print(accuracy_score(testing_labels, predictions)) score = cross_val_score(rf, training_features,training_labels, cv = 10, scoring= 'accuracy') print(score) predictions = rf.predict(testing_features) print(predictions) score = accuracy_score(testing_labels, predictions) print(score) # ## KNeighbors # In[106]: from sklearn.neighbors import KNeighborsClassifier # In[107]: #TRAIN/TEST ALGORITHM #instance the model kList = range(1,50) cv_scores = [] neighbors = filter(lambda x: x % 2 != 0, kList) # In[108]: for i in neighbors: print(i) knn = KNeighborsClassifier(n_neighbors=i) knn.fit(training_features,training_labels) #test the model predictions = knn.predict(testing_features) # hold out cross validation #print(accuracy_score(testing_labels, predictions)) scores = cross_val_score(knn, training_features,training_labels, cv = 10, scoring= 'accuracy') #print(scores) cv_scores.append(scores.mean()) print("done finding") # In[109]: optimalk = cv_scores.index(max(cv_scores)) # In[110]: knn = KNeighborsClassifier(n_neighbors=optimalk) knn.fit(training_features,training_labels) # In[111]: predictions = knn.predict(testing_features) #data['predictions'] = knn.predict(testing_features) score = accuracy_score(testing_labels, predictions) print(score) # ## Predict Whether a Patient Will Show Up: User Input # In[112]: data.head() # In[113]: age = 0.0 scholarship = 0.0 hypertension = 0.0 diabetes = 0.0 alcoholism = 0.0 handicap = 0.0 sms = 0.0 male = 0.0 female = 0.0 waitingtime = 0 inputage = int(input("Enter the patient's age: "+ "\n" )) inputscholarship = input("Is the patient on Scholarship(Yes or No): "+ "\n" ) inputhypertension = input("Does the patient have Hypertension?(Yes or No): "+ "\n" ) inputdiabetes = input("Is the patient Diabetic?(Yes or No): "+ "\n" ) inputalcoholism = input("Is the patient an Alcoholic?(Yes or No): "+ "\n" ) inputhandicap = int(input("How many Handicaps does the patient have?: "+ "\n" )) inputsms = input("Will the patient recieve a text message?(Yes or No): "+ "\n" ) inputgender = input("What is the patient gender?(Male or Female): "+ "\n") inputwaitingtime = int(input("How many days away is the appointment?: "+ "\n")) age = inputage handicap = inputhandicap waitingtime = inputwaitingtime if inputscholarship == "Yes" or "yes": scholarship = 1.0 elif inputscholarship == "No" or "no": scholarship = 0 if hypertension == "Yes" or "yes": hypertension = 1.0 elif hypertension == "No" or "no": hypertension = 0 if inputdiabetes == "Yes" or "yes": diabetes = 1.0 elif inputdiabetes == "No" or "no": daibetes = 0 if inputalcoholism == "Yes" or "yes": alcoholism = 1.0 elif inputalcoholism == "No" or "no": alcoholism = 0 if inputsms == "Yes" or "yes": sms = 1.0 elif inputsms == "No" or "no": sms = 0 if inputgender == "Male" or "M": male = 1.0 elif inputgender == "Female" or "F": female = 1.0 else: print("incorrect gender input") answer = [age,scholarship,hypertension,diabetes,alcoholism,handicap,sms,male,female,waitingtime] #the commented out chunk was for testing to not have to type everything in everytime I wanted to test """ print(" ") print("Fixed answer: ") fixedanswer = [5, 1.0, 1.0 ,1.0, 1.0, 4, 0.0, 1.0, 1.0,10] print(fixedanswer) print(rf.predict([fixedanswer])) print(lg.predict([fixedanswer])) print(knn.predict([fixedanswer])) """ print(" ") print("user answer: ") print(answer) print(rf.predict([answer])) print(lg.predict([answer])) print(knn.predict([answer])) # # Esemble Model # In[114]: print("Here we will use an ensemble of our three different models to vote whether this patient will show up or not.") print("Let's see how our individual models voted.") noshowcounter = 0.0 showcounter = 0.0 randomresult = (rf.predict([answer])) logresult = (lg.predict([answer])) knnresult = (knn.predict([answer])) print("") print("random forrest:") print(randomresult[0]) if randomresult[0] == 1: noshowcounter+=1 print("no show") else: showcounter+=1 print("show") print("") print("logistic regression:") print(logresult[0]) if logresult[0] == 1: noshowcounter+=1 print("no show") else: showcounter+=1 print("show") print("") print("knn:") print(knnresult[0]) if knnresult[0] == 1: noshowcounter+=1 print("no show") else: showcounter+=1 print("show") print("") print("The final vote is %f no shows to %d shows" %(noshowcounter,showcounter)) # ### Analysis of Ensemble Model: # What you can see here is that there needs to be more descrepencies or more features because an esenmble doesn't really help here because they all vote the same # # Result # In[115]: if noshowcounter >= 2: print("Our Esemble Model predicts the patient is not going to show up for their appointment.") print("Be advised, intervention may be neccesary or suggested in order for the patient to show up ") else: print("Our Model Predicts that this patient will show up to their appointment, intervention is not needed") # In[116]: rfpredictions = rf.predict(testing_features) lgpredictions = lg.predict(testing_features) knnpredictions = knn.predict(testing_features) print(rfpredictions) print(lgpredictions) print(knnpredictions) print("") lengthoflists = (len(rfpredictions)) ensemblepredictions = [] ensemblescore = 0 for i in range(len(rfpredictions)): if rfpredictions[i] == 1: ensemblescore+=1 if lgpredictions[i] == 1: ensemblescore+=1 if knnpredictions[i] == 1: ensemblescore+=1 if ensemblescore >= 2: ensemblescore = 1 else: ensemblescore = 0 ensemblepredictions.append(ensemblescore) print("") print("done with for loop") # In[117]: print("") #uncomment if you want to see my ensemble predicting basically all zeros. #print(ensemblepredictions) ensemblescore = accuracy_score(testing_labels, ensemblepredictions) print(ensemblescore) # ## Confusion Matrix # In[118]: from sklearn.metrics import confusion_matrix confusion_matrix(testing_labels, ensemblepredictions) # ## Error Analysis: # I was a bit confused what was going on here and why all of the predictions were zeros but what we learned is that just because you have these features doesn't neccesarily mean you can convert them into a yes or no no show. Rather indiviudal classifiers and ensemble model learned if you just say people are always going to show up you will get an 80% accuracy # # That being said, you can still predict the probability at which individuals may or may not show up using predicta proba on logistic regression # ### Predicting the probability of an individual patient not showing up # ## Patient #1: 5 year old female with a lot of medical "problems" # In[119]: age = 0.0 scholarship = 0.0 hypertension = 0.0 diabetes = 0.0 alcoholism = 0.0 handicap = 0.0 sms = 0.0 male = 0.0 female = 0.0 waitingtime = 0 inputage = int(input("Enter the patient's age: "+ "\n" )) inputscholarship = input("Is the patient on Scholarship(Yes or No): "+ "\n" ) inputhypertension = input("Does the patient have Hypertension?(Yes or No): "+ "\n" ) inputdiabetes = input("Is the patient Diabetic?(Yes or No): "+ "\n" ) inputalcoholism = input("Is the patient an Alcoholic?(Yes or No): "+ "\n" ) inputhandicap = int(input("How many Handicaps does the patient have?: "+ "\n" )) inputsms = input("Will the patient recieve a text message?(Yes or No): "+ "\n" ) inputgender = input("What is the patient gender?(Male or Female): "+ "\n") inputwaitingtime = int(input("How many days away is the appointment?: "+ "\n")) age = inputage handicap = inputhandicap waitingtime = inputwaitingtime if inputscholarship == "Yes" or "yes": scholarship = 1.0 elif inputscholarship == "No" or "no": scholarship = 0 if hypertension == "Yes" or "yes": hypertension = 1.0 elif hypertension == "No" or "no": hypertension = 0 if inputdiabetes == "Yes" or "yes": diabetes = 1.0 elif inputdiabetes == "No" or "no": daibetes = 0 if inputalcoholism == "Yes" or "yes": alcoholism = 1.0 elif inputalcoholism == "No" or "no": alcoholism = 0 if inputsms == "Yes" or "yes": sms = 1.0 elif inputsms == "No" or "no": sms = 0 if inputgender == "Male" or "M": male = 1.0 elif inputgender == "Female" or "F": female = 1.0 else: print("incorrect gender input") answer = [age,scholarship,hypertension,diabetes,alcoholism,handicap,sms,male,female,waitingtime] #the commented out chunk was for testing to not have to type everything in everytime I wanted to test print(" ") """ print("Fixed answer: ") fixedanswer = [100, 1.0, 1.0 ,1.0, 1.0, 5, 0.0, 1.0, 1.0,10] print(fixedanswer) #print(rf.predict([fixedanswer])) #print(lg.predict([fixedanswer])) #print(knn.predict([fixedanswer])) """ print(" ") print("user answer: ") print(answer) # In[120]: probabilityresult = lg.predict_proba([answer]) showupproba = probabilityresult[0] showupproba = showupproba[0] noshowproba = probabilityresult[0] noshowproba = noshowproba[1] print("There is a %f percent chance patient #1 does show up and a %f percent chance this person doesn't show up" % (showupproba,noshowproba)) # ## Patient #2: 100 year old female with the same lot of medical "problems" # In[121]: age = 0.0 scholarship = 0.0 hypertension = 0.0 diabetes = 0.0 alcoholism = 0.0 handicap = 0.0 sms = 0.0 male = 0.0 female = 0.0 waitingtime = 0 inputage = int(input("Enter the patient's age: "+ "\n" )) inputscholarship = input("Is the patient on Scholarship(Yes or No): "+ "\n" ) inputhypertension = input("Does the patient have Hypertension?(Yes or No): "+ "\n" ) inputdiabetes = input("Is the patient Diabetic?(Yes or No): "+ "\n" ) inputalcoholism = input("Is the patient an Alcoholic?(Yes or No): "+ "\n" ) inputhandicap = int(input("How many Handicaps does the patient have?: "+ "\n" )) inputsms = input("Will the patient recieve a text message?(Yes or No): "+ "\n" ) inputgender = input("What is the patient gender?(Male or Female): "+ "\n") inputwaitingtime = int(input("How many days away is the appointment?: "+ "\n")) age = inputage handicap = inputhandicap waitingtime = inputwaitingtime if inputscholarship == "Yes" or "yes": scholarship = 1.0 elif inputscholarship == "No" or "no": scholarship = 0 if hypertension == "Yes" or "yes": hypertension = 1.0 elif hypertension == "No" or "no": hypertension = 0 if inputdiabetes == "Yes" or "yes": diabetes = 1.0 elif inputdiabetes == "No" or "no": daibetes = 0 if inputalcoholism == "Yes" or "yes": alcoholism = 1.0 elif inputalcoholism == "No" or "no": alcoholism = 0 if inputsms == "Yes" or "yes": sms = 1.0 elif inputsms == "No" or "no": sms = 0 if inputgender == "Male" or "M": male = 1.0 elif inputgender == "Female" or "F": female = 1.0 else: print("incorrect gender input") answer = [age,scholarship,hypertension,diabetes,alcoholism,handicap,sms,male,female,waitingtime] #the commented out chunk was for testing to not have to type everything in everytime I wanted to test print(" ") """ print("Fixed answer: ") fixedanswer = [100, 1.0, 1.0 ,1.0, 1.0, 5, 0.0, 1.0, 1.0,10] print(fixedanswer) #print(rf.predict([fixedanswer])) #print(lg.predict([fixedanswer])) #print(knn.predict([fixedanswer])) """ print(" ") print("user answer: ") print(answer) # In[122]: probabilityresult = lg.predict_proba([answer]) showupproba = probabilityresult[0] showupproba = showupproba[0] noshowproba = probabilityresult[0] noshowproba = noshowproba[1] print("There is a %f percent chance patient #1 does show up and a %f percent chance this person doesn't show up" % (showupproba,noshowproba)) # ## Analysis of different patients # # Age seems to be a big huge factor which makes sense because children aren't able to get to appointments themselves. Also if a child is 5 and is an alcholic i'm pretty sure that would mean they would have an alcholic and unrealiable parents which would make sense that they would have a way less likelyhood to show up than a 100 year old with the same features. # # While a 16% difference in showing up or not may not be the most instiutive or knowledgable thing in the world we can "empirically" say these people are more or less likely to show up than one another. # # side note I tried different training testing partitions(10/90 and 70/30) and that didn't really have any affect on my accuracy levels.