-
Notifications
You must be signed in to change notification settings - Fork 0
/
Customer_Churn.Rmd
664 lines (436 loc) · 19.2 KB
/
Customer_Churn.Rmd
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
---
title: "Telco Customer Churn"
author: "Thanasis Zoumpekas"
output:
html_document:
df_print: paged
---
# Data Acquisition
The dataset downloaded from IBM sample datasets. You can find more on link : https://www.ibm.com/communities/analytics/watson-analytics-blog/guide-to-sample-datasets/
### Telco Customer Churn Dataset
This data set provides information to predict behavior to retain customers.
A **telecommunications company** is concerned about the number of customers leaving their landline business for cable competitors. They need to understand who is leaving.
The data set includes information about:
-Customers who left within the last month – the column is called Churn
-Services that each customer has signed up for – phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies
-Customer account information – how long they’ve been a customer, contract, payment method, paperless billing, monthly charges, and total charges
-Demographic info about customers – gender, age range, and if they have partners and dependents
```{r}
library(readr)
library(tidyr)
library(tidyverse)
library(MASS)
library(car)
library(e1071)
library(caret)
library(cowplot)
library(caTools)
library(pROC)
df <- read.csv('/home/thzou/Projects/B.I./Customer_Churn/WA_Fn-UseC_-Telco-Customer-Churn.csv')
head(df)
```
```{r}
summary(df)
```
# Data Pre-processing
## Data Exploration
We will check for na values, i.e. missing data from our dataframe.
```{r}
options(repr.plot.width = 6, repr.plot.height = 4)
missing_data <- df %>% summarise_all(funs(sum(is.na(.))/n()))
missing_data <- gather(missing_data, key = "variables", value = "percent_missing")
ggplot(missing_data, aes(x = reorder(variables, percent_missing), y = percent_missing)) +
geom_bar(stat = "identity", fill = "red", aes(color = I('white')), size = 0.3)+
xlab('variables')+
coord_flip()+
theme_bw()
```
```{r}
cat ("Number of missing values :", sum(is.na(df))) #number of missing values
dfnew = na.omit(df)
cat ("\nNumber of missing values (after removing the NAs):", sum(is.na(dfnew))) #double check for missing values
head(dfnew)
```
SeniorCitizen is in 'int' form, that can be changed to categorical.
```{r}
dfnew <- dfnew[complete.cases(dfnew),]
dfnew$SeniorCitizen <- as.factor(ifelse(dfnew$SeniorCitizen==1, 'YES', 'NO'))
```
We will check how many unique customers we have. As we can see we have 7032 unique customers.
```{r}
length(unique(dfnew$customerID))
```
We will drop the column customerID, because it is unique for each observation. Thus, this variable does not provide us with additional valuable information.
```{r}
dfnew = subset(dfnew, select = -c(customerID)) #drop the customerID
head(dfnew)
```
```{r}
options(repr.plot.width = 6, repr.plot.height = 4)
dfnew %>%
group_by(Churn) %>%
summarise(Count = n())%>%
mutate(percent = prop.table(Count)*100)%>%
ggplot(aes(reorder(Churn, -percent), percent), fill = Churn)+
geom_col(fill = c("#FC4E07", "#E7B800"))+
geom_text(aes(label = sprintf("%.2f%%", percent)), hjust = 0.01,vjust = -0.5, size =3)+
theme_bw()+
xlab("Churn") +
ylab("Percent")+
ggtitle("Churn Percent")
```
The graph above shows that 26% of customers or subscribers stop doing business with the company.
Below we can see the percentage of customer churn, according to each feature.
```{r}
theme1 <- theme_bw()+ theme(axis.text.x = element_text(angle = 0, hjust = 1, vjust = 0.5),legend.position="none")
theme2 <- theme_bw()+ theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),legend.position="none")
#options(repr.plot.width = 14, repr.plot.height = 10)
plot_grid(ggplot(dfnew, aes(x=gender,fill=Churn))+ geom_bar()+ theme2,
ggplot(dfnew, aes(x=SeniorCitizen,fill=Churn))+ geom_bar(position = 'fill')+theme2,
ggplot(dfnew, aes(x=Partner,fill=Churn))+ geom_bar(position = 'fill')+theme2,
ggplot(dfnew, aes(x=Dependents,fill=Churn))+ geom_bar(position = 'fill')+theme2,
ggplot(dfnew, aes(x=PhoneService,fill=Churn))+ geom_bar(position = 'fill')+theme2,
ggplot(dfnew, aes(x=MultipleLines,fill=Churn))+ geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 14)),
align = "h")
```
```{r}
#options(repr.plot.width = 12, repr.plot.height = 8)
plot_grid(ggplot(dfnew, aes(x=InternetService,fill=Churn))+ geom_bar(position = 'fill')+ theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=OnlineSecurity,fill=Churn))+ geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=OnlineBackup,fill=Churn))+ geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=DeviceProtection,fill=Churn))+ geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=TechSupport,fill=Churn))+ geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=StreamingTV,fill=Churn))+ geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
align = "h")
```
```{r}
plot_grid(ggplot(dfnew, aes(x=StreamingMovies,fill=Churn))+
geom_bar(position = 'fill')+ theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=Contract,fill=Churn))+
geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=PaperlessBilling,fill=Churn))+
geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
ggplot(dfnew, aes(x=PaymentMethod,fill=Churn))+
geom_bar(position = 'fill')+theme2+
scale_x_discrete(labels = function(x) str_wrap(x, width = 10)),
align = "h")
```
```{r}
ggplot(dfnew, aes(x=Churn, y=tenure, fill=Churn)) +
geom_boxplot(alpha=0.4) +
stat_summary(fun.y=mean, geom="point", shape=20, size=10, color="red", fill="red") +
theme(legend.position="right") +
scale_fill_brewer(palette="Set2") +
xlab(" ")
ggplot(dfnew, aes(x=Churn, y=MonthlyCharges, fill=Churn)) +
geom_boxplot(alpha=0.4) +
stat_summary(fun.y=mean, geom="point", shape=20, size=10, color="red", fill="red") +
theme(legend.position="right") +
scale_fill_brewer(palette="Set1") +
xlab(" ")
ggplot(dfnew, aes(x=Churn, y=TotalCharges, fill=Churn)) +
geom_boxplot(alpha=0.4) +
stat_summary(fun.y=mean, geom="point", shape=20, size=10, color="red", fill="red") +
theme(legend.position="right") +
scale_fill_brewer(palette="Set3") +
xlab(" ")
```
The red dot on the graphs above indicates the mean (average value).
We will check the correlation between continuous variables of the dataset.
```{r}
library(mlbench)
library(caret)
library(corrplot)
# calculate correlation matrix
correlationMatrix <- cor(dfnew[,c('tenure','MonthlyCharges','TotalCharges')])
# summarize the correlation matrix
print(correlationMatrix)
# find attributes that are highly corrected (ideally >0.75)
highlyCorrelated <- findCorrelation(correlationMatrix, cutoff=0.5)
# print indexes of highly correlated attributes
print(highlyCorrelated)
corrplot(correlationMatrix, method="number")
```
We have only 3 continuous variables so we dont need a heatmap to represent the correlation matrix. As we can see Total Charges are highly correlated (0.83) with tenure. We can also observe that Monthly Charges are also correlated with Total Charges (0.65). That is somehow natural, because they are both charges.
## Data Preparation
**Redefine the categorical features-variables**
According to Data Exploration section, we observe that there are categorical features, labeled 'No', 'No Internet Service' or 'No Phone Service'. In order to make these variables more useful, we redefine these values as 'No' and clean these features.
```{r}
dfnew <- data.frame(lapply(dfnew, function(x) {
gsub("No internet service", "No", x)}))
dfnew <- data.frame(lapply(dfnew, function(x) {
gsub("No phone service", "No", x)}))
```
**Standardization of continuous variables**
```{r}
num_columns <- c("tenure", "MonthlyCharges", "TotalCharges")
dfnew[num_columns] <- sapply(dfnew[num_columns], as.numeric)
telco_int <- dfnew[,c("tenure", "MonthlyCharges", "TotalCharges")]
telco_int <- data.frame(scale(telco_int))
```
**Creating derived features**
In order to create derived feature from tenure(which is in months), we create different bins of tenure, labeled as follows, '0-1 year', '2-3 years', '3-4 years' etc.
```{r}
#max(telco$tenure)
#min(telco$tenure)
dfnew <- mutate(dfnew, tenure_bin = tenure)
dfnew$tenure_bin[dfnew$tenure_bin >=0 & dfnew$tenure_bin <= 12] <- '0-1 year'
dfnew$tenure_bin[dfnew$tenure_bin > 12 & dfnew$tenure_bin <= 24] <- '1-2 years'
dfnew$tenure_bin[dfnew$tenure_bin > 24 & dfnew$tenure_bin <= 36] <- '2-3 years'
dfnew$tenure_bin[dfnew$tenure_bin > 36 & dfnew$tenure_bin <= 48] <- '3-4 years'
dfnew$tenure_bin[dfnew$tenure_bin > 48 & dfnew$tenure_bin <= 60] <- '4-5 years'
dfnew$tenure_bin[dfnew$tenure_bin > 60 & dfnew$tenure_bin <= 72] <- '5-6 years'
dfnew$tenure_bin <- as.factor(dfnew$tenure_bin)
```
After observing the distribution of data in each tenure bin, we found that maximum number of customers have a tenure of either 0-1 years and followed by 5-6 years.
```{r}
ggplot(dfnew, aes(tenure_bin, fill = tenure_bin)) + geom_bar()+ theme1
```
**Creating Dummy Variables**
```{r}
telco_cat <- dfnew[,-c(5,18,19)]
#Creating Dummy Variables
dummy<- data.frame(sapply(telco_cat,function(x) data.frame(model.matrix(~x-1,data =telco_cat))[,-1]))
head(dummy)
```
**Creating the final dataset by combining the numeric and dummy data frames.**
```{r}
#Combining the data
df_final <- cbind(telco_int,dummy)
head(df_final)
```
```{r}
col_names <- names(df_final[,-c(1:3)])
df_final[,col_names] <- lapply(df_final[,col_names] , factor)
```
## Rank Features By Importance
The importance of features can be estimated from data by building a model. Some methods like decision trees have a built in mechanism to report on variable importance. For other algorithms, the importance can be estimated using a ROC curve analysis conducted for each attribute.
Below we will use the Learning Vector Quantization (LVQ) model. The varImp is then used to estimate the variable importance, which is printed and plotted. It shows that the glucose, mass and age attributes are the top 3 most important attributes in the dataset and the insulin attribute is the least important.
```{r}
set.seed(6)
library(e1071)
library(mlbench)
library(caret)
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)
# prepare training scheme
control <- trainControl(method="repeatedcv", number=10, repeats=3)
# train the model
model_lvq <- train(Churn~., data=df_final, method="lvq", trControl=control)
# estimate variable importance
importance_lvq <- varImp(model_lvq, scale=FALSE)
stopCluster(cl)
# summarize importance
print(importance_lvq)
# plot importance
plot(importance_lvq)
```
```{r}
set.seed(7)
library(e1071)
library(mlbench)
library(caret)
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)
# prepare training scheme
control <- trainControl(method="repeatedcv", number=10, repeats=3)
# train the model
model_ada <- train(Churn~., data=df_final, method="ada", trControl=control)
# estimate variable importance
importance_ada <- varImp(model_ada, scale=FALSE)
stopCluster(cl)
# summarize importance
print(importance_ada)
# plot importance
plot(importance_ada)
```
```{r}
set.seed(8)
library(e1071)
library(mlbench)
library(caret)
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)
# prepare training scheme
control <- trainControl(method="repeatedcv", number=10, repeats=3)
# train the model
model_svm <- train(Churn~., data=df_final, method="svmRadial", trControl=control)
# estimate variable importance
importance_svm <- varImp(model_svm, scale=FALSE)
stopCluster(cl)
# summarize importance
print(importance_svm)
# plot importance
plot(importance_svm)
```
## Feature Selection
Automatic feature selection methods can be used to build many models with different subsets of a dataset and identify those attributes that are and are not required to build an accurate model.
A popular automatic method for feature selection provided by the caret R package is called Recursive Feature Elimination or RFE.
The example below provides an example of the RFE method on the Pima Indians Diabetes dataset. A Random Forest algorithm is used on each iteration to evaluate the model. The algorithm is configured to explore all possible subsets of the attributes. All 8 attributes are selected in this example, although in the plot showing the accuracy of the different attribute subset sizes, we can see that just 4 attributes gives almost comparable results.
```{r}
# ensure the results are repeatable
set.seed(7)
# load the library
library(mlbench)
library(caret)
library(doParallel)
y = df_final$Churn
x = subset(df_final, select = -c(Churn))
# define the control using a random forest selection function
cl <- makeCluster(4)
registerDoParallel(cl)
control <- rfeControl(functions=rfFuncs, method="cv", number=10, repeats=3)
# run the RFE algorithm
results <- rfe(x, y, rfeControl=control)
stopCluster(cl)
# summarize the results
print(results)
# list the chosen features
predictors(results)
# plot the results
plot(results, type=c("g", "o"))
```
## Model Building
We will try to predict if a customer is going to leave of not (i.e. customer churn prediction).
### Logistic Regression
First of all we will split the data in 65% training and 35% validation set.
```{r}
library(e1071)
library(mlbench)
library(caret)
library(doParallel)
#Splitting the data
set.seed(123)
indices = sample.split(df_final$Churn, SplitRatio = 0.65)
train = df_final[indices,]
validation = df_final[!(indices),]
cl <- makeCluster(4)
registerDoParallel(cl)
#Build the first model using all variables
model_1 = glm(Churn ~ ., data = train, family = "binomial")
summary(model_1)
stopCluster(cl)
```
**stepAIC** is a iterative process of adding or removing variables, in order to get a subset of variables that gives the best performing model. We will use this for variable selection.
```{r}
model_2 <- stepAIC(model_1, direction="both",trace = 0)
```
```{r}
summary(model_2)
```
We use variance inflation factor (vif) to get rid of redundant predictors or the variables that have high multicollinearity between them. Multicollinearity exists when two or more predictor variables are highly related to each other and then it becomes difficult to understand the impact of an independent variable on the dependent variable.
The Variance Inflation Factor(VIF) is used to measure the multicollinearity between predictor variables in a model. A predictor having a VIF of 2 or less is generally considered safe and it can be assumed that it is not correlated with other predictor variables. Higher the VIF, greater is the correlation of the predictor variable w.r.t other predictor variables. However, Predictors with high VIF may have high p-value(or highly significant), hence, we need to see the significance of the Predictor variable before removing it from our model.
```{r}
vif(model_2)
```
**Removing variables-features due to high p-value ( > 0.05 alpha level)**
```{r}
model_3 <-glm(formula = Churn ~ tenure + MonthlyCharges + SeniorCitizen +
InternetService.xFiber.optic + InternetService.xNo +
OnlineSecurity + OnlineBackup + TechSupport +
StreamingTV + Contract.xOne.year + Contract.xTwo.year + PaperlessBilling +
PaymentMethod.xElectronic.check + tenure_bin.x1.2.years +
tenure_bin.x5.6.years, family = "binomial", data = train)
summary(model_3)
vif(model_3)
```
**Removing StreamingTV feature**
```{r}
model_4 <-glm(formula = Churn ~ tenure + MonthlyCharges + SeniorCitizen +
InternetService.xFiber.optic + InternetService.xNo +
OnlineSecurity + OnlineBackup + TechSupport +
Contract.xOne.year + Contract.xTwo.year + PaperlessBilling +
PaymentMethod.xElectronic.check + tenure_bin.x1.2.years +
tenure_bin.x5.6.years, family = "binomial", data = train)
summary(model_4)
vif(model_4)
```
## Model Evaluation
### Logistic Regression
```{r}
final_model <- model_4 #keep the final model
pred <- predict(final_model, type = "response", newdata = validation[,-24])
summary(pred)
validation$prob <- pred
# Using probability cutoff of 50%.
pred_churn <- factor(ifelse(pred >= 0.50, "Yes", "No"))
actual_churn <- factor(ifelse(validation$Churn==1,"Yes","No"))
table(actual_churn,pred_churn)
```
```{r}
cutoff_churn <- factor(ifelse(pred >=0.50, "Yes", "No"))
conf_final <- confusionMatrix(cutoff_churn, actual_churn, positive = "Yes")
accuracy <- conf_final$overall[1]
sensitivity <- conf_final$byClass[1]
specificity <- conf_final$byClass[2]
round(accuracy,digits=2)
round(sensitivity,digits=2)
round(specificity,digits=2)
```
We can observe that, by using a cutoff of 0.50, we are getting good accuracy and specificity, but the sensitivity is nearly above average. Thus, we need to find the optimal probalility cutoff which will give maximum accuracy, sensitivity and specificity.
```{r}
perform_fn <- function(cutoff)
{
predicted_churn <- factor(ifelse(pred >= cutoff, "Yes", "No"))
conf <- confusionMatrix(predicted_churn, actual_churn, positive = "Yes")
accuray <- conf$overall[1]
sensitivity <- conf$byClass[1]
specificity <- conf$byClass[2]
out <- t(as.matrix(c(sensitivity, specificity, accuray)))
colnames(out) <- c("sensitivity", "specificity", "accuracy")
return(out)
}
summary(pred)
s = seq(0.01,0.80,length=100)
OUT = matrix(0,100,3)
for(i in 1:100)
{
OUT[i,] = perform_fn(s[i])
}
plot(s, OUT[,1],xlab="Cutoff",ylab="Value",cex.lab=1.5,cex.axis=1.5,ylim=c(0,1),
type="l",lwd=2,axes=FALSE,col=2)
axis(1,seq(0,1,length=5),seq(0,1,length=5),cex.lab=1.5)
axis(2,seq(0,1,length=5),seq(0,1,length=5),cex.lab=1.5)
lines(s,OUT[,2],col="darkgreen",lwd=2)
lines(s,OUT[,3],col=4,lwd=2)
box()
legend("bottom",col=c(2,"darkgreen",4,"darkred"),text.font =3,inset = 0.02,
box.lty=0,cex = 0.8,
lwd=c(2,2,2,2),c("Sensitivity","Specificity","Accuracy"))
abline(v = 0.32, col="red", lwd=1, lty=2)
axis(1, at = seq(0.1, 1, by = 0.1))
optimal_cutoff <- s[which(abs(OUT[,1]-OUT[,2])<0.01)]
cat("\n\nOptimal Cutoff : ", optimal_cutoff)
```
We will calculate again the accuracy, sensitivity and specificity, by using optimal probalility cutoff.
```{r}
cutoff_churn <- factor(ifelse(pred >= optimal_cutoff, "Yes", "No"))
conf_final <- confusionMatrix(cutoff_churn, actual_churn, positive = "Yes")
accuracy <- conf_final$overall[1]
sensitivity <- conf_final$byClass[1]
specificity <- conf_final$byClass[2]
accuracy = round(accuracy,digits=2)
sensitivity = round(sensitivity,digits=2)
specificity = round(specificity,digits=2)
```
## Model Summary
Best logistic regression model :
```{r}
summary(final_model)
perf_metrics <- data_frame(accuracy,sensitivity,specificity)
perf_metrics
```
We can predict with 75% probability if a customer is going to leave/unsubscribe or stay.