-
Notifications
You must be signed in to change notification settings - Fork 0
/
Telecom+Churn+-+Logistic+++DT+++RF.py
1479 lines (685 loc) · 26 KB
/
Telecom+Churn+-+Logistic+++DT+++RF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# ## Telecom Churn Case Study
# With 21 predictor variables we need to predict whether a particular customer will switch to another telecom provider or not. In telecom terminology, this is referred to as churning and not churning, respectively.
# ### Step 1: Importing and Merging Data
# In[168]:
# Suppressing Warnings
import warnings
warnings.filterwarnings('ignore')
# In[169]:
# Importing Pandas and NumPy
import pandas as pd, numpy as np
# In[170]:
# Importing all datasets
churn_data = pd.read_csv("/Users/aishwaryathorat/Movies/MS Courses/Upg/DT/Tree models instead of Logistic Regression/churn_data.csv")
churn_data.head()
# In[171]:
customer_data = pd.read_csv("/Users/aishwaryathorat/Movies/MS Courses/Upg/DT/Tree models instead of Logistic Regression/customer_data.csv")
customer_data.head()
# In[172]:
internet_data = pd.read_csv("/Users/aishwaryathorat/Movies/MS Courses/Upg/DT/Tree models instead of Logistic Regression/internet_data.csv")
internet_data.head()
# #### Combining all data files into one consolidated dataframe
# In[173]:
# Merging on 'customerID'
df_1 = pd.merge(churn_data, customer_data, how='inner', on='customerID')
# In[174]:
# Final dataframe with all predictor variables
telecom = pd.merge(df_1, internet_data, how='inner', on='customerID')
# ### Step 2: Inspecting the Dataframe
# In[175]:
# Let's see the head of our master dataset
telecom.head()
# In[176]:
# Let's check the dimensions of the dataframe
telecom.shape
# In[177]:
# statistical aspects of the dataframe
telecom.describe()
# In[178]:
telecom.info()
# ### Step 3: Data Preparation
# #### Converting some binary variables (Yes/No) to 0/1
# In[179]:
# List of variables to map
varlist = ['PhoneService', 'PaperlessBilling', 'Churn', 'Partner', 'Dependents']
# Defining the map function
def binary_map(x):
return x.map({'Yes': 1, "No": 0})
# Applying the function to the housing list
telecom[varlist] = telecom[varlist].apply(binary_map)
# In[180]:
telecom.head()
# #### For categorical variables with multiple levels, create dummy features (one-hot encoded)
# In[181]:
# Creating a dummy variable for some of the categorical variables and dropping the first one.
dummy1 = pd.get_dummies(telecom[['Contract', 'PaymentMethod', 'gender', 'InternetService']], drop_first=True)
# Adding the results to the master dataframe
telecom = pd.concat([telecom, dummy1], axis=1)
# In[182]:
telecom.head()
# In[183]:
# Creating dummy variables for the remaining categorical variables and dropping the level with big names.
# Creating dummy variables for the variable 'MultipleLines'
ml = pd.get_dummies(telecom['MultipleLines'], prefix='MultipleLines')
# Dropping MultipleLines_No phone service column
ml1 = ml.drop(['MultipleLines_No phone service'], axis=1)
#Adding the results to the master dataframe
telecom = pd.concat([telecom,ml1], axis=1)
# Creating dummy variables for the variable 'OnlineSecurity'.
os = pd.get_dummies(telecom['OnlineSecurity'], prefix='OnlineSecurity')
os1 = os.drop(['OnlineSecurity_No internet service'], axis=1)
# Adding the results to the master dataframe
telecom = pd.concat([telecom,os1], axis=1)
# Creating dummy variables for the variable 'OnlineBackup'.
ob = pd.get_dummies(telecom['OnlineBackup'], prefix='OnlineBackup')
ob1 = ob.drop(['OnlineBackup_No internet service'], axis=1)
# Adding the results to the master dataframe
telecom = pd.concat([telecom,ob1], axis=1)
# Creating dummy variables for the variable 'DeviceProtection'.
dp = pd.get_dummies(telecom['DeviceProtection'], prefix='DeviceProtection')
dp1 = dp.drop(['DeviceProtection_No internet service'], axis=1)
# Adding the results to the master dataframe
telecom = pd.concat([telecom,dp1], axis=1)
# Creating dummy variables for the variable 'TechSupport'.
ts = pd.get_dummies(telecom['TechSupport'], prefix='TechSupport')
ts1 = ts.drop(['TechSupport_No internet service'], axis=1)
# Adding the results to the master dataframe
telecom = pd.concat([telecom,ts1], axis=1)
# Creating dummy variables for the variable 'StreamingTV'.
st =pd.get_dummies(telecom['StreamingTV'], prefix='StreamingTV')
st1 = st.drop(['StreamingTV_No internet service'], axis=1)
# Adding the results to the master dataframe
telecom = pd.concat([telecom,st1], axis=1)
# Creating dummy variables for the variable 'StreamingMovies'.
sm = pd.get_dummies(telecom['StreamingMovies'], prefix='StreamingMovies')
sm1 = sm.drop(['StreamingMovies_No internet service'], axis=1)
# Adding the results to the master dataframe
telecom = pd.concat([telecom,sm1], axis=1)
# In[184]:
telecom.head()
# #### Dropping the repeated variables
# In[185]:
# We have created dummies for the below variables, so we can drop them
telecom = telecom.drop(['Contract','PaymentMethod','gender','MultipleLines','InternetService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection',
'TechSupport', 'StreamingTV', 'StreamingMovies'], axis=1)
# In[186]:
telecom = telecom[~(telecom.TotalCharges == " ")]
# In[187]:
telecom.TotalCharges = telecom.TotalCharges.astype(float, errors="ignore")
# In[188]:
# #The varaible was imported as a string we need to convert it to float
# telecom['TotalCharges'] = telecom['TotalCharges'].convert_objects(convert_numeric=True)
# In[189]:
telecom.info()
# Now you can see that you have all variables as numeric.
# #### Checking for Outliers
# In[190]:
# Checking for outliers in the continuous variables
num_telecom = telecom[['tenure','MonthlyCharges','SeniorCitizen','TotalCharges']]
# In[191]:
# Checking outliers at 25%, 50%, 75%, 90%, 95% and 99%
num_telecom.describe(percentiles=[.25, .5, .75, .90, .95, .99])
# From the distribution shown above, you can see that there no outliers in your data. The numbers are gradually increasing.
# #### Checking for Missing Values and Inputing Them
# In[192]:
# Adding up the missing values (column-wise)
telecom.isnull().sum()
# It means that 11/7043 = 0.001561834 i.e 0.1%, best is to remove these observations from the analysis
# In[193]:
# Checking the percentage of missing values
round(100*(telecom.isnull().sum()/len(telecom.index)), 2)
# In[194]:
# Removing NaN TotalCharges rows
telecom = telecom[~np.isnan(telecom['TotalCharges'])]
# In[195]:
# Checking percentage of missing values after removing the missing values
round(100*(telecom.isnull().sum()/len(telecom.index)), 2)
# Now we don't have any missing values
# ### Step 4: Test-Train Split
# In[196]:
from sklearn.model_selection import train_test_split
# In[197]:
# Putting feature variable to X
X = telecom.drop(['Churn','customerID'], axis=1)
X.head()
# In[198]:
# Putting response variable to y
y = telecom['Churn']
y.head()
# In[199]:
# Splitting the data into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, test_size=0.3, random_state=100)
# ### Step 5: Feature Scaling
# In[200]:
from sklearn.preprocessing import StandardScaler
# In[201]:
scaler = StandardScaler()
X_train[['tenure','MonthlyCharges','TotalCharges']] = scaler.fit_transform(X_train[['tenure','MonthlyCharges','TotalCharges']])
X_train.head()
# In[202]:
### Checking the Churn Rate
churn = (sum(telecom['Churn'])/len(telecom['Churn'].index))*100
churn
# We have almost 27% churn rate
# ### Step 6: Looking at Correlations
# In[203]:
# Importing matplotlib and seaborn
import matplotlib.pyplot as plt
import seaborn as sns
get_ipython().run_line_magic('matplotlib', 'inline')
# In[204]:
telecom.head()
# In[205]:
telecom.columns
# In[206]:
# Let's see the correlation matrix
plt.figure(figsize = (20,10)) # Size of the figure
sns.heatmap(telecom[['tenure', 'PhoneService', 'PaperlessBilling',
'MonthlyCharges', 'TotalCharges', 'Churn', 'SeniorCitizen', 'Partner',
'Dependents', 'Contract_One year', 'Contract_Two year',
'PaymentMethod_Credit card (automatic)',
'PaymentMethod_Electronic check', 'PaymentMethod_Mailed check',
'gender_Male', 'InternetService_Fiber optic', 'InternetService_No',
'MultipleLines_No', 'MultipleLines_Yes', 'OnlineSecurity_No',
'OnlineSecurity_Yes', 'OnlineBackup_No', 'OnlineBackup_Yes',
'DeviceProtection_No', 'DeviceProtection_Yes', 'TechSupport_No',
'TechSupport_Yes', 'StreamingTV_No', 'StreamingTV_Yes',
'StreamingMovies_No', 'StreamingMovies_Yes']].corr(),annot = True)
plt.show()
# #### Dropping highly correlated dummy variables
# In[207]:
X_test = X_test.drop(['MultipleLines_No','OnlineSecurity_No','OnlineBackup_No','DeviceProtection_No','TechSupport_No',
'StreamingTV_No','StreamingMovies_No'], axis=1)
X_train = X_train.drop(['MultipleLines_No','OnlineSecurity_No','OnlineBackup_No','DeviceProtection_No','TechSupport_No',
'StreamingTV_No','StreamingMovies_No'], axis=1)
# #### Checking the Correlation Matrix
# After dropping highly correlated variables now let's check the correlation matrix again.
# In[208]:
plt.figure(figsize = (20,10))
sns.heatmap(X_train.corr(),annot = True)
plt.show()
# ### Step 7: Model Building
# Let's start by splitting our data into a training set and a test set.
# #### Running Your First Training Model
# In[209]:
import statsmodels.api as sm
# In[210]:
X_train.head()
# In[211]:
X_train.info()
# In[212]:
y_train.info()
# In[213]:
# X_train=np.asarray(X_train)
# y_train=np.asarray(y_train)
# In[229]:
# Logistic regression model
logm1 = sm.GLM(y_train.astype(float),(sm.add_constant(X_train.astype(float))), family = sm.families.Binomial())
logm1.fit().summary()
# In[230]:
import statsmodels.api as sm
# # Ensure the input data is correctly formatted and numeric
X_train = sm.add_constant(X_train.astype(float)) # Add a constant term for the intercept
logit_model = sm.Logit(y_train.astype(float), X_train.astype(float))
result = logit_model.fit()
print(result.summary())
# ### Step 8: Feature Selection Using RFE
# In[216]:
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
# In[217]:
from sklearn.feature_selection import RFE
rfe = RFE(logreg, n_features_to_select=15) # running RFE with 15 variables as output
rfe = rfe.fit(X_train, y_train)
# In[218]:
rfe.support_
# In[219]:
X_train
# In[221]:
list(zip(X_train.columns, rfe.support_, rfe.ranking_))
# In[222]:
col = X_train.columns[rfe.support_]
# In[223]:
X_train.columns[~rfe.support_]
# ##### Assessing the model with StatsModels
# In[225]:
print(X_train.dtypes)
# In[226]:
X_train = X_train.apply(pd.to_numeric, errors='coerce')
X_train = X_train.fillna(0)
# In[228]:
X_train_sm = sm.add_constant(X_train[col])
logm2 = sm.GLM(y_train.astype(float),X_train_sm.astype(float), family = sm.families.Binomial())
res = logm2.fit()
res.summary()
# In[232]:
# Getting the predicted values on the train set
y_train_pred = res.predict(X_train_sm.astype(float))
y_train_pred[:10]
# In[233]:
y_train_pred = y_train_pred.values.reshape(-1)
y_train_pred[:10]
# ##### Creating a dataframe with the actual churn flag and the predicted probabilities
# In[234]:
y_train_pred_final = pd.DataFrame({'Churn':y_train.values, 'Churn_Prob':y_train_pred})
y_train_pred_final['CustID'] = y_train.index
y_train_pred_final.head()
# ##### Creating new column 'predicted' with 1 if Churn_Prob > 0.5 else 0
# In[235]:
y_train_pred_final['predicted'] = y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > 0.5 else 0)
# Let's see the head
y_train_pred_final.head()
# In[236]:
from sklearn import metrics
# In[237]:
# Confusion matrix
confusion = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.predicted )
print(confusion)
# In[55]:
# Predicted not_churn churn
# Actual
# not_churn 3270 365
# churn 579 708
# In[238]:
# Let's check the overall accuracy.
print(metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.predicted))
# #### Checking VIFs
# In[239]:
# Check for the VIF values of the feature variables.
from statsmodels.stats.outliers_influence import variance_inflation_factor
# In[240]:
# Create a dataframe that will contain the names of all the feature variables and their respective VIFs
vif = pd.DataFrame()
vif['Features'] = X_train[col].columns
vif['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]
vif['VIF'] = round(vif['VIF'], 2)
vif = vif.sort_values(by = "VIF", ascending = False)
vif
# There are a few variables with high VIF. It's best to drop these variables as they aren't helping much with prediction and unnecessarily making the model complex. The variable 'MonthlyCharges' has the highest VIF. So let's start by dropping that.
# In[241]:
col = col.drop('MonthlyCharges', 1)
col
# In[242]:
# Let's re-run the model using the selected variables
X_train_sm = sm.add_constant(X_train[col])
logm3 = sm.GLM(y_train.astype(float),X_train_sm.astype(float), family = sm.families.Binomial())
res = logm3.fit()
res.summary()
# In[243]:
y_train_pred = res.predict(X_train_sm).values.reshape(-1)
# In[244]:
y_train_pred[:10]
# In[245]:
y_train_pred_final['Churn_Prob'] = y_train_pred
# In[246]:
# Creating new column 'predicted' with 1 if Churn_Prob > 0.5 else 0
y_train_pred_final['predicted'] = y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > 0.5 else 0)
y_train_pred_final.head()
# In[247]:
# Let's check the overall accuracy.
print(metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.predicted))
# So overall the accuracy hasn't dropped much.
# ##### Let's check the VIFs again
# In[248]:
vif = pd.DataFrame()
vif['Features'] = X_train[col].columns
vif['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]
vif['VIF'] = round(vif['VIF'], 2)
vif = vif.sort_values(by = "VIF", ascending = False)
vif
# In[249]:
# Let's drop TotalCharges since it has a high VIF
col = col.drop('TotalCharges')
col
# In[250]:
# Let's re-run the model using the selected variables
X_train_sm = sm.add_constant(X_train[col])
logm4 = sm.GLM(y_train,X_train_sm, family = sm.families.Binomial())
res = logm4.fit()
res.summary()
# In[251]:
y_train_pred = res.predict(X_train_sm).values.reshape(-1)
# In[252]:
y_train_pred[:10]
# In[253]:
y_train_pred_final['Churn_Prob'] = y_train_pred
# In[254]:
# Creating new column 'predicted' with 1 if Churn_Prob > 0.5 else 0
y_train_pred_final['predicted'] = y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > 0.5 else 0)
y_train_pred_final.head()
# In[255]:
# Let's check the overall accuracy.
print(metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.predicted))
# The accuracy is still practically the same.
# ##### Let's now check the VIFs again
# In[256]:
vif = pd.DataFrame()
vif['Features'] = X_train[col].columns
vif['VIF'] = [variance_inflation_factor(X_train[col].values, i) for i in range(X_train[col].shape[1])]
vif['VIF'] = round(vif['VIF'], 2)
vif = vif.sort_values(by = "VIF", ascending = False)
vif
# All variables have a good value of VIF. So we need not drop any more variables and we can proceed with making predictions using this model only
# In[257]:
# Let's take a look at the confusion matrix again
confusion = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.predicted )
confusion
# In[76]:
# Actual/Predicted not_churn churn
# not_churn 3269 366
# churn 595 692
# In[258]:
# Let's check the overall accuracy.
metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.predicted)
# ## Metrics beyond simply accuracy
# In[259]:
TP = confusion[1,1] # true positive
TN = confusion[0,0] # true negatives
FP = confusion[0,1] # false positives
FN = confusion[1,0] # false negatives
# In[260]:
# Let's see the sensitivity of our logistic regression model
TP / float(TP+FN)
# In[261]:
# Let us calculate specificity
TN / float(TN+FP)
# In[262]:
# Calculate false postive rate - predicting churn when customer does not have churned
print(FP/ float(TN+FP))
# In[263]:
# positive predictive value
print (TP / float(TP+FP))
# In[264]:
# Negative predictive value
print (TN / float(TN+ FN))
# ### Step 9: Plotting the ROC Curve
# An ROC curve demonstrates several things:
#
# - It shows the tradeoff between sensitivity and specificity (any increase in sensitivity will be accompanied by a decrease in specificity).
# - The closer the curve follows the left-hand border and then the top border of the ROC space, the more accurate the test.
# - The closer the curve comes to the 45-degree diagonal of the ROC space, the less accurate the test.
# In[265]:
def draw_roc( actual, probs ):
fpr, tpr, thresholds = metrics.roc_curve( actual, probs,
drop_intermediate = False)
auc_score = metrics.roc_auc_score( actual, probs )
plt.figure(figsize=(5, 5))
plt.plot( fpr, tpr, label='ROC curve (area = %0.2f)' % auc_score )
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate or [1 - True Negative Rate]')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
return None
# In[266]:
fpr, tpr, thresholds = metrics.roc_curve( y_train_pred_final.Churn, y_train_pred_final.Churn_Prob, drop_intermediate = False )
# In[267]:
draw_roc(y_train_pred_final.Churn, y_train_pred_final.Churn_Prob)
# ### Step 10: Finding Optimal Cutoff Point
# Optimal cutoff probability is that prob where we get balanced sensitivity and specificity
# In[268]:
# Let's create columns with different probability cutoffs
numbers = [float(x)/10 for x in range(10)]
for i in numbers:
y_train_pred_final[i]= y_train_pred_final.Churn_Prob.map(lambda x: 1 if x > i else 0)
y_train_pred_final.head()
# In[269]:
# Now let's calculate accuracy sensitivity and specificity for various probability cutoffs.
cutoff_df = pd.DataFrame( columns = ['prob','accuracy','sensi','speci'])
from sklearn.metrics import confusion_matrix
# TP = confusion[1,1] # true positive
# TN = confusion[0,0] # true negatives
# FP = confusion[0,1] # false positives
# FN = confusion[1,0] # false negatives
num = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
for i in num:
cm1 = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final[i] )
total1=sum(sum(cm1))
accuracy = (cm1[0,0]+cm1[1,1])/total1
speci = cm1[0,0]/(cm1[0,0]+cm1[0,1])
sensi = cm1[1,1]/(cm1[1,0]+cm1[1,1])
cutoff_df.loc[i] =[ i ,accuracy,sensi,speci]
print(cutoff_df)
# In[270]:
# Let's plot accuracy sensitivity and specificity for various probabilities.
cutoff_df.plot.line(x='prob', y=['accuracy','sensi','speci'])
plt.show()
# #### From the curve above, 0.3 is the optimum point to take it as a cutoff probability.
# In[271]:
y_train_pred_final['final_predicted'] = y_train_pred_final.Churn_Prob.map( lambda x: 1 if x > 0.3 else 0)
y_train_pred_final.head()
# In[272]:
# Let's check the overall accuracy.
metrics.accuracy_score(y_train_pred_final.Churn, y_train_pred_final.final_predicted)
# In[273]:
confusion2 = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.final_predicted )
confusion2
# In[274]:
TP = confusion2[1,1] # true positive
TN = confusion2[0,0] # true negatives
FP = confusion2[0,1] # false positives
FN = confusion2[1,0] # false negatives
# In[275]:
# Let's see the sensitivity of our logistic regression model
TP / float(TP+FN)
# In[276]:
# Let us calculate specificity
TN / float(TN+FP)
# In[277]:
# Calculate false postive rate - predicting churn when customer does not have churned
print(FP/ float(TN+FP))
# In[278]:
# Positive predictive value
print (TP / float(TP+FP))
# In[279]:
# Negative predictive value
print (TN / float(TN+ FN))
#
#
#
#
# ## Precision and Recall
# In[99]:
#Looking at the confusion matrix again
# In[280]:
confusion = metrics.confusion_matrix(y_train_pred_final.Churn, y_train_pred_final.predicted )
confusion
# ##### Precision