Naive Bayes, NB, DDA algorithms

In statistics, Naive Bayes classifiers are a family of simple "probabilistic classifiers" based on applying Bayes' theorem with strong (naive) independence assumptions between the features. They are among the simplest Bayesian network models.But they could be coupled with Kernel density estimation and achieve higher accuracy levels.
Naive Bayes classifiers are highly scalable, requiring a number of parameters linear in the number of variables (features/predictors) in a learning problem. Maximum-likelihood training can be done by evaluating a closed-form expression, which takes linear time, rather than by expensive iterative approximation as used for many other types of classifiers.
In the statistics and computer science literature, naive Bayes models are known under a variety of names, including simple Bayes and independence Bayes. All these names reference the use of Bayes' theorem in the classifier's decision rule, but naïve Bayes is not (necessarily) a Bayesian method.

In computer graphics, a digital differential analyzer (DDA) is hardware or software used for interpolation of variables over an interval between start and end point. DDAs are used for rasterization of lines, triangles and polygons. They can be extended to non linear functions, such as perspective correct texture mapping, quadratic curves, and traversing voxels.

Here we are going to implement Naive Bayes, NB and DDA algorithms using Telecom Churn Dataset.

0. Loading required libraries

In [4]:
library(DBI)
library(corrgram)
library(caret) 
library(gridExtra)
library(ggpubr)

1. Setting up the code parallelizing

Today is a good practice to start parallelizing your code. The common motivation behind parallel computing is that something is taking too long time. For somebody that means any computation that takes more than 3 minutes – this because parallelization is incredibly simple and most tasks that take time are embarrassingly parallel. Here are a few common tasks that fit the description:

  • Bootstrapping
  • Cross-validation
  • Multivariate Imputation by Chained Equations (MICE)
  • Fitting multiple regression models
You can find out more about parallelizing your computations in R - here.

For Windows users

In [ ]:
# process in parallel on Windows
library(doParallel) 
cl <- makeCluster(detectCores(), type='PSOCK')
registerDoParallel(cl)

For Mac OSX and Unix like systems users

In [7]:
# process in parallel on Mac OSX and UNIX like systems
library(doMC)
registerDoMC(cores = 4)

2. Importing Data

In [8]:
#Set working directory where CSV is located

#getwd()
#setwd("...YOUR WORKING DIRECTORY WITH A DATASET...")
#getwd()
In [8]:
# Load the DataSets: 
dataSet <- read.csv("TelcoCustomerChurnDataset.csv", header = TRUE, sep = ',')
colnames(dataSet) #Check the dataframe column names
  1. 'Account_Length'
  2. 'Vmail_Message'
  3. 'Day_Mins'
  4. 'Eve_Mins'
  5. 'Night_Mins'
  6. 'Intl_Mins'
  7. 'CustServ_Calls'
  8. 'Churn'
  9. 'Intl_Plan'
  10. 'Vmail_Plan'
  11. 'Day_Calls'
  12. 'Day_Charge'
  13. 'Eve_Calls'
  14. 'Eve_Charge'
  15. 'Night_Calls'
  16. 'Night_Charge'
  17. 'Intl_Calls'
  18. 'Intl_Charge'
  19. 'State'
  20. 'Area_Code'
  21. 'Phone'

3. Exploring the dataset

In [9]:
# Print top 10 rows in the dataSet
head(dataSet, 10)
A data.frame: 10 × 21
Account_LengthVmail_MessageDay_MinsEve_MinsNight_MinsIntl_MinsCustServ_CallsChurnIntl_PlanVmail_Plan⋯Day_ChargeEve_CallsEve_ChargeNight_CallsNight_ChargeIntl_CallsIntl_ChargeStateArea_CodePhone
<int><int><dbl><dbl><dbl><dbl><int><fct><fct><fct>⋯<dbl><int><dbl><int><dbl><int><dbl><fct><int><fct>
112825265.1197.4244.710.01nono yes⋯45.07 9916.78 9111.0132.70KS415382-4657
210726161.6195.5254.413.71nono yes⋯27.4710316.6210311.4533.70OH415371-7191
3137 0243.4121.2162.612.20nono no ⋯41.3811010.30104 7.3253.29NJ415358-1921
4 84 0299.4 61.9196.9 6.62noyesno ⋯50.90 88 5.26 89 8.8671.78OH408375-9999
5 75 0166.7148.3186.910.13noyesno ⋯28.3412212.61121 8.4132.73OK415330-6626
6118 0223.4220.6203.9 6.30noyesno ⋯37.9810118.75118 9.1861.70AL510391-8027
712124218.2348.5212.6 7.53nono yes⋯37.0910829.62118 9.5772.03MA510355-9993
8147 0157.0103.1211.8 7.10noyesno ⋯26.69 94 8.76 96 9.5361.92MO415329-9001
9117 0184.5351.6215.8 8.71nono no ⋯31.37 8029.89 90 9.7142.35LA408335-4719
1014137258.6222.0326.411.20noyesyes⋯43.9611118.87 9714.6953.02WV415330-8173
In [10]:
# Print last 10 rows in the dataSet
tail(dataSet, 10)
A data.frame: 10 × 21
Account_LengthVmail_MessageDay_MinsEve_MinsNight_MinsIntl_MinsCustServ_CallsChurnIntl_PlanVmail_Plan⋯Day_ChargeEve_CallsEve_ChargeNight_CallsNight_ChargeIntl_CallsIntl_ChargeStateArea_CodePhone
<int><int><dbl><dbl><dbl><dbl><int><fct><fct><fct>⋯<dbl><int><dbl><int><dbl><int><dbl><fct><int><fct>
3324117 0118.4249.3227.013.65yesno no ⋯20.13 9721.19 5610.22 33.67IN415362-5899
3325159 0169.8197.7193.711.61no no no ⋯28.8710516.80 82 8.72 43.13WV415377-1164
3326 78 0193.4116.9243.3 9.32no no no ⋯32.88 88 9.9410910.95 42.51OH408368-8555
3327 96 0106.6284.8178.914.91no no no ⋯18.12 8724.21 92 8.05 74.02OH415347-6812
3328 79 0134.7189.7221.411.82no no no ⋯22.90 6816.12128 9.96 53.19SC415348-3830
332919236156.2215.5279.1 9.92no no yes⋯26.5512618.32 8312.56 62.67AZ415414-4276
3330 68 0231.1153.4191.3 9.63no no no ⋯39.29 5513.04123 8.61 42.59WV415370-3271
3331 28 0180.8288.8191.914.12no no no ⋯30.74 5824.55 91 8.64 63.81RI510328-8230
3332184 0213.8159.6139.2 5.02no yesno ⋯36.35 8413.57137 6.26101.35CT510364-6381
3333 7425234.4265.9241.413.70no no yes⋯39.85 8222.60 7710.86 43.70TN415400-4344
In [11]:
# Dimention of Dataset
dim(dataSet)
  1. 3333
  2. 21
In [12]:
# Check Data types of each column
table(unlist(lapply(dataSet, class)))
 factor integer numeric 
      5       8       8 
In [13]:
# Check Data types of individual column
data.class(dataSet$Account_Length) 
data.class(dataSet$Vmail_Message) 
data.class(dataSet$Day_Mins)
data.class(dataSet$Eve_Mins)
data.class(dataSet$Night_Mins) 
data.class(dataSet$Intl_Mins)
data.class(dataSet$CustServ_Calls)
data.class(dataSet$Intl_Plan) 
data.class(dataSet$Vmail_Plan)
data.class(dataSet$Day_Calls)
data.class(dataSet$Day_Charge) 
data.class(dataSet$Eve_Calls)
data.class(dataSet$Eve_Charge) 
data.class(dataSet$Night_Calls)
data.class(dataSet$Night_Charge)
data.class(dataSet$Intl_Calls) 
data.class(dataSet$Intl_Charge)
data.class(dataSet$State) 
data.class(dataSet$Phone)
data.class(dataSet$Churn)
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'factor'
'factor'
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'numeric'
'factor'
'factor'
'factor'

Converting variables Intl_Plan, Vmail_Plan, State to numeric data type.

In [14]:
dataSet$Intl_Plan <- as.numeric(dataSet$Intl_Plan)
dataSet$Vmail_Plan <- as.numeric(dataSet$Vmail_Plan)
dataSet$State <- as.numeric(dataSet$State)
In [15]:
# Check Data types of each column
table(unlist(lapply(dataSet, class)))
 factor integer numeric 
      2       8      11 

4. Exploring or Summarising dataset with descriptive statistics

In [16]:
# Find out if there is missing value in rows
rowSums(is.na(dataSet))
  1. 0
  2. 0
  3. 0
  4. 0
  5. 0
  6. 0
  7. 0
  8. 0
  9. 0
  10. 0
  11. 0
  12. 0
  13. 0
  14. 0
  15. 0
  16. 0
  17. 0
  18. 0
  19. 0
  20. 0
  21. 0
  22. 0
  23. 0
  24. 0
  25. 0
  26. 0
  27. 0
  28. 0
  29. 0
  30. 0
  31. 0
  32. 0
  33. 0
  34. 0
  35. 0
  36. 0
  37. 0
  38. 0
  39. 0
  40. 0
  41. 0
  42. 0
  43. 0
  44. 0
  45. 0
  46. 0
  47. 0
  48. 0
  49. 0
  50. 0
  51. 0
  52. 0
  53. 0
  54. 0
  55. 0
  56. 0
  57. 0
  58. 0
  59. 0
  60. 0
  61. 0
  62. 0
  63. 0
  64. 0
  65. 0
  66. 0
  67. 0
  68. 0
  69. 0
  70. 0
  71. 0
  72. 0
  73. 0
  74. 0
  75. 0
  76. 0
  77. 0
  78. 0
  79. 0
  80. 0
  81. 0
  82. 0
  83. 0
  84. 0
  85. 0
  86. 0
  87. 0
  88. 0
  89. 0
  90. 0
  91. 0
  92. 0
  93. 0
  94. 0
  95. 0
  96. 0
  97. 0
  98. 0
  99. 0
  100. 0
  101. 0
  102. 0
  103. 0
  104. 0
  105. 0
  106. 0
  107. 0
  108. 0
  109. 0
  110. 0
  111. 0
  112. 0
  113. 0
  114. 0
  115. 0
  116. 0
  117. 0
  118. 0
  119. 0
  120. 0
  121. 0
  122. 0
  123. 0
  124. 0
  125. 0
  126. 0
  127. 0
  128. 0
  129. 0
  130. 0
  131. 0
  132. 0
  133. 0
  134. 0
  135. 0
  136. 0
  137. 0
  138. 0
  139. 0
  140. 0
  141. 0
  142. 0
  143. 0
  144. 0
  145. 0
  146. 0
  147. 0
  148. 0
  149. 0
  150. 0
  151. 0
  152. 0
  153. 0
  154. 0
  155. 0
  156. 0
  157. 0
  158. 0
  159. 0
  160. 0
  161. 0
  162. 0
  163. 0
  164. 0
  165. 0
  166. 0
  167. 0
  168. 0
  169. 0
  170. 0
  171. 0
  172. 0
  173. 0
  174. 0
  175. 0
  176. 0
  177. 0
  178. 0
  179. 0
  180. 0
  181. 0
  182. 0
  183. 0
  184. 0
  185. 0
  186. 0
  187. 0
  188. 0
  189. 0
  190. 0
  191. 0
  192. 0
  193. 0
  194. 0
  195. 0
  196. 0
  197. 0
  198. 0
  199. 0
  200. 0
  201. ⋯
  202. 0
  203. 0
  204. 0
  205. 0
  206. 0
  207. 0
  208. 0
  209. 0
  210. 0
  211. 0
  212. 0
  213. 0
  214. 0
  215. 0
  216. 0
  217. 0
  218. 0
  219. 0
  220. 0
  221. 0
  222. 0
  223. 0
  224. 0
  225. 0
  226. 0
  227. 0
  228. 0
  229. 0
  230. 0
  231. 0
  232. 0
  233. 0
  234. 0
  235. 0
  236. 0
  237. 0
  238. 0
  239. 0
  240. 0
  241. 0
  242. 0
  243. 0
  244. 0
  245. 0
  246. 0
  247. 0
  248. 0
  249. 0
  250. 0
  251. 0
  252. 0
  253. 0
  254. 0
  255. 0
  256. 0
  257. 0
  258. 0
  259. 0
  260. 0
  261. 0
  262. 0
  263. 0
  264. 0
  265. 0
  266. 0
  267. 0
  268. 0
  269. 0
  270. 0
  271. 0
  272. 0
  273. 0
  274. 0
  275. 0
  276. 0
  277. 0
  278. 0
  279. 0
  280. 0
  281. 0
  282. 0
  283. 0
  284. 0
  285. 0
  286. 0
  287. 0
  288. 0
  289. 0
  290. 0
  291. 0
  292. 0
  293. 0
  294. 0
  295. 0
  296. 0
  297. 0
  298. 0
  299. 0
  300. 0
  301. 0
  302. 0
  303. 0
  304. 0
  305. 0
  306. 0
  307. 0
  308. 0
  309. 0
  310. 0
  311. 0
  312. 0
  313. 0
  314. 0
  315. 0
  316. 0
  317. 0
  318. 0
  319. 0
  320. 0
  321. 0
  322. 0
  323. 0
  324. 0
  325. 0
  326. 0
  327. 0
  328. 0
  329. 0
  330. 0
  331. 0
  332. 0
  333. 0
  334. 0
  335. 0
  336. 0
  337. 0
  338. 0
  339. 0
  340. 0
  341. 0
  342. 0
  343. 0
  344. 0
  345. 0
  346. 0
  347. 0
  348. 0
  349. 0
  350. 0
  351. 0
  352. 0
  353. 0
  354. 0
  355. 0
  356. 0
  357. 0
  358. 0
  359. 0
  360. 0
  361. 0
  362. 0
  363. 0
  364. 0
  365. 0
  366. 0
  367. 0
  368. 0
  369. 0
  370. 0
  371. 0
  372. 0
  373. 0
  374. 0
  375. 0
  376. 0
  377. 0
  378. 0
  379. 0
  380. 0
  381. 0
  382. 0
  383. 0
  384. 0
  385. 0
  386. 0
  387. 0
  388. 0
  389. 0
  390. 0
  391. 0
  392. 0
  393. 0
  394. 0
  395. 0
  396. 0
  397. 0
  398. 0
  399. 0
  400. 0
  401. 0
In [17]:
# Find out if there is missing value in columns
colSums(is.na(dataSet))
Account_Length
0
Vmail_Message
0
Day_Mins
0
Eve_Mins
0
Night_Mins
0
Intl_Mins
0
CustServ_Calls
0
Churn
0
Intl_Plan
0
Vmail_Plan
0
Day_Calls
0
Day_Charge
0
Eve_Calls
0
Eve_Charge
0
Night_Calls
0
Night_Charge
0
Intl_Calls
0
Intl_Charge
0
State
0
Area_Code
0
Phone
0

Missing value checking using different packages (mice and VIM)

In [18]:
#Checking missing value with the mice package
library(mice)
md.pattern(dataSet)
Attaching package: ‘mice’


The following objects are masked from ‘package:base’:

    cbind, rbind


 /\     /\
{  `---'  }
{  O   O  }
==>  V <==  No need for mice. This data set is completely observed.
 \  \|/  /
  `-----'

A matrix: 2 × 22 of type dbl
Account_LengthVmail_MessageDay_MinsEve_MinsNight_MinsIntl_MinsCustServ_CallsChurnIntl_PlanVmail_Plan⋯Eve_CallsEve_ChargeNight_CallsNight_ChargeIntl_CallsIntl_ChargeStateArea_CodePhone
33331111111111⋯1111111110
0000000000⋯0000000000
In [19]:
#Checking missing value with the VIM package
library(VIM)
mice_plot <- aggr(dataSet, col=c('navyblue','yellow'),
                  numbers=TRUE, sortVars=TRUE,
                  labels=names(dataSet[1:21]), cex.axis=.9,
                  gap=3, ylab=c("Missing data","Pattern"))
Loading required package: colorspace

Loading required package: grid

VIM is ready to use.


Suggestions and bug-reports can be submitted at: https://github.com/statistikat/VIM/issues


Attaching package: ‘VIM’


The following object is masked from ‘package:datasets’:

    sleep


 Variables sorted by number of missings: 
       Variable Count
 Account_Length     0
  Vmail_Message     0
       Day_Mins     0
       Eve_Mins     0
     Night_Mins     0
      Intl_Mins     0
 CustServ_Calls     0
          Churn     0
      Intl_Plan     0
     Vmail_Plan     0
      Day_Calls     0
     Day_Charge     0
      Eve_Calls     0
     Eve_Charge     0
    Night_Calls     0
   Night_Charge     0
     Intl_Calls     0
    Intl_Charge     0
          State     0
      Area_Code     0
          Phone     0

After the observation, we can claim that dataset contains no missing values.

Summary of dataset

In [20]:
# Selecting just columns with numeric data type
numericalCols <- colnames(dataSet[c(1:7,9:20)])

Difference between the lapply and sapply functions (we will use them in the next 2 cells):
We use lapply - when we want to apply a function to each element of a list in turn and get a list back.
We use sapply - when we want to apply a function to each element of a list in turn, but we want a vector back, rather than a list.

Finding statistics metrics with lapply function

In [21]:
#Sum
lapply(dataSet[numericalCols], FUN = sum)
$Account_Length
336849
$Vmail_Message
26994
$Day_Mins
599190.4
$Eve_Mins
669867.5
$Night_Mins
669506.5
$Intl_Mins
34120.9
$CustServ_Calls
5209
$Intl_Plan
3656
$Vmail_Plan
4255
$Day_Calls
334752
$Day_Charge
101864.17
$Eve_Calls
333681
$Eve_Charge
56939.44
$Night_Calls
333659
$Night_Charge
30128.07
$Intl_Calls
14930
$Intl_Charge
9214.35
$State
90189
$Area_Code
1457129
In [22]:
#Mean
lapply(dataSet[numericalCols], FUN = mean)
$Account_Length
101.064806480648
$Vmail_Message
8.0990099009901
$Day_Mins
179.775097509751
$Eve_Mins
200.980348034803
$Night_Mins
200.87203720372
$Intl_Mins
10.2372937293729
$CustServ_Calls
1.56285628562856
$Intl_Plan
1.0969096909691
$Vmail_Plan
1.27662766276628
$Day_Calls
100.435643564356
$Day_Charge
30.5623072307231
$Eve_Calls
100.114311431143
$Eve_Charge
17.0835403540354
$Night_Calls
100.107710771077
$Night_Charge
9.03932493249325
$Intl_Calls
4.47944794479448
$Intl_Charge
2.76458145814581
$State
27.0594059405941
$Area_Code
437.182418241824
In [23]:
#median
lapply(dataSet[numericalCols], FUN = median)
$Account_Length
101
$Vmail_Message
0
$Day_Mins
179.4
$Eve_Mins
201.4
$Night_Mins
201.2
$Intl_Mins
10.3
$CustServ_Calls
1
$Intl_Plan
1
$Vmail_Plan
1
$Day_Calls
101
$Day_Charge
30.5
$Eve_Calls
100
$Eve_Charge
17.12
$Night_Calls
100
$Night_Charge
9.05
$Intl_Calls
4
$Intl_Charge
2.78
$State
27
$Area_Code
415
In [24]:
#Min
lapply(dataSet[numericalCols], FUN = min)
$Account_Length
1
$Vmail_Message
0
$Day_Mins
0
$Eve_Mins
0
$Night_Mins
23.2
$Intl_Mins
0
$CustServ_Calls
0
$Intl_Plan
1
$Vmail_Plan
1
$Day_Calls
0
$Day_Charge
0
$Eve_Calls
0
$Eve_Charge
0
$Night_Calls
33
$Night_Charge
1.04
$Intl_Calls
0
$Intl_Charge
0
$State
1
$Area_Code
408
In [25]:
#Max
lapply(dataSet[numericalCols], FUN = max)
$Account_Length
243
$Vmail_Message
51
$Day_Mins
350.8
$Eve_Mins
363.7
$Night_Mins
395
$Intl_Mins
20
$CustServ_Calls
9
$Intl_Plan
2
$Vmail_Plan
2
$Day_Calls
165
$Day_Charge
59.64
$Eve_Calls
170
$Eve_Charge
30.91
$Night_Calls
175
$Night_Charge
17.77
$Intl_Calls
20
$Intl_Charge
5.4
$State
51
$Area_Code
510
In [26]:
#Length
lapply(dataSet[numericalCols], FUN = length)
$Account_Length
3333
$Vmail_Message
3333
$Day_Mins
3333
$Eve_Mins
3333
$Night_Mins
3333
$Intl_Mins
3333
$CustServ_Calls
3333
$Intl_Plan
3333
$Vmail_Plan
3333
$Day_Calls
3333
$Day_Charge
3333
$Eve_Calls
3333
$Eve_Charge
3333
$Night_Calls
3333
$Night_Charge
3333
$Intl_Calls
3333
$Intl_Charge
3333
$State
3333
$Area_Code
3333

Finding statistics metrics with sapply function

In [27]:
# Sum
sapply(dataSet[numericalCols], FUN = sum)
Account_Length
336849
Vmail_Message
26994
Day_Mins
599190.4
Eve_Mins
669867.5
Night_Mins
669506.5
Intl_Mins
34120.9
CustServ_Calls
5209
Intl_Plan
3656
Vmail_Plan
4255
Day_Calls
334752
Day_Charge
101864.17
Eve_Calls
333681
Eve_Charge
56939.44
Night_Calls
333659
Night_Charge
30128.07
Intl_Calls
14930
Intl_Charge
9214.35
State
90189
Area_Code
1457129
In [28]:
# Mean
sapply(dataSet[numericalCols], FUN = mean)
Account_Length
101.064806480648
Vmail_Message
8.0990099009901
Day_Mins
179.775097509751
Eve_Mins
200.980348034803
Night_Mins
200.87203720372
Intl_Mins
10.2372937293729
CustServ_Calls
1.56285628562856
Intl_Plan
1.0969096909691
Vmail_Plan
1.27662766276628
Day_Calls
100.435643564356
Day_Charge
30.5623072307231
Eve_Calls
100.114311431143
Eve_Charge
17.0835403540354
Night_Calls
100.107710771077
Night_Charge
9.03932493249325
Intl_Calls
4.47944794479448
Intl_Charge
2.76458145814581
State
27.0594059405941
Area_Code
437.182418241824
In [29]:
# Median
sapply(dataSet[numericalCols], FUN = median)
Account_Length
101
Vmail_Message
0
Day_Mins
179.4
Eve_Mins
201.4
Night_Mins
201.2
Intl_Mins
10.3
CustServ_Calls
1
Intl_Plan
1
Vmail_Plan
1
Day_Calls
101
Day_Charge
30.5
Eve_Calls
100
Eve_Charge
17.12
Night_Calls
100
Night_Charge
9.05
Intl_Calls
4
Intl_Charge
2.78
State
27
Area_Code
415
In [30]:
# Min
sapply(dataSet[numericalCols], FUN = min)
Account_Length
1
Vmail_Message
0
Day_Mins
0
Eve_Mins
0
Night_Mins
23.2
Intl_Mins
0
CustServ_Calls
0
Intl_Plan
1
Vmail_Plan
1
Day_Calls
0
Day_Charge
0
Eve_Calls
0
Eve_Charge
0
Night_Calls
33
Night_Charge
1.04
Intl_Calls
0
Intl_Charge
0
State
1
Area_Code
408
In [31]:
# Max
sapply(dataSet[numericalCols], FUN = max)
Account_Length
243
Vmail_Message
51
Day_Mins
350.8
Eve_Mins
363.7
Night_Mins
395
Intl_Mins
20
CustServ_Calls
9
Intl_Plan
2
Vmail_Plan
2
Day_Calls
165
Day_Charge
59.64
Eve_Calls
170
Eve_Charge
30.91
Night_Calls
175
Night_Charge
17.77
Intl_Calls
20
Intl_Charge
5.4
State
51
Area_Code
510
In [32]:
# Length
sapply(dataSet[numericalCols], FUN = length)
Account_Length
3333
Vmail_Message
3333
Day_Mins
3333
Eve_Mins
3333
Night_Mins
3333
Intl_Mins
3333
CustServ_Calls
3333
Intl_Plan
3333
Vmail_Plan
3333
Day_Calls
3333
Day_Charge
3333
Eve_Calls
3333
Eve_Charge
3333
Night_Calls
3333
Night_Charge
3333
Intl_Calls
3333
Intl_Charge
3333
State
3333
Area_Code
3333

In the next few cells, you will find three different options on how to aggregate data.

In [33]:
# OPTION 1: (Using Aggregate FUNCTION - all variables together)
aggregate(dataSet[numericalCols], list(dataSet$Churn), summary)
A data.frame: 2 × 20
Group.1Account_LengthVmail_MessageDay_MinsEve_MinsNight_MinsIntl_MinsCustServ_CallsIntl_PlanVmail_PlanDay_CallsDay_ChargeEve_CallsEve_ChargeNight_CallsNight_ChargeIntl_CallsIntl_ChargeStateArea_Code
<fct><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]><dbl[,6]>
no 1, 73, 100, 100.7937, 127, 2430, 0, 0, 8.604561, 22, 510, 142.825, 177.2, 175.1758, 210.30, 315.6 0.0, 164.5, 199.6, 199.0433, 233.20, 361.823.2, 165.90, 200.25, 200.1332, 234.90, 395.00, 8.4, 10.2, 10.15888, 12.0, 18.90, 1, 1, 1.449825, 2, 81, 1, 1, 1.065263, 1, 21, 1, 1, 1.295439, 2, 20, 87.0, 100, 100.2832, 114.0, 1630, 24.2825, 30.12, 29.78042, 35.75, 53.65 0, 87, 100, 100.0386, 114, 1700.00, 13.980, 16.97, 16.91891, 19.820, 30.7533, 87, 100, 100.0582, 113, 1751.04, 7.470, 9.01, 9.006074, 10.570, 17.770, 3, 4, 4.532982, 6, 190.00, 2.27, 2.75, 2.743404, 3.24, 5.11, 14, 27, 27.01193, 40, 51408, 408, 415, 437.0747, 510, 510
yes1, 76, 103, 102.6646, 127, 2250, 0, 0, 5.115942, 0, 480, 153.250, 217.6, 206.9141, 265.95, 350.870.9, 177.1, 211.3, 212.4101, 249.45, 363.747.4, 171.25, 204.80, 205.2317, 239.85, 354.92, 8.8, 10.6, 10.70000, 12.8, 20.00, 1, 2, 2.229814, 4, 91, 1, 1, 1.283644, 2, 21, 1, 1, 1.165631, 1, 20, 87.5, 103, 101.3354, 116.5, 1650, 26.0550, 36.99, 35.17592, 45.21, 59.6448, 87, 101, 100.5611, 114, 1686.03, 15.055, 17.96, 18.05497, 21.205, 30.9149, 85, 100, 100.3996, 115, 1582.13, 7.705, 9.22, 9.235528, 10.795, 15.971, 2, 4, 4.163561, 5, 200.54, 2.38, 2.86, 2.889545, 3.46, 5.41, 17, 27, 27.33954, 39, 51408, 408, 415, 437.8178, 510, 510
In [34]:
# OPTION 2: (Using Aggregate FUNCTION - variables separately)
aggregate(dataSet$Intl_Mins, list(dataSet$Churn), summary)
aggregate(dataSet$Day_Mins, list(dataSet$Churn), summary)
aggregate(dataSet$Night_Mins, list(dataSet$Churn), summary)
A data.frame: 2 × 2
Group.1x
<fct><dbl[,6]>
no 0, 8.4, 10.2, 10.15888, 12.0, 18.9
yes2, 8.8, 10.6, 10.70000, 12.8, 20.0
A data.frame: 2 × 2
Group.1x
<fct><dbl[,6]>
no 0, 142.825, 177.2, 175.1758, 210.30, 315.6
yes0, 153.250, 217.6, 206.9141, 265.95, 350.8
A data.frame: 2 × 2
Group.1x
<fct><dbl[,6]>
no 23.2, 165.90, 200.25, 200.1332, 234.90, 395.0
yes47.4, 171.25, 204.80, 205.2317, 239.85, 354.9
In [35]:
# OPTION 3: (Using "by" FUNCTION instead of "Aggregate" FUNCTION)
by(dataSet$Intl_Mins, dataSet[8], FUN = summary)
by(dataSet$Day_Mins, dataSet[8], FUN = summary)
by(dataSet$Night_Mins, dataSet[8], FUN = summary)
Churn: no
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   0.00    8.40   10.20   10.16   12.00   18.90 
------------------------------------------------------------ 
Churn: yes
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    2.0     8.8    10.6    10.7    12.8    20.0 
Churn: no
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    0.0   142.8   177.2   175.2   210.3   315.6 
------------------------------------------------------------ 
Churn: yes
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    0.0   153.2   217.6   206.9   265.9   350.8 
Churn: no
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   23.2   165.9   200.2   200.1   234.9   395.0 
------------------------------------------------------------ 
Churn: yes
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   47.4   171.2   204.8   205.2   239.8   354.9 

Find out correlation

In [36]:
# Correlations/covariances among numeric variables 
library(Hmisc)
cor(dataSet[c(2,5,11,13,16,18)], use="complete.obs", method="kendall") 
cov(dataSet[c(2,5,11,13,16,18)], use="complete.obs")
Loading required package: survival


Attaching package: ‘survival’


The following object is masked from ‘package:caret’:

    cluster


Loading required package: Formula


Attaching package: ‘Hmisc’


The following objects are masked from ‘package:base’:

    format.pval, units


A matrix: 6 × 6 of type dbl
Vmail_MessageNight_MinsDay_CallsEve_CallsNight_ChargeIntl_Charge
Vmail_Message 1.000000000 0.003718463-0.009573189-5.382921e-03 0.003710434-1.263503e-03
Night_Mins 0.003718463 1.000000000 0.012550159 3.291091e-03 0.999625309-7.103399e-03
Day_Calls-0.009573189 0.012550159 1.000000000 9.253492e-03 0.012531632 1.038631e-02
Eve_Calls-0.005382921 0.003291091 0.009253492 1.000000e+00 0.003310838-9.536135e-05
Night_Charge 0.003710434 0.999625309 0.012531632 3.310838e-03 1.000000000-7.097366e-03
Intl_Charge-0.001263503-0.007103399 0.010386309-9.536135e-05-0.007097366 1.000000e+00
A matrix: 6 × 6 of type dbl
Vmail_MessageNight_MinsDay_CallsEve_CallsNight_ChargeIntl_Charge
Vmail_Message187.37134656 5.3174453 -2.6229779 -1.59925653 0.23873433 0.02975334
Night_Mins 5.317445292557.7140018 23.2812431 -2.10859729115.09955435-0.57867377
Day_Calls -2.62297790 23.2812431402.7681409 2.58373944 1.04716693 0.32775442
Eve_Calls -1.59925653 -2.1085973 2.5837394396.91099860 -0.09322113 0.13025644
Night_Charge 0.23873433 115.0995543 1.0471669 -0.09322113 5.17959717-0.02605168
Intl_Charge 0.02975334 -0.5786738 0.3277544 0.13025644 -0.02605168 0.56817315
In [37]:
# Correlations with significance levels
rcorr(as.matrix(dataSet[c(2,5,11,13,16,18)]), type="pearson")
              Vmail_Message Night_Mins Day_Calls Eve_Calls Night_Charge
Vmail_Message          1.00       0.01     -0.01     -0.01         0.01
Night_Mins             0.01       1.00      0.02      0.00         1.00
Day_Calls             -0.01       0.02      1.00      0.01         0.02
Eve_Calls             -0.01       0.00      0.01      1.00         0.00
Night_Charge           0.01       1.00      0.02      0.00         1.00
Intl_Charge            0.00      -0.02      0.02      0.01        -0.02
              Intl_Charge
Vmail_Message        0.00
Night_Mins          -0.02
Day_Calls            0.02
Eve_Calls            0.01
Night_Charge        -0.02
Intl_Charge          1.00

n= 3333 


P
              Vmail_Message Night_Mins Day_Calls Eve_Calls Night_Charge
Vmail_Message               0.6576     0.5816    0.7350    0.6583      
Night_Mins    0.6576                   0.1855    0.9039    0.0000      
Day_Calls     0.5816        0.1855               0.7092    0.1857      
Eve_Calls     0.7350        0.9039     0.7092              0.9056      
Night_Charge  0.6583        0.0000     0.1857    0.9056                
Intl_Charge   0.8678        0.3810     0.2111    0.6167    0.3808      
              Intl_Charge
Vmail_Message 0.8678     
Night_Mins    0.3810     
Day_Calls     0.2111     
Eve_Calls     0.6167     
Night_Charge  0.3808     
Intl_Charge              

5. Visualising DataSet

In [38]:
# Pie Chart from data 
mytable <- table(dataSet$Churn)
lbls <- paste(names(mytable), "\n", mytable, sep="")
pie(mytable, labels = lbls, col=rainbow(length(lbls)), 
    main="Pie Chart of Classes\n (with sample sizes)")
In [39]:
# Barplot of categorical data
par(mfrow=c(1,1))
barplot(table(dataSet$Churn), ylab = "Count", 
        col=c("darkblue","red"))
barplot(prop.table(table(dataSet$Churn)), ylab = "Proportion", 
        col=c("darkblue","red"))
barplot(table(dataSet$Churn), xlab = "Count", horiz = TRUE, 
        col=c("darkblue","red"))
barplot(prop.table(table(dataSet$Churn)), xlab = "Proportion", horiz = TRUE, 
        col=c("darkblue","red"))
In [40]:
# Scatterplot Matrices from the glus Package 
library(gclus)
dta <- dataSet[c(2,5,11,13,16,18)] # get data 
dta.r <- abs(cor(dta)) # get correlations
dta.col <- dmat.color(dta.r) # get colors
# reorder variables so those with highest correlation are closest to the diagonal
dta.o <- order.single(dta.r) 
cpairs(dta, dta.o, panel.colors=dta.col, gap=.5, 
       main="Variables Ordered and Colored by Correlation" )
Loading required package: cluster

Visualise correlations

In [41]:
corrgram(dataSet[c(2,5,11,13,16,18)], order=TRUE, lower.panel=panel.shade,
         upper.panel=panel.pie, text.panel=panel.txt, main=" ")
In [42]:
# More graphs on correlatios amaong data
# Using "Hmisc"
res2 <- rcorr(as.matrix(dataSet[,c(2,5,11,13,16,18)]))
# Extract the correlation coefficients
res2$r
# Extract p-values
res2$P
A matrix: 6 × 6 of type dbl
Vmail_MessageNight_MinsDay_CallsEve_CallsNight_ChargeIntl_Charge
Vmail_Message 1.000000000 0.007681136-0.009548068-0.005864351 0.007663290 0.002883658
Night_Mins 0.007681136 1.000000000 0.022937845-0.002092768 0.999999215-0.015179849
Day_Calls-0.009548068 0.022937845 1.000000000 0.006462114 0.022926638 0.021666095
Eve_Calls-0.005864351-0.002092768 0.006462114 1.000000000-0.002055984 0.008673858
Night_Charge 0.007663290 0.999999215 0.022926638-0.002055984 1.000000000-0.015186139
Intl_Charge 0.002883658-0.015179849 0.021666095 0.008673858-0.015186139 1.000000000
A matrix: 6 × 6 of type dbl
Vmail_MessageNight_MinsDay_CallsEve_CallsNight_ChargeIntl_Charge
Vmail_Message NA0.65755700.58160890.73503350.65830200.8678283
Night_Mins0.6575570 NA0.18552680.90386940.00000000.3809828
Day_Calls0.58160890.1855268 NA0.70919640.18574180.2111142
Eve_Calls0.73503350.90386940.7091964 NA0.90555110.6166654
Night_Charge0.65830200.00000000.18574180.9055511 NA0.3807855
Intl_Charge0.86782830.38098280.21111420.61666540.3807855 NA
In [43]:
# Using "corrplot"
library(corrplot)
library(RColorBrewer)
corrplot(res2$r, type = "upper", order = "hclust", col=brewer.pal(n=8, name="RdYlBu"),
         tl.col = "black", tl.srt = 45)
corrplot(res2$r, type = "lower", order = "hclust", col=brewer.pal(n=8, name="RdYlBu"),
         tl.col = "black", tl.srt = 45)
corrplot 0.84 loaded

In [44]:
# Using PerformanceAnalytics
library(PerformanceAnalytics)
data <- dataSet[, c(2,5,11,13,16,18)]
chart.Correlation(data, histogram=TRUE, pch=19)
Loading required package: xts

Loading required package: zoo


Attaching package: ‘zoo’


The following objects are masked from ‘package:base’:

    as.Date, as.Date.numeric



Attaching package: ‘PerformanceAnalytics’


The following object is masked from ‘package:graphics’:

    legend


In [45]:
# Using Colored Headmap 
col <- colorRampPalette(c("blue", "white", "red"))(20)
heatmap(x = res2$r, col = col, symm = TRUE)

We should notice that Night_Mins and Night_Charge have a strong, linear, positive relationship.

6. Pre-Processing of DataSet i.e. train (75%) : test (25%) split

In [46]:
train_test_index <- createDataPartition(dataSet$Churn, p=0.75, list=FALSE)
training_dataset <- dataSet[, c(1:20)][train_test_index,]
testing_dataset  <- dataSet[, c(1:20)][-train_test_index,]
In [47]:
dim(training_dataset)
dim(testing_dataset)
  1. 2501
  2. 20
  1. 832
  2. 20

7. Cross Validation and control parameter setup

In [48]:
control <- trainControl(method="repeatedcv", # repeatedcv / adaptive_cv
                        number=2, repeats = 2, 
                        verbose = TRUE, search = "grid",
                        allowParallel = TRUE)
metric <- "Accuracy"
tuneLength = 2

8. Algorithm : Naive Bayes, NB, DDA

In [50]:
names(getModelInfo())
  1. 'ada'
  2. 'AdaBag'
  3. 'AdaBoost.M1'
  4. 'adaboost'
  5. 'amdai'
  6. 'ANFIS'
  7. 'avNNet'
  8. 'awnb'
  9. 'awtan'
  10. 'bag'
  11. 'bagEarth'
  12. 'bagEarthGCV'
  13. 'bagFDA'
  14. 'bagFDAGCV'
  15. 'bam'
  16. 'bartMachine'
  17. 'bayesglm'
  18. 'binda'
  19. 'blackboost'
  20. 'blasso'
  21. 'blassoAveraged'
  22. 'bridge'
  23. 'brnn'
  24. 'BstLm'
  25. 'bstSm'
  26. 'bstTree'
  27. 'C5.0'
  28. 'C5.0Cost'
  29. 'C5.0Rules'
  30. 'C5.0Tree'
  31. 'cforest'
  32. 'chaid'
  33. 'CSimca'
  34. 'ctree'
  35. 'ctree2'
  36. 'cubist'
  37. 'dda'
  38. 'deepboost'
  39. 'DENFIS'
  40. 'dnn'
  41. 'dwdLinear'
  42. 'dwdPoly'
  43. 'dwdRadial'
  44. 'earth'
  45. 'elm'
  46. 'enet'
  47. 'evtree'
  48. 'extraTrees'
  49. 'fda'
  50. 'FH.GBML'
  51. 'FIR.DM'
  52. 'foba'
  53. 'FRBCS.CHI'
  54. 'FRBCS.W'
  55. 'FS.HGD'
  56. 'gam'
  57. 'gamboost'
  58. 'gamLoess'
  59. 'gamSpline'
  60. 'gaussprLinear'
  61. 'gaussprPoly'
  62. 'gaussprRadial'
  63. 'gbm_h2o'
  64. 'gbm'
  65. 'gcvEarth'
  66. 'GFS.FR.MOGUL'
  67. 'GFS.LT.RS'
  68. 'GFS.THRIFT'
  69. 'glm.nb'
  70. 'glm'
  71. 'glmboost'
  72. 'glmnet_h2o'
  73. 'glmnet'
  74. 'glmStepAIC'
  75. 'gpls'
  76. 'hda'
  77. 'hdda'
  78. 'hdrda'
  79. 'HYFIS'
  80. 'icr'
  81. 'J48'
  82. 'JRip'
  83. 'kernelpls'
  84. 'kknn'
  85. 'knn'
  86. 'krlsPoly'
  87. 'krlsRadial'
  88. 'lars'
  89. 'lars2'
  90. 'lasso'
  91. 'lda'
  92. 'lda2'
  93. 'leapBackward'
  94. 'leapForward'
  95. 'leapSeq'
  96. 'Linda'
  97. 'lm'
  98. 'lmStepAIC'
  99. 'LMT'
  100. 'loclda'
  101. 'logicBag'
  102. 'LogitBoost'
  103. 'logreg'
  104. 'lssvmLinear'
  105. 'lssvmPoly'
  106. 'lssvmRadial'
  107. 'lvq'
  108. 'M5'
  109. 'M5Rules'
  110. 'manb'
  111. 'mda'
  112. 'Mlda'
  113. 'mlp'
  114. 'mlpKerasDecay'
  115. 'mlpKerasDecayCost'
  116. 'mlpKerasDropout'
  117. 'mlpKerasDropoutCost'
  118. 'mlpML'
  119. 'mlpSGD'
  120. 'mlpWeightDecay'
  121. 'mlpWeightDecayML'
  122. 'monmlp'
  123. 'msaenet'
  124. 'multinom'
  125. 'mxnet'
  126. 'mxnetAdam'
  127. 'naive_bayes'
  128. 'nb'
  129. 'nbDiscrete'
  130. 'nbSearch'
  131. 'neuralnet'
  132. 'nnet'
  133. 'nnls'
  134. 'nodeHarvest'
  135. 'null'
  136. 'OneR'
  137. 'ordinalNet'
  138. 'ordinalRF'
  139. 'ORFlog'
  140. 'ORFpls'
  141. 'ORFridge'
  142. 'ORFsvm'
  143. 'ownn'
  144. 'pam'
  145. 'parRF'
  146. 'PART'
  147. 'partDSA'
  148. 'pcaNNet'
  149. 'pcr'
  150. 'pda'
  151. 'pda2'
  152. 'penalized'
  153. 'PenalizedLDA'
  154. 'plr'
  155. 'pls'
  156. 'plsRglm'
  157. 'polr'
  158. 'ppr'
  159. 'PRIM'
  160. 'protoclass'
  161. 'qda'
  162. 'QdaCov'
  163. 'qrf'
  164. 'qrnn'
  165. 'randomGLM'
  166. 'ranger'
  167. 'rbf'
  168. 'rbfDDA'
  169. 'Rborist'
  170. 'rda'
  171. 'regLogistic'
  172. 'relaxo'
  173. 'rf'
  174. 'rFerns'
  175. 'RFlda'
  176. 'rfRules'
  177. 'ridge'
  178. 'rlda'
  179. 'rlm'
  180. 'rmda'
  181. 'rocc'
  182. 'rotationForest'
  183. 'rotationForestCp'
  184. 'rpart'
  185. 'rpart1SE'
  186. 'rpart2'
  187. 'rpartCost'
  188. 'rpartScore'
  189. 'rqlasso'
  190. 'rqnc'
  191. 'RRF'
  192. 'RRFglobal'
  193. 'rrlda'
  194. 'RSimca'
  195. 'rvmLinear'
  196. 'rvmPoly'
  197. 'rvmRadial'
  198. 'SBC'
  199. 'sda'
  200. 'sdwd'
  201. 'simpls'
  202. 'SLAVE'
  203. 'slda'
  204. 'smda'
  205. 'snn'
  206. 'sparseLDA'
  207. 'spikeslab'
  208. 'spls'
  209. 'stepLDA'
  210. 'stepQDA'
  211. 'superpc'
  212. 'svmBoundrangeString'
  213. 'svmExpoString'
  214. 'svmLinear'
  215. 'svmLinear2'
  216. 'svmLinear3'
  217. 'svmLinearWeights'
  218. 'svmLinearWeights2'
  219. 'svmPoly'
  220. 'svmRadial'
  221. 'svmRadialCost'
  222. 'svmRadialSigma'
  223. 'svmRadialWeights'
  224. 'svmSpectrumString'
  225. 'tan'
  226. 'tanSearch'
  227. 'treebag'
  228. 'vbmpRadial'
  229. 'vglmAdjCat'
  230. 'vglmContRatio'
  231. 'vglmCumulative'
  232. 'widekernelpls'
  233. 'WM'
  234. 'wsrf'
  235. 'xgbDART'
  236. 'xgbLinear'
  237. 'xgbTree'
  238. 'xyf'
In [49]:
getModelInfo("naive_bayes"); getModelInfo("nb"); getModelInfo("dda");
$naive_bayes =
$label
'Naive Bayes'
$library
'naivebayes'
$loop
NULL
$type
'Classification'
$parameters
A data.frame: 3 × 3
parameterclasslabel
<chr><chr><chr>
laplace numericLaplace Correction
usekernellogicalDistribution Type
adjust numericBandwidth Adjustment
$grid
function (x, y, len = NULL, search = "grid") 
expand.grid(usekernel = c(TRUE, FALSE), laplace = 0, adjust = 1)
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    if (param$usekernel) {
        out <- naivebayes::naive_bayes(x, y, usekernel = TRUE, 
            laplace = param$laplace, adjust = param$adjust, ...)
    }
    else out <- naivebayes::naive_bayes(x, y, usekernel = FALSE, 
        laplace = param$laplace, ...)
    out
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata)
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    as.data.frame(predict(modelFit, newdata, type = "prob"), 
        stringsAsFactors = TRUE)
}
$predictors
function (x, ...) 
if (hasTerms(x)) predictors(x$terms) else names(x$tables)
$tags
'Bayesian Model'
$levels
function (x) 
x$levels
$sort
function (x) 
x[order(x[, 1]), ]
$awnb
$label
'Naive Bayes Classifier with Attribute Weighting'
$library
'bnclassify'
$type
'Classification'
$parameters
A data.frame: 1 × 3
parameterclasslabel
<chr><chr><chr>
smoothnumericSmoothing Parameter
$grid
function (x, y, len = NULL, search = "grid") 
{
    if (search == "grid") {
        out <- data.frame(smooth = 0:(len - 1))
    }
    else {
        out <- data.frame(smooth = runif(len, min = 0, max = 10))
    }
    out
}
$loop
NULL
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    dat <- if (is.data.frame(x)) 
        x
    else as.data.frame(x, stringsAsFactors = TRUE)
    dat$.outcome <- y
    struct <- bnclassify::nb(class = ".outcome", dataset = dat)
    args <- list(x = bnclassify::nb(".outcome", dataset = dat), 
        dataset = dat, smooth = param$smooth)
    dots <- list(...)
    args <- c(args, dots)
    do.call(bnclassify::lp, args)
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata)
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata, prob = TRUE)
}
$levels
function (x) 
x$obsLevels
$predictors
function (x, s = NULL, ...) 
x$xNames
$tags
  1. 'Bayesian Model'
  2. 'Categorical Predictors Only'
$sort
function (x) 
x[order(x[, 1]), ]
$glm.nb
$label
'Negative Binomial Generalized Linear Model'
$library
'MASS'
$loop
NULL
$type
'Regression'
$parameters
A data.frame: 1 × 3
parameterclasslabel
<chr><chr><chr>
linkcharacterLink Function
$grid
function (x, y, len = NULL, search = "grid") 
data.frame(link = c("log", "sqrt", "identity"))[1:min(len, 3), 
    , drop = FALSE]
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    dat <- if (is.data.frame(x)) 
        x
    else as.data.frame(x, stringsAsFactors = TRUE)
    dat$.outcome <- y
    theDots <- list(...)
    if (!is.null(wts)) 
        theDots$weights <- wts
    modelArgs <- c(list(formula = as.formula(".outcome ~ ."), 
        data = dat, link = as.character(param$link)), theDots)
    out <- do.call(getFromNamespace("glm.nb", "MASS"), modelArgs)
    out$call <- NULL
    out
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata, type = "response")
}
$prob
NULL
$varImp
function (object, ...) 
{
    values <- summary(object)$coef
    varImps <- abs(values[-1, grep("value$", colnames(values)), 
        drop = FALSE])
    out <- data.frame(varImps)
    colnames(out) <- "Overall"
    if (!is.null(names(varImps))) 
        rownames(out) <- names(varImps)
    out
}
$predictors
function (x, ...) 
predictors(x$terms)
$levels
NULL
$trim
function (x) 
{
    x$y = c()
    x$model = c()
    x$residuals = c()
    x$fitted.values = c()
    x$effects = c()
    x$qr$qr = c()
    x$linear.predictors = c()
    x$weights = c()
    x$prior.weights = c()
    x$data = c()
    x$family$variance = c()
    x$family$dev.resids = c()
    x$family$aic = c()
    x$family$validmu = c()
    x$family$simulate = c()
    attr(x$terms, ".Environment") = c()
    attr(x$formula, ".Environment") = c()
    x
}
$tags
  1. 'Generalized Linear Model'
  2. 'Accepts Case Weights'
$sort
function (x) 
x
$manb
$label
'Model Averaged Naive Bayes Classifier'
$library
'bnclassify'
$type
'Classification'
$parameters
A data.frame: 2 × 3
parameterclasslabel
<chr><chr><chr>
smoothnumericSmoothing Parameter
prior numericPrior Probability
$grid
function (x, y, len = NULL, search = "grid") 
{
    if (search == "grid") {
        out <- expand.grid(smooth = 0:(len - 1), prior = seq(0.1, 
            0.9, length = len))
    }
    else {
        out <- data.frame(smooth = runif(len, min = 0, max = 10), 
            prior = runif(len))
    }
    out$smooth[out$smooth <= 0] <- 0.05
    out
}
$loop
NULL
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    dat <- if (is.data.frame(x)) 
        x
    else as.data.frame(x, stringsAsFactors = TRUE)
    dat$.outcome <- y
    struct <- bnclassify::nb(class = ".outcome", dataset = dat)
    bnclassify::lp(struct, dat, smooth = param$smooth, manb_prior = param$prior, 
        ...)
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata)
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata, prob = TRUE)
}
$levels
function (x) 
x$obsLevels
$predictors
function (x, s = NULL, ...) 
x$xNames
$tags
  1. 'Bayesian Model'
  2. 'Categorical Predictors Only'
$sort
function (x) 
x[order(x[, 1]), ]
$nb
$label
'Naive Bayes'
$library
'klaR'
$loop
NULL
$type
'Classification'
$parameters
A data.frame: 3 × 3
parameterclasslabel
<chr><chr><chr>
fL numericLaplace Correction
usekernellogicalDistribution Type
adjust numericBandwidth Adjustment
$grid
function (x, y, len = NULL, search = "grid") 
expand.grid(usekernel = c(TRUE, FALSE), fL = 0, adjust = 1)
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    if (param$usekernel) {
        out <- klaR::NaiveBayes(x, y, usekernel = TRUE, fL = param$fL, 
            adjust = param$adjust, ...)
    }
    else out <- klaR::NaiveBayes(x, y, usekernel = FALSE, fL = param$fL, 
        ...)
    out
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata)$class
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata, type = "raw")$posterior
}
$predictors
function (x, ...) 
if (hasTerms(x)) predictors(x$terms) else x$varnames
$tags
'Bayesian Model'
$levels
function (x) 
x$levels
$sort
function (x) 
x[order(x[, 1]), ]
$nbDiscrete
$label
'Naive Bayes Classifier'
$library
'bnclassify'
$type
'Classification'
$parameters
A data.frame: 1 × 3
parameterclasslabel
<chr><chr><chr>
smoothnumericSmoothing Parameter
$grid
function (x, y, len = NULL, search = "grid") 
{
    if (search == "grid") {
        out <- data.frame(smooth = 0:(len - 1))
    }
    else {
        out <- data.frame(smooth = runif(len, min = 0, max = 10))
    }
    out
}
$loop
NULL
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    dat <- if (is.data.frame(x)) 
        x
    else as.data.frame(x, stringsAsFactors = TRUE)
    dat$.outcome <- y
    bnclassify::bnc("nb", class = ".outcome", dataset = dat, 
        smooth = param$smooth, ...)
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata)
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata, prob = TRUE)
}
$levels
function (x) 
x$obsLevels
$predictors
function (x, s = NULL, ...) 
x$xNames
$tags
  1. 'Bayesian Model'
  2. 'Categorical Predictors Only'
$sort
function (x) 
x[order(x[, 1]), ]
$nbSearch
$label
'Semi-Naive Structure Learner Wrapper'
$library
'bnclassify'
$type
'Classification'
$parameters
A data.frame: 5 × 3
parameterclasslabel
<chr><chr><chr>
k numeric #Folds
epsilon numeric Minimum Absolute Improvement
smooth numeric Smoothing Parameter
final_smoothnumeric Final Smoothing Parameter
direction characterSearch Direction
$grid
function (x, y, len = NULL, search = "grid") 
{
    if (search == "grid") {
        out <- expand.grid(k = 10, epsilon = 0.01, smooth = 0.01, 
            final_smooth = 1, direction = c("forward", "backwards"))
    }
    else {
        out <- data.frame(k = sample(3:10, size = len, replace = TRUE), 
            epsilon = runif(len, min = 0, max = 0.05), smooth = runif(len, 
                min = 0, max = 10), final_smooth = runif(len, 
                min = 0, max = 10), direction = sample(c("forward", 
                "backwards"), size = len, replace = TRUE))
    }
    out
}
$loop
NULL
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    dat <- if (is.data.frame(x)) 
        x
    else as.data.frame(x, stringsAsFactors = TRUE)
    dat$.outcome <- y
    if (param$direction == "forward") {
        struct <- bnclassify::fssj(class = ".outcome", dataset = dat, 
            k = param$k, epsilon = param$epsilon, smooth = param$smooth)
    }
    else {
        struct <- bnclassify::bsej(class = ".outcome", dataset = dat, 
            k = param$k, epsilon = param$epsilon, smooth = param$smooth)
    }
    bnclassify::lp(struct, dat, smooth = param$final_smooth, 
        ...)
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata)
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    if (!is.data.frame(newdata)) 
        newdata <- as.data.frame(newdata, stringsAsFactors = TRUE)
    predict(modelFit, newdata, prob = TRUE)
}
$levels
function (x) 
x$obsLevels
$predictors
function (x, s = NULL, ...) 
x$xNames
$tags
  1. 'Bayesian Model'
  2. 'Categorical Predictors Only'
$sort
function (x) 
x[order(x[, 1]), ]
$dda
$label
'Diagonal Discriminant Analysis'
$library
'sparsediscrim'
$loop
NULL
$type
'Classification'
$parameters
A data.frame: 2 × 3
parameterclasslabel
<chr><chr><chr>
model characterModel
shrinkagecharacterShrinkage Type
$grid
function (x, y, len = NULL, search = "grid") 
data.frame(model = rep(c("Linear", "Quadratic"), each = 3), shrinkage = rep(c("None", 
    "Variance", "Mean"), 2))
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    if (param$model == "Linear") {
        if (param$shrinkage == "None") {
            out <- sparsediscrim::dlda(x, y, ...)
        }
        else {
            if (param$shrinkage == "Variance") {
                out <- sparsediscrim::sdlda(x, y, ...)
            }
            else out <- sparsediscrim::smdlda(x, y, ...)
        }
    }
    else {
        if (param$shrinkage == "None") {
            out <- sparsediscrim::dqda(x, y, ...)
        }
        else {
            if (param$shrinkage == "Variance") {
                out <- sparsediscrim::sdqda(x, y, ...)
            }
            else out <- sparsediscrim::smdqda(x, y, ...)
        }
    }
    out
}
$predict
function (modelFit, newdata, submodels = NULL) 
predict(modelFit, newdata)$class
$prob
function (modelFit, newdata, submodels = NULL) 
{
    out <- predict(modelFit, newdata)$scores
    as.data.frame(t(apply(out, 2, function(x) exp(-x)/sum(exp(-x)))), 
        stringsAsFactors = TRUE)
}
$predictors
function (x, ...) 
if (hasTerms(x)) predictors(x$terms) else colnames(x$means)
$tags
  1. 'Discriminant Analysis'
  2. 'Linear Classifier'
  3. 'Polynomial Model'
  4. 'Regularization'
$levels
function (x) 
names(x$prior)
$sort
function (x) 
x
$hdda
$label
'High Dimensional Discriminant Analysis'
$library
'HDclassif'
$loop
NULL
$type
'Classification'
$parameters
A data.frame: 2 × 3
parameterclasslabel
<chr><chr><chr>
thresholdcharacterThreshold
model numeric Model Type
$grid
function (x, y, len = NULL, search = "grid") 
{
    mods <- c("AkjBkQkDk", "AkBkQkDk", "ABkQkDk", "AkjBQkDk", 
        "AkBQkDk", "ABQkDk", "AkjBkQkD", "AkBkQkD", "ABkQkD", 
        "AkjBQkD", "AkBQkD", "ABQkD", "AjBQD", "ABQD")
    if (search == "grid") {
        out <- expand.grid(model = c("all"), threshold = seq(0.05, 
            0.3, length = len))
    }
    else {
        out <- data.frame(model = sample(mods, size = len, replace = TRUE), 
            threshold = runif(len, min = 0, max = 1))
    }
    out
}
$fit
function (x, y, wts, param, lev, last, classProbs, ...) 
{
    HDclassif::hdda(x, y, model = as.character(param$model), 
        threshold = param$threshold, ...)
}
$predict
function (modelFit, newdata, submodels = NULL) 
{
    as.character(predict(modelFit, newdata)$class)
}
$prob
function (modelFit, newdata, submodels = NULL) 
{
    data.frame(unclass(predict(modelFit, newdata)$posterior))
}
$levels
function (x) 
x$obsLevels
$tags
  1. 'Discriminant Analysis'
  2. 'Linear Classifier'
$sort
function (x) 
x[order(-x$threshold), ]

1) Training - without explicit parameter tuning / using default

In [52]:
# naive_bayes
fit.naive_bayes <- caret::train(Churn~., data=training_dataset, method="naive_bayes", 
                                metric=metric, 
                                trControl=control,
                                verbose = TRUE
)
print(fit.naive_bayes)
Aggregating results
Selecting tuning parameters
Fitting laplace = 0, usekernel = TRUE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

No pre-processing
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1251, 1250 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8702523  0.4775787
   TRUE      0.8724497  0.2517298

Tuning parameter 'laplace' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were laplace = 0, usekernel = TRUE
 and adjust = 1.
In [53]:
# nb
fit.nb <- caret::train(Churn~., data=training_dataset, method="nb", 
                       metric=metric, 
                       trControl=control,
                       verbose = TRUE
)
print(fit.nb)
Aggregating results
Selecting tuning parameters
Fitting fL = 0, usekernel = FALSE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

No pre-processing
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1251, 1250 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8688494  0.4710194
   TRUE      0.8684531  0.1664339

Tuning parameter 'fL' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were fL = 0, usekernel = FALSE and adjust
 = 1.
In [55]:
# dda
fit.dda <- caret::train(Churn~., data=training_dataset, method="dda", 
                        metric=metric, 
                        trControl=control,
                        verbose = TRUE
)
print(fit.dda)
Aggregating results
Selecting tuning parameters
Fitting model = Quadratic, shrinkage = Mean on full training set
Diagonal Discriminant Analysis 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

No pre-processing
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1250, 1251 
Resampling results across tuning parameters:

  model      shrinkage  Accuracy   Kappa    
  Linear     Mean       0.5825714  0.1772734
  Linear     None       0.5825714  0.1772734
  Linear     Variance         NaN        NaN
  Quadratic  Mean       0.6797252  0.2840468
  Quadratic  None       0.6797252  0.2840468
  Quadratic  Variance         NaN        NaN

Accuracy was used to select the optimal model using the largest value.
The final values used for the model were model = Quadratic and shrinkage = Mean.

2) Training - with explicit parameter tuning using preProcess method

In [56]:
# naive_bayes
fit.naive_bayes_preProc <- caret::train(Churn~., data=training_dataset, method="naive_bayes", 
                                        metric=metric, 
                                        trControl=control,
                                        preProc=c("center", "scale"), 
                                        verbose = TRUE
)
print(fit.naive_bayes_preProc)
Aggregating results
Selecting tuning parameters
Fitting laplace = 0, usekernel = FALSE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1251, 1250, 1251, 1250 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8728489  0.4887380
   TRUE      0.8714537  0.2154238

Tuning parameter 'laplace' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were laplace = 0, usekernel = FALSE
 and adjust = 1.
In [57]:
# nb
fit.nb_preProc <- caret::train(Churn~., data=training_dataset, method="nb", 
                               metric=metric, 
                               trControl=control,
                               preProc=c("center", "scale"), 
                               verbose = TRUE
)
print(fit.nb_preProc)
Aggregating results
Selecting tuning parameters
Fitting fL = 0, usekernel = TRUE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1250, 1251 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8686505  0.4677752
   TRUE      0.8690536  0.2077854

Tuning parameter 'fL' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were fL = 0, usekernel = TRUE and adjust
 = 1.
In [58]:
# dda
fit.dda_preProc <- caret::train(Churn~., data=training_dataset, method="dda", 
                                metric=metric, 
                                trControl=control,
                                preProc=c("center", "scale"), 
                                verbose = TRUE
)
print(fit.dda_preProc)
Aggregating results
Selecting tuning parameters
Fitting model = Quadratic, shrinkage = None on full training set
Diagonal Discriminant Analysis 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1251, 1250, 1250, 1251 
Resampling results across tuning parameters:

  model      shrinkage  Accuracy   Kappa    
  Linear     Mean       0.5665682  0.1672779
  Linear     None       0.5885615  0.1814163
  Linear     Variance         NaN        NaN
  Quadratic  Mean       0.6719325  0.2728773
  Quadratic  None       0.6753314  0.2768144
  Quadratic  Variance         NaN        NaN

Accuracy was used to select the optimal model using the largest value.
The final values used for the model were model = Quadratic and shrinkage = None.

3) Training - with explicit parameter tuning using preProcess method & Automatic Grid i.e. tuneLength

In [59]:
# naive_bayes
fit.naive_bayes_automaticGrid <- caret::train(Churn~., data=training_dataset, method="naive_bayes", 
                                              metric=metric, 
                                              trControl=control,
                                              preProc=c("center", "scale"), 
                                              tuneLength = tuneLength,
                                              verbose = TRUE
)
print(fit.naive_bayes_automaticGrid)
Aggregating results
Selecting tuning parameters
Fitting laplace = 0, usekernel = FALSE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1251, 1250 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8710513  0.4818473
   TRUE      0.8696560  0.1915383

Tuning parameter 'laplace' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were laplace = 0, usekernel = FALSE
 and adjust = 1.
In [60]:
# nb
fit.nb_automaticGrid <- caret::train(Churn~., data=training_dataset, method="nb", 
                                     metric=metric, 
                                     trControl=control,
                                     preProc=c("center", "scale"), 
                                     tuneLength = tuneLength,
                                     verbose = TRUE
)
print(fit.nb_automaticGrid)
Aggregating results
Selecting tuning parameters
Fitting fL = 0, usekernel = TRUE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1250, 1251 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8664563  0.4535703
   TRUE      0.8700534  0.1983141

Tuning parameter 'fL' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were fL = 0, usekernel = TRUE and adjust
 = 1.
In [61]:
# dda
fit.dda_automaticGrid <- caret::train(Churn~., data=training_dataset, method="dda", 
                                      metric=metric, 
                                      trControl=control,
                                      preProc=c("center", "scale"), 
                                      tuneLength = tuneLength,
                                      verbose = TRUE
)
print(fit.dda_automaticGrid)
Aggregating results
Selecting tuning parameters
Fitting model = Quadratic, shrinkage = None on full training set
Diagonal Discriminant Analysis 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1251, 1250, 1251, 1250 
Resampling results across tuning parameters:

  model      shrinkage  Accuracy   Kappa    
  Linear     Mean       0.5689703  0.1697918
  Linear     None       0.5939626  0.1855654
  Linear     Variance         NaN        NaN
  Quadratic  Mean       0.6781268  0.2783895
  Quadratic  None       0.6813255  0.2808640
  Quadratic  Variance         NaN        NaN

Accuracy was used to select the optimal model using the largest value.
The final values used for the model were model = Quadratic and shrinkage = None.

4) Training - with explicit parameter tuning using preProcess method & Manual Grid i.e. tuneGrid

In [62]:
# naive_bayes
grid <- expand.grid(usekernel  = c("FALSE","TRUE"),
                    laplace    = c(seq(from = 1, to = 10, by = 1)),
                    adjust    = c(seq(from = 1, to = 10, by = 1))
)
fit.naive_bayes_manualGrid <- caret::train(Churn~., data=training_dataset, method="naive_bayes", 
                                           metric=metric, 
                                           trControl=control,
                                           preProc=c("center", "scale"), 
                                           tuneGrid = grid,
                                           verbose = TRUE
)
print(fit.naive_bayes_manualGrid)
plot(fit.naive_bayes_manualGrid)
Aggregating results
Selecting tuning parameters
Fitting laplace = 1, usekernel = FALSE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1251, 1250, 1250, 1251 
Resampling results across tuning parameters:

  usekernel  laplace  adjust  Accuracy   Kappa      
  FALSE       1        1      0.8736507  0.246338029
  FALSE       1        2      0.8722507  0.226088169
  FALSE       1        3      0.8658536  0.146195985
  FALSE       1        4      0.8590560  0.062806827
  FALSE       1        5      0.8560579  0.019523955
  FALSE       1        6      0.8554579  0.007012040
  FALSE       1        7      0.8552580  0.004691657
  FALSE       1        8      0.8548582  0.000000000
  FALSE       1        9      0.8548582  0.000000000
  FALSE       1       10      0.8548582  0.000000000
  FALSE       2        1      0.8736507  0.246338029
  FALSE       2        2      0.8722507  0.226088169
  FALSE       2        3      0.8658536  0.146195985
  FALSE       2        4      0.8590560  0.062806827
  FALSE       2        5      0.8560579  0.019523955
  FALSE       2        6      0.8554579  0.007012040
  FALSE       2        7      0.8552580  0.004691657
  FALSE       2        8      0.8548582  0.000000000
  FALSE       2        9      0.8548582  0.000000000
  FALSE       2       10      0.8548582  0.000000000
  FALSE       3        1      0.8736507  0.246338029
  FALSE       3        2      0.8722507  0.226088169
  FALSE       3        3      0.8658536  0.146195985
  FALSE       3        4      0.8590560  0.062806827
  FALSE       3        5      0.8560579  0.019523955
  FALSE       3        6      0.8554579  0.007012040
  FALSE       3        7      0.8552580  0.004691657
  FALSE       3        8      0.8548582  0.000000000
  FALSE       3        9      0.8548582  0.000000000
  FALSE       3       10      0.8548582  0.000000000
  FALSE       4        1      0.8736507  0.246338029
  FALSE       4        2      0.8722507  0.226088169
  FALSE       4        3      0.8658536  0.146195985
  FALSE       4        4      0.8590560  0.062806827
  FALSE       4        5      0.8560579  0.019523955
  FALSE       4        6      0.8554579  0.007012040
  FALSE       4        7      0.8552580  0.004691657
  FALSE       4        8      0.8548582  0.000000000
  FALSE       4        9      0.8548582  0.000000000
  FALSE       4       10      0.8548582  0.000000000
  FALSE       5        1      0.8736507  0.246338029
  FALSE       5        2      0.8722507  0.226088169
  FALSE       5        3      0.8658536  0.146195985
  FALSE       5        4      0.8590560  0.062806827
  FALSE       5        5      0.8560579  0.019523955
  FALSE       5        6      0.8554579  0.007012040
  FALSE       5        7      0.8552580  0.004691657
  FALSE       5        8      0.8548582  0.000000000
  FALSE       5        9      0.8548582  0.000000000
  FALSE       5       10      0.8548582  0.000000000
  FALSE       6        1      0.8736507  0.246338029
  FALSE       6        2      0.8722507  0.226088169
  FALSE       6        3      0.8658536  0.146195985
  FALSE       6        4      0.8590560  0.062806827
  FALSE       6        5      0.8560579  0.019523955
  FALSE       6        6      0.8554579  0.007012040
  FALSE       6        7      0.8552580  0.004691657
  FALSE       6        8      0.8548582  0.000000000
  FALSE       6        9      0.8548582  0.000000000
  FALSE       6       10      0.8548582  0.000000000
  FALSE       7        1      0.8736507  0.246338029
  FALSE       7        2      0.8722507  0.226088169
  FALSE       7        3      0.8658536  0.146195985
  FALSE       7        4      0.8590560  0.062806827
  FALSE       7        5      0.8560579  0.019523955
  FALSE       7        6      0.8554579  0.007012040
  FALSE       7        7      0.8552580  0.004691657
  FALSE       7        8      0.8548582  0.000000000
  FALSE       7        9      0.8548582  0.000000000
  FALSE       7       10      0.8548582  0.000000000
  FALSE       8        1      0.8736507  0.246338029
  FALSE       8        2      0.8722507  0.226088169
  FALSE       8        3      0.8658536  0.146195985
  FALSE       8        4      0.8590560  0.062806827
  FALSE       8        5      0.8560579  0.019523955
  FALSE       8        6      0.8554579  0.007012040
  FALSE       8        7      0.8552580  0.004691657
  FALSE       8        8      0.8548582  0.000000000
  FALSE       8        9      0.8548582  0.000000000
  FALSE       8       10      0.8548582  0.000000000
  FALSE       9        1      0.8736507  0.246338029
  FALSE       9        2      0.8722507  0.226088169
  FALSE       9        3      0.8658536  0.146195985
  FALSE       9        4      0.8590560  0.062806827
  FALSE       9        5      0.8560579  0.019523955
  FALSE       9        6      0.8554579  0.007012040
  FALSE       9        7      0.8552580  0.004691657
  FALSE       9        8      0.8548582  0.000000000
  FALSE       9        9      0.8548582  0.000000000
  FALSE       9       10      0.8548582  0.000000000
  FALSE      10        1      0.8736507  0.246338029
  FALSE      10        2      0.8722507  0.226088169
  FALSE      10        3      0.8658536  0.146195985
  FALSE      10        4      0.8590560  0.062806827
  FALSE      10        5      0.8560579  0.019523955
  FALSE      10        6      0.8554579  0.007012040
  FALSE      10        7      0.8552580  0.004691657
  FALSE      10        8      0.8548582  0.000000000
  FALSE      10        9      0.8548582  0.000000000
  FALSE      10       10      0.8548582  0.000000000
  TRUE        1        1      0.8736507  0.246338029
  TRUE        1        2      0.8722507  0.226088169
  TRUE        1        3      0.8658536  0.146195985
  TRUE        1        4      0.8590560  0.062806827
  TRUE        1        5      0.8560579  0.019523955
  TRUE        1        6      0.8554579  0.007012040
  TRUE        1        7      0.8552580  0.004691657
  TRUE        1        8      0.8548582  0.000000000
  TRUE        1        9      0.8548582  0.000000000
  TRUE        1       10      0.8548582  0.000000000
  TRUE        2        1      0.8736507  0.246338029
  TRUE        2        2      0.8722507  0.226088169
  TRUE        2        3      0.8658536  0.146195985
  TRUE        2        4      0.8590560  0.062806827
  TRUE        2        5      0.8560579  0.019523955
  TRUE        2        6      0.8554579  0.007012040
  TRUE        2        7      0.8552580  0.004691657
  TRUE        2        8      0.8548582  0.000000000
  TRUE        2        9      0.8548582  0.000000000
  TRUE        2       10      0.8548582  0.000000000
  TRUE        3        1      0.8736507  0.246338029
  TRUE        3        2      0.8722507  0.226088169
  TRUE        3        3      0.8658536  0.146195985
  TRUE        3        4      0.8590560  0.062806827
  TRUE        3        5      0.8560579  0.019523955
  TRUE        3        6      0.8554579  0.007012040
  TRUE        3        7      0.8552580  0.004691657
  TRUE        3        8      0.8548582  0.000000000
  TRUE        3        9      0.8548582  0.000000000
  TRUE        3       10      0.8548582  0.000000000
  TRUE        4        1      0.8736507  0.246338029
  TRUE        4        2      0.8722507  0.226088169
  TRUE        4        3      0.8658536  0.146195985
  TRUE        4        4      0.8590560  0.062806827
  TRUE        4        5      0.8560579  0.019523955
  TRUE        4        6      0.8554579  0.007012040
  TRUE        4        7      0.8552580  0.004691657
  TRUE        4        8      0.8548582  0.000000000
  TRUE        4        9      0.8548582  0.000000000
  TRUE        4       10      0.8548582  0.000000000
  TRUE        5        1      0.8736507  0.246338029
  TRUE        5        2      0.8722507  0.226088169
  TRUE        5        3      0.8658536  0.146195985
  TRUE        5        4      0.8590560  0.062806827
  TRUE        5        5      0.8560579  0.019523955
  TRUE        5        6      0.8554579  0.007012040
  TRUE        5        7      0.8552580  0.004691657
  TRUE        5        8      0.8548582  0.000000000
  TRUE        5        9      0.8548582  0.000000000
  TRUE        5       10      0.8548582  0.000000000
  TRUE        6        1      0.8736507  0.246338029
  TRUE        6        2      0.8722507  0.226088169
  TRUE        6        3      0.8658536  0.146195985
  TRUE        6        4      0.8590560  0.062806827
  TRUE        6        5      0.8560579  0.019523955
  TRUE        6        6      0.8554579  0.007012040
  TRUE        6        7      0.8552580  0.004691657
  TRUE        6        8      0.8548582  0.000000000
  TRUE        6        9      0.8548582  0.000000000
  TRUE        6       10      0.8548582  0.000000000
  TRUE        7        1      0.8736507  0.246338029
  TRUE        7        2      0.8722507  0.226088169
  TRUE        7        3      0.8658536  0.146195985
  TRUE        7        4      0.8590560  0.062806827
  TRUE        7        5      0.8560579  0.019523955
  TRUE        7        6      0.8554579  0.007012040
  TRUE        7        7      0.8552580  0.004691657
  TRUE        7        8      0.8548582  0.000000000
  TRUE        7        9      0.8548582  0.000000000
  TRUE        7       10      0.8548582  0.000000000
  TRUE        8        1      0.8736507  0.246338029
  TRUE        8        2      0.8722507  0.226088169
  TRUE        8        3      0.8658536  0.146195985
  TRUE        8        4      0.8590560  0.062806827
  TRUE        8        5      0.8560579  0.019523955
  TRUE        8        6      0.8554579  0.007012040
  TRUE        8        7      0.8552580  0.004691657
  TRUE        8        8      0.8548582  0.000000000
  TRUE        8        9      0.8548582  0.000000000
  TRUE        8       10      0.8548582  0.000000000
  TRUE        9        1      0.8736507  0.246338029
  TRUE        9        2      0.8722507  0.226088169
  TRUE        9        3      0.8658536  0.146195985
  TRUE        9        4      0.8590560  0.062806827
  TRUE        9        5      0.8560579  0.019523955
  TRUE        9        6      0.8554579  0.007012040
  TRUE        9        7      0.8552580  0.004691657
  TRUE        9        8      0.8548582  0.000000000
  TRUE        9        9      0.8548582  0.000000000
  TRUE        9       10      0.8548582  0.000000000
  TRUE       10        1      0.8736507  0.246338029
  TRUE       10        2      0.8722507  0.226088169
  TRUE       10        3      0.8658536  0.146195985
  TRUE       10        4      0.8590560  0.062806827
  TRUE       10        5      0.8560579  0.019523955
  TRUE       10        6      0.8554579  0.007012040
  TRUE       10        7      0.8552580  0.004691657
  TRUE       10        8      0.8548582  0.000000000
  TRUE       10        9      0.8548582  0.000000000
  TRUE       10       10      0.8548582  0.000000000

Accuracy was used to select the optimal model using the largest value.
The final values used for the model were laplace = 1, usekernel = FALSE
 and adjust = 1.
In [65]:
# nb
grid <- expand.grid(usekernel  = c("FALSE","TRUE"),
                    fL    = c(seq(from = 1, to = 10, by = 3)),
                    adjust    = c(seq(from = 1, to = 10, by = 3))
)
fit.nb_manualGrid <- caret::train(Churn~., data=training_dataset, method="nb", 
                                  metric=metric, 
                                  trControl=control,
                                  preProc=c("center", "scale"), 
                                  tuneGrid = grid,
                                  verbose = TRUE
)
print(fit.nb_manualGrid)
Aggregating results
Selecting tuning parameters
Fitting fL = 1, usekernel = FALSE, adjust = 1 on full training set
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1250, 1251 
Resampling results across tuning parameters:

  usekernel  fL  adjust  Accuracy   Kappa      
  FALSE       1   1      0.8734513  0.243668211
  FALSE       1   4      0.8576577  0.040826832
  FALSE       1   7      0.8552582  0.004688062
  FALSE       1  10      0.8548582  0.000000000
  FALSE       4   1      0.8734513  0.243668211
  FALSE       4   4      0.8576577  0.040826832
  FALSE       4   7      0.8552582  0.004688062
  FALSE       4  10      0.8548582  0.000000000
  FALSE       7   1      0.8734513  0.243668211
  FALSE       7   4      0.8576577  0.040826832
  FALSE       7   7      0.8552582  0.004688062
  FALSE       7  10      0.8548582  0.000000000
  FALSE      10   1      0.8734513  0.243668211
  FALSE      10   4      0.8576577  0.040826832
  FALSE      10   7      0.8552582  0.004688062
  FALSE      10  10      0.8548582  0.000000000
  TRUE        1   1      0.8734513  0.243668211
  TRUE        1   4      0.8576577  0.040826832
  TRUE        1   7      0.8552582  0.004688062
  TRUE        1  10      0.8548582  0.000000000
  TRUE        4   1      0.8734513  0.243668211
  TRUE        4   4      0.8576577  0.040826832
  TRUE        4   7      0.8552582  0.004688062
  TRUE        4  10      0.8548582  0.000000000
  TRUE        7   1      0.8734513  0.243668211
  TRUE        7   4      0.8576577  0.040826832
  TRUE        7   7      0.8552582  0.004688062
  TRUE        7  10      0.8548582  0.000000000
  TRUE       10   1      0.8734513  0.243668211
  TRUE       10   4      0.8576577  0.040826832
  TRUE       10   7      0.8552582  0.004688062
  TRUE       10  10      0.8548582  0.000000000

Accuracy was used to select the optimal model using the largest value.
The final values used for the model were fL = 1, usekernel = FALSE and adjust
 = 1.
In [66]:
# dda
grid <- expand.grid(model     = c("Linear","Quadratic"),
                    shrinkage = c("Mean", "None", "Variance")
)
fit.dda_manualGrid <- caret::train(Churn~., data=training_dataset, method="dda", 
                                   metric=metric, 
                                   trControl=control,
                                   preProc=c("center", "scale"), 
                                   tuneGrid = grid,
                                   verbose = TRUE
)
print(fit.dda_manualGrid)
plot(fit.dda_manualGrid)
Aggregating results
Selecting tuning parameters
Fitting model = Quadratic, shrinkage = None on full training set
Diagonal Discriminant Analysis 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1251, 1250, 1251, 1250 
Resampling results across tuning parameters:

  model      shrinkage  Accuracy   Kappa    
  Linear     Mean       0.5671757  0.1694759
  Linear     None       0.5903669  0.1833374
  Linear     Variance         NaN        NaN
  Quadratic  Mean       0.6761412  0.2801548
  Quadratic  None       0.6781415  0.2816168
  Quadratic  Variance         NaN        NaN

Accuracy was used to select the optimal model using the largest value.
The final values used for the model were model = Quadratic and shrinkage = None.

Collect the results of trained models

In [67]:
results <- resamples(list(      trained_Model_1  = fit.naive_bayes
                                , trained_Model_2  = fit.nb
                                #, trained_Model_3  = fit.dda
                                
                                , trained_Model_4  = fit.naive_bayes_preProc
                                , trained_Model_5  = fit.nb_preProc
                                #, trained_Model_6  = fit.dda_preProc
                                
                                , trained_Model_7  = fit.naive_bayes_automaticGrid
                                , trained_Model_8  = fit.nb_automaticGrid
                                #, trained_Model_9  = fit.dda_automaticGrid
                                
                                , trained_Model_10 = fit.naive_bayes_manualGrid
                                , trained_Model_11 = fit.nb_manualGrid
                                #, trained_Model_12 = fit.dda_manualGrid
))

Summarize the fitted models

In [68]:
summary(results)
Call:
summary.resamples(object = results)

Models: trained_Model_1, trained_Model_2, trained_Model_4, trained_Model_5, trained_Model_7, trained_Model_8, trained_Model_10, trained_Model_11 
Number of resamples: 4 

Accuracy 
                      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
trained_Model_1  0.8648000 0.8678787 0.8712524 0.8724497 0.8758235 0.8824940
trained_Model_2  0.8592000 0.8622000 0.8696496 0.8688494 0.8762990 0.8768985
trained_Model_4  0.8672000 0.8684000 0.8732489 0.8728489 0.8776978 0.8776978
trained_Model_5  0.8601119 0.8672280 0.8708512 0.8690536 0.8726767 0.8744000
trained_Model_7  0.8688000 0.8688787 0.8704524 0.8710513 0.8726251 0.8745004
trained_Model_8  0.8625100 0.8678275 0.8700518 0.8700534 0.8722777 0.8776000
trained_Model_10 0.8616000 0.8634815 0.8733014 0.8736507 0.8834705 0.8864000
trained_Model_11 0.8688000 0.8706772 0.8717026 0.8734513 0.8744767 0.8816000
                 NA's
trained_Model_1     0
trained_Model_2     0
trained_Model_4     0
trained_Model_5     0
trained_Model_7     0
trained_Model_8     0
trained_Model_10    0
trained_Model_11    0

Kappa 
                       Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
trained_Model_1  0.10829612 0.2092886 0.2562885 0.2517298 0.2987297 0.3860461
trained_Model_2  0.43149223 0.4537303 0.4705059 0.4710194 0.4877950 0.5115734
trained_Model_4  0.46534664 0.4732033 0.4879770 0.4887380 0.5035118 0.5136513
trained_Model_5  0.07103303 0.1460284 0.2055050 0.2077854 0.2672621 0.3490986
trained_Model_7  0.45018357 0.4601530 0.4773717 0.4818473 0.4990659 0.5224622
trained_Model_8  0.14789441 0.1697040 0.1981728 0.1983141 0.2267830 0.2490164
trained_Model_10 0.08029601 0.1057571 0.2519525 0.2463380 0.3925335 0.4011511
trained_Model_11 0.18813059 0.1953985 0.2053473 0.2436682 0.2536170 0.3758477
                 NA's
trained_Model_1     0
trained_Model_2     0
trained_Model_4     0
trained_Model_5     0
trained_Model_7     0
trained_Model_8     0
trained_Model_10    0
trained_Model_11    0

Plot and rank the fitted models

In [69]:
dotplot(results)
In [70]:
bwplot(results)

Assign the best trained model based on Accuracy

In [71]:
best_trained_model <- fit.naive_bayes_automaticGrid

9. Test skill of the BEST trained model on validation/testing dataset

In [72]:
predictions <- predict(best_trained_model, newdata=testing_dataset)

Evaluate the BEST trained model and print results

In [73]:
res_  <- caret::confusionMatrix(table(predictions, testing_dataset$Churn))
print("Results from the BEST trained model ... ...\n"); 
print(round(res_$overall, digits = 3))
[1] "Results from the BEST trained model ... ...\n"
      Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
         0.852          0.407          0.826          0.876          0.856 
AccuracyPValue  McnemarPValue 
         0.639          0.857 

10. Save the model to disk

In [74]:
#getwd()
saveRDS(best_trained_model, "./best_trained_model.rds")
In [75]:
# load the model
#getwd()
saved_model <- readRDS("./best_trained_model.rds")
print(saved_model)
Naive Bayes 

2501 samples
  19 predictor
   2 classes: 'no', 'yes' 

Pre-processing: centered (19), scaled (19) 
Resampling: Cross-Validated (2 fold, repeated 2 times) 
Summary of sample sizes: 1250, 1251, 1251, 1250 
Resampling results across tuning parameters:

  usekernel  Accuracy   Kappa    
  FALSE      0.8710513  0.4818473
   TRUE      0.8696560  0.1915383

Tuning parameter 'laplace' was held constant at a value of 0
Tuning
 parameter 'adjust' was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were laplace = 0, usekernel = FALSE
 and adjust = 1.
In [76]:
# make a predictions on "new data" using the final model
final_predictions <- predict(saved_model, dataSet[1:20])
confusionMatrix(table(final_predictions, dataSet$Churn))
res_ <- confusionMatrix(table(final_predictions, dataSet$Churn))
print("Results from the BEST trained model ... ...\n"); 
print(round(res_$overall, digits = 3))
Confusion Matrix and Statistics

                 
final_predictions   no  yes
              no  2625  216
              yes  225  267
                                         
               Accuracy : 0.8677         
                 95% CI : (0.8557, 0.879)
    No Information Rate : 0.8551         
    P-Value [Acc > NIR] : 0.01963        
                                         
                  Kappa : 0.4702         
                                         
 Mcnemar's Test P-Value : 0.70324        
                                         
            Sensitivity : 0.9211         
            Specificity : 0.5528         
         Pos Pred Value : 0.9240         
         Neg Pred Value : 0.5427         
             Prevalence : 0.8551         
         Detection Rate : 0.7876         
   Detection Prevalence : 0.8524         
      Balanced Accuracy : 0.7369         
                                         
       'Positive' Class : no             
                                         
[1] "Results from the BEST trained model ... ...\n"
      Accuracy          Kappa  AccuracyLower  AccuracyUpper   AccuracyNull 
         0.868          0.470          0.856          0.879          0.855 
AccuracyPValue  McnemarPValue 
         0.020          0.703 
In [77]:
print(res_$table)
fourfoldplot(res_$table, color = c("#CC6666", "#99CC99"),
             conf.level = 0, margin = 1, main = "Confusion Matrix")
                 
final_predictions   no  yes
              no  2625  216
              yes  225  267

REFERENCES