-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDepression_Analysis_Complete.R
1472 lines (1192 loc) · 44.3 KB
/
Depression_Analysis_Complete.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Script for analyzing depression
# Loading packages
library(data.table) # Fread and data.table functionality
library(tidyverse) # Multiple packages including dplyr
library(kableExtra) # Output tables
library(caret) # Cross-validation
library(ggplot2) # Plots
library(ggthemr) # Theme of ggplots
library(rcompanion) # Cramer v test
library(randomForest) # Random forest model
library(pROC) # ROC plots
library(rcompanion)
library(DescTools)
# Function for applying chi-squared test
apply_chi_cramer = function(pairs,dt){
# column_pairs : Names of categorical columns
# dt: Data table that is passed
# Getting the first and second categorical columns
v1 = pairs[1]
v2 = pairs[2]
# Creating a table with frequencies
tbl = table(dt[[v1]],
dt[[v2]])
# Computing Chi-Squared values
res_chi = chisq.test(tbl)
# Computing Cramer's V Measure
res_cramer_v = rcompanion::cramerV(tbl)
# Returning Results
return(data.table::data.table(variable1 = v1,
variable2 = v2,
p_value_chi = res_chi$p.value,
statistic_chi = res_chi$statistic,
cramer_V = res_cramer_v
)
)
}
# Missing values function
missing_val_func = function(col){
n = length(col)
total_missing = sum(is.na(col))
percent_missing = round(total_missing/n*100, digits = 2)
return(list(total_missing,percent_missing))
}
# Loading in needed datasets
DIDA = fread("data/Depression_In_Depth.csv")
# Dimensions of the dataset
dim(DIDA)
# Getting the class counts for depressed
depressed_counts = DIDA[,.(total = .N), keyby = DEPRESSED]
# Changing depressed into a factor
depressed_counts$DEPRESSED = factor(depressed_counts$DEPRESSED,
levels = c(0,1),
labels = c("Not Depressed",
"Depressed"))
# Setting the theme for ggplot
ggthemr("fresh")
# Displaying class counts
class_count_g = ggplot(depressed_counts,
aes(x = DEPRESSED,
y = total,
fill = DEPRESSED)) +
geom_bar(stat = "identity") +
geom_text(aes(label = total),
position = position_stack(vjust = 0.5),
size = 3,
color = "white") +
labs(title = "Class Count of Depression Variable",
x = "Class",
y = "Count",
fill = "Category")
# Saving the plot as a PNG in the images folder
ggsave(filename = "images/class_count_g.png",
plot =class_count_g,
width = 6,
height = 4)
# Getting a subset of all numerical variables
numerical_DIDA = DIDA[,.SD,.SDcols = sapply(DIDA,is.numeric)]
# The number of numerical variables
dim(numerical_DIDA)[2]
# aggregation of age range
age_dt = DIDA[,.(total = .N), keyby = AGERNG]
# The color palette for fresh plus two additional colors
fresh_colors = c("#111111",
"#65ADC2",
"#233B43",
"#E84646",
"#C29365",
"#362C21",
"#316675",
"#168E7F",
"#109B37",
"#F8766D",
"#B79F00")
# Displaying the age range distribution
ggplot(age_dt,
aes(x = AGERNG,
y = total,
fill = AGERNG)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = fresh_colors) +
geom_text(aes(label = total),
position = position_stack(vjust = 0.5),
size = 3,
color = "white") +
labs(title = "Distribution of Age Range",
x = "Age Range",
y = "Count",
fill = "Category")
# aggregated subset of educated students with/out depression
gender_dt = DIDA[,.(count = .N),
keyby = .(GENDER,DEPRESSED)]
#Plot of participant counts who are educated
ggplot(gender_dt, aes(x = GENDER,
y= count,
fill = factor(DEPRESSED))) +
geom_bar(stat = "identity", position = "dodge") +
geom_text(aes(label = count),
position = position_dodge(width = 0.9),
vjust = 1.5,
size = 3,
color = "white") +
labs(title = "Gender ~ Depression Count",
x = "Gender",
y = "Count",
fill = "Depression Status")
# Creating a percentage column
gender_dt2 = DIDA[,.(Count = .N),
keyby = .(GENDER)][,Percentage := round(Count/sum(Count),
digits = 2)*100]
# Pie chart of the count of females and males
ggplot(gender_dt2, aes(x = "",
y= Percentage,
fill = factor(GENDER))) +
geom_bar(width = 1, stat = "identity") +
coord_polar(theta = "y") +
geom_text(aes(label = paste(Percentage,"%")),
position = position_stack(vjust = 0.5),
size = 3,
color = "white") +
labs(title = "Percentage of Men and Women",
x = NULL,
y = NULL,
fill = "Gender") +
theme_void()
# Adding a percentage column
gender_dt[,Percentage := round(count/sum(count), digits = 2)*100,
keyby = GENDER]
# Creating labels
gender_dt$Label = factor(ifelse(gender_dt$DEPRESSED == 1, "Depressed", "Not Depressed"),
levels = c("Not Depressed","Depressed"))
# Excluding variables that have been analyzed
variables_exclude = c("AGERNG","GENDER")
# Casting to long format
DIDA_long = DIDA[,melt(.SD, id.vars = "DEPRESSED",
variable.name = "Variable",
value.name = "Value")]
# Counting the number of depressed
DIDA_long = DIDA_long[,.(Count = .N),
by = .(DEPRESSED, Variable, Value)]
# Calculating the percentage
DIDA_long[,Percentage := Count/sum(Count),
by = .(Variable, Value)]
# Making another aggregated table for the bar charts
DIDA_long_agg = DIDA_long[,.(Count = sum(Count)),
by = .(Variable, Value)]
# Getting a subset of the variables
subset_columns1 = as.character(unique(DIDA_long$Variable)[3:10])
# Creating bar plots of counts 3-10
ggplot(DIDA_long_agg[Variable %in% subset_columns1,],
aes(x = Value,
y= Count)) +
geom_bar(stat = "identity") +
geom_text(aes(label = Count),
vjust = 1.5,
size = 3,
color = "white") +
facet_wrap(~Variable, scales = "free_x") +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
# Pie charts 3-10
ggplot(DIDA_long[Variable %in% subset_columns1,],
aes(x = "", y = Percentage,
fill = factor(DEPRESSED))) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
facet_wrap(~Variable + Value, scales = "free") +
geom_text(aes(label = sprintf("%.1f%%", Percentage*100)),
position = position_stack(vjust = 0.5)) +
theme_void() +
theme(legend.position = "bottom") +
labs(fill = "Depression")
# Getting a subset of the variables 11-18
subset_columns2 = as.character(unique(DIDA_long$Variable)[11:18])
# Creating bar plots of counts
ggplot(DIDA_long_agg[Variable %in% subset_columns2,],
aes(x = Value,
y= Count)) +
geom_bar(stat = "identity") +
geom_text(aes(label = Count),
vjust = 1.5,
size = 3,
color = "white") +
facet_wrap(~Variable, scales = "free_x") +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
# Pie charts 11-18
ggplot(DIDA_long[Variable %in% subset_columns2,],
aes(x = "", y = Percentage,
fill = factor(DEPRESSED))) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
facet_wrap(~Variable + Value, scales = "free") +
geom_text(aes(label = sprintf("%.1f%%", Percentage*100)),
position = position_stack(vjust = 0.5)) +
theme_void() +
theme(legend.position = "bottom") +
labs(fill = "Depression")
# Getting a subset of the variables
subset_columns3 = as.character(unique(DIDA_long$Variable)[19:26])
# Creating bar plots of counts 19-26
ggplot(DIDA_long_agg[Variable %in% subset_columns3,],
aes(x = Value,
y= Count)) +
geom_bar(stat = "identity") +
geom_text(aes(label = Count),
vjust = 1.5,
size = 3,
color = "white") +
facet_wrap(~Variable, scales = "free_x") +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
# Pie chart 19-26
ggplot(DIDA_long[Variable %in% subset_columns3,],
aes(x = "", y = Percentage,
fill = factor(DEPRESSED))) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
facet_wrap(~Variable + Value, scales = "free") +
geom_text(aes(label = sprintf("%.1f%%", Percentage*100)),
position = position_stack(vjust = 0.5)) +
theme_void() +
theme(legend.position = "bottom") +
labs(fill = "Depression")
# Getting a subset of the variables
subset_columns4 = as.character(unique(DIDA_long$Variable)[27:30])
# Creating bar plots of counts 27-30
ggplot(DIDA_long_agg[Variable %in% subset_columns4,],
aes(x = Value,
y= Count)) +
geom_bar(stat = "identity") +
geom_text(aes(label = Count),
vjust = 1.5,
size = 3,
color = "white") +
facet_wrap(~Variable, scales = "free_x") +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
# Pie charts 27-30
ggplot(DIDA_long[Variable %in% subset_columns3,],
aes(x = "", y = Percentage,
fill = factor(DEPRESSED))) +
geom_bar(stat = "identity", width = 1) +
coord_polar("y", start = 0) +
facet_wrap(~Variable + Value, scales = "free") +
geom_text(aes(label = sprintf("%.1f%%", Percentage*100)),
position = position_stack(vjust = 0.5)) +
theme_void() +
theme(legend.position = "bottom") +
labs(fill = "Depression")
# Pearson’s Chi-Squared Test for Correlation between Categorical Variables
# Columns of data.table
columns = names(DIDA)
# Generating all pairs for categorical columns
column_pairs = combn(columns, 2, simplify = FALSE)
# Getting chi-squared results for all pairs
suppressWarnings({
chi_cramer_results = lapply(column_pairs,
function(x) apply_chi_cramer(pairs = x,
dt = DIDA))
})
# Creating a data.table from all results
chi_cramer_results = do.call(rbind, chi_cramer_results)
# Getting a subset of all pair that have a significant p-value
chi_cramer_significant = chi_cramer_results[p_value_chi < 0.05,][order(p_value_chi)]
# Labeling rows based on Cramer V association.
cut_b = c(0,0.1,0.3,0.5,1)
cut_labs = c("Weak", "Moderate", "Strong", "Very Strong")
# Assigning it to chi_cramer_significant
chi_cramer_significant[,association_type := cut(cramer_V,
breaks = cut_b,
labels = cut_labs,
include.lowest = TRUE)]
# Getting the first 10 rows
dis_tbl1 = chi_cramer_significant[1:10,]
# Displaying the first 10 rows
knitr::kable(dis_tbl1,booktabs=TRUE,
format="latex",
caption = "Categorical Association")%>%
kable_styling(latex_options = "HOLD_position")
# Heatmap of association
ggplot(chi_cramer_significant,
aes(x = variable1,
y = variable2,
fill = cramer_V)) +
geom_tile() +
labs(title = "Heatmap of Cramer's V (Significant Variables)",
x = " ",
y = " ",
fill = "Cramer's Value") +
theme(axis.text.x = element_text(size = 8,
angle = 45,
hjust = 1))
# Getting a subset where pairs contain depressed
cc_depressed_subset = chi_cramer_significant[variable1 == "DEPRESSED" | variable2 == "DEPRESSED"]
# Displaying the results
knitr::kable(cc_depressed_subset,booktabs=TRUE,
format="latex",
caption = "Categorical Association with Depression")%>%
kable_styling(latex_options = "HOLD_position")
# Aggregating the columns based on association type
assoc_type_agg = cc_depressed_subset[,.(Count = .N),
keyby = association_type]
# Plot of association
ggplot(assoc_type_agg, aes(x = association_type,
y = Count,
fill = association_type)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Count ~ Association Strength") +
geom_text(aes(label = Count),
vjust = 1.5,
size = 3,
color = "white")
# Heatmap of association
ggplot(cc_depressed_subset,
aes(x = variable1,
y = variable2,
fill = cramer_V)) +
geom_tile() +
labs(title = "Heatmap of Cramer's V",
x = " ",
y = " ",
fill = "Cramer's Value") +
theme(axis.text.x = element_text(size = 8,
angle = 45,
hjust = 1))
# Calculating the X squared with dependent variable
dependent_variables = columns[-length(columns)]
# Passing variables to function
suppressWarnings({
X_squared_results = lapply(dependent_variables,
function(x){
tbl = table(DIDA[[x]],DIDA$DEPRESSED)
res_chi = as.numeric(chisq.test(tbl)$p.value)
res_cramer_v = as.numeric(rcompanion::cramerV(tbl))
dt = data.table(variable = x,
chi_squared = res_chi,
cramer_v = res_cramer_v)
return(dt)
})
})
# Creating a data.table from all results
chi_cramer_selection = do.call(rbind, X_squared_results)
# Selecting the variables based on a cut-off criterion
chi_cutoff = 0.05
cramer_cutoff = 0.2
# Data table containing the selected variables
selected_variables_dt = chi_cramer_selection[chi_squared < chi_cutoff &
cramer_v > cramer_cutoff ]
# Making a display table
display_selected_variables = selected_variables_dt
# Changing names of the dataset
names(display_selected_variables) = c("Variables", "P-Values", "Cramer's V")
# Getting the selected variables
DIDA_Sub = DIDA[,selected_variables_dt$variable, with = F]
# Changing all the character variables to integers
DIDA_Sub[,names(DIDA_Sub):= lapply(.SD,function(x) as.integer(x == "Yes")
)]
# Adding the response variable
DIDA_Sub$DEPRESSED = DIDA$DEPRESSED
# Changing the response into a factor
DIDA_Sub$DEPRESSED = factor(DIDA_Sub$DEPRESSED)
# Training and Testing Models
set.seed(1255)
# Training/validation index 65%
train_index = createDataPartition(DIDA_Sub$DEPRESSED,
p = 0.65,
list = FALSE)
# Training/validation data
train_set = DIDA_Sub[train_index]
# Testing set 35%
test_set = DIDA_Sub[-train_index]
# Creating hyperparameters for Random Forest
rf_hyper_grid = expand.grid(
mtry = c(3, 5, 8, 10, 13)
)
# Other hyper parameters for random forest
ntree = c(100, 200, 300, 500, 1000)
nodesize = c(1, 5, 10)
maxnodes = c(10, 20, 30)
# Creating hyperparameters for logistic regression
lr_hyper_grid = expand.grid(
alpha = seq(0, 1, by = 0.1),
lambda = 10^seq(-3, 1, length = 100)
)
# Creating hyperparameters for gradient boosting
gb_hyper_grid = expand.grid(
n.trees = c(50, 100, 200, 300, 400, 500),
interaction.depth = c(1, 3, 5, 7, 9),
shrinkage = c(0.01, 0.05, 0.1, 0.2),
n.minobsinnode = c(5, 10, 15, 20)
)
set.seed(409)
# Settings for caret train
tc = trainControl(
method = "cv",
number = 5,
search = "grid")
# Training and tuning random forest model
# Creating a list to store the results
rfm_results = list()
# Note that the code is commented out because it saved as RDS
# # Applying all the hyperparameters
# for(ntree_value in ntree){
# for(nodesize_value in nodesize){
# for(maxnodes_value in maxnodes){
# set.seed(123)
# rfm = train(
# DEPRESSED ~ .,
# data = train_set,
# method = "rf",
# trControl = tc,
# tuneGrid = rf_hyper_grid,
# ntree = ntree_value,
# nodesize = nodesize_value,
# maxnodes = maxnodes_value
# )
#
# # Storing the results of the model
# rfm_results[[paste("ntree=",
# ntree_value,
# "nodesize=",
# nodesize_value,
# "maxnodes=",
# maxnodes_value,
# sep = "_")]] = rfm
# }
# }
# }
#
# # Saving as RDS to not run computationally expensive code
# saveRDS(rfm_results, file = "data/rfm_results.rds")
# Loading the stored results
rfm_results =readRDS(file = "data/rfm_results.rds")
# # Training and tuning logistic regression model
# lrm = train(
# DEPRESSED ~ .,
# data = train_set,
# method = "glmnet",
# trControl = tc,
# tuneGrid = lr_hyper_grid,
# family = "binomial"
# )
#
# # # Saving logistic regression results
# saveRDS(lrm, file = "data/lrm.rds")
# Loading the stored results
lrm =readRDS(file = "data/lrm.rds")
# # Training the gradient boosting model
# gbm = train(
# DEPRESSED ~ .,
# data = train_set,
# method = "gbm",
# preProcess = c("scale", "center"),
# trControl = tc,
# tuneGrid = gb_hyper_grid,
# verbose = FALSE
# )
#
# # Saving gradient boosting results
# saveRDS(gbm, file = "data/gbm.rds")
# Loading the stored results
gbm =readRDS(file = "data/gbm.rds")
# Creating a list of best models from RF
rfm_metrics_list = lapply(seq_along(rfm_results),function(y){
x = rfm_results[[y]]
best_row = x$results[x$results$mtry == as.numeric(x$bestTune),]
best_row$model_number = y
return(best_row)
})
# Changing list into a data table
rfm_metrics_dt = data.table(
bind_rows(rfm_metrics_list))[,.(mtry, Accuracy,Kappa,model_number)]
# Casting the data to long
rfm_met_long = suppressWarnings({ melt(rfm_metrics_dt,
id.vars = "model_number",
measure.vars = c("Accuracy","Kappa"),
variable.name = "Metric",
value.name = "Value") })
# Getting the max accuracy and kappa
max_acc = rfm_met_long[Metric == "Accuracy",.SD[which.max(Value)]]
max_kap = rfm_met_long[Metric == "Kappa",.SD[which.max(Value)]]
# ggplot of results
ggplot(rfm_met_long, aes(x = model_number,
y = Value,
color = Metric)) +
geom_point() +
geom_line() +
geom_point(data = max_acc,
aes(x = model_number,y = Value),
color = "red") +
geom_point(data = max_kap,
aes(x = model_number,y = Value),
color = "red") +
labs(title = "Accuracy and Kappa for Random Forest Models",
x = "Model Number",
y = "Metric")
# Best Random Forest Model
rf_best_model = rfm_results[[18]]$finalModel
# Getting subset of the results (Accuracy and Kappa)
lm_df = lrm$results[,3:4]
# Creating an ID for rows
lm_df$model_number = 1:nrow(lm_df)
# Casting logistic regression results to long
lrm_met_long = suppressWarnings({melt(lm_df,
id.vars = "model_number",
measure.vars = c("Accuracy","Kappa"),
variable.name = "Metric",
value.name = "Value")})
# Changing to a data.table
lrm_met_long = data.table(lrm_met_long)
# Getting the max accuracy and kappa
max_acc2 = lrm_met_long[Metric == "Accuracy",.SD[which.max(Value)]]
max_kap2 = lrm_met_long[Metric == "Kappa",.SD[which.max(Value)]]
# ggplot of results
ggplot(lrm_met_long, aes(x = model_number,
y = Value,
color = Metric)) +
geom_point() +
geom_line() +
geom_point(data = max_acc2,
aes(x = model_number,y = Value),
color = "red") +
geom_point(data = max_kap2,
aes(x = model_number,y = Value),
color = "red") +
labs(title = "Accuracy and Kappa for Logistic regression",
x = "Model Number",
y = "Metric")
# Best logistic regression model
lrm_best_model = lrm$finalModel
# Accuracy vs Regularization Parameter
plot(lrm)
# Plot of performance metrics
plot(gbm)
# Getting subset of the results (Accuracy and Kappa)
gbm_df = gbm$results[,5:6]
# Creating an ID for rows
gbm_df$model_number = 1:nrow(gbm_df)
# Casting logistic regression results to long
gbm_met_long = suppressWarnings({melt(gbm_df,
id.vars = "model_number",
measure.vars = c("Accuracy","Kappa"),
variable.name = "Metric",
value.name = "Value")})
# Changing to a data.table
gbm_met_long = data.table(gbm_met_long)
# Getting the max accuracy and kappa
max_acc3 = gbm_met_long[Metric == "Accuracy",.SD[which.max(Value)]]
max_kap3 = gbm_met_long[Metric == "Kappa",.SD[which.max(Value)]]
# ggplot of results
ggplot(gbm_met_long, aes(x = model_number,
y = Value,
color = Metric)) +
geom_point() +
geom_line() +
geom_point(data = max_acc3,
aes(x = model_number,y = Value),
color = "red") +
geom_point(data = max_kap3,
aes(x = model_number,y = Value),
color = "red") +
labs(title = "Accuracy and Kappa for Gradient Boosting",
x = "Model Number",
y = "Metric")
# Best gradient boosting model
gbm_best_model = gbm$finalModel
# Random Forest predictions
rf_pred = predict(rf_best_model,newdata = test_set)
# Confusion matrix
rf_cm = confusionMatrix(rf_pred,test_set$DEPRESSED)
# Converting confusion matrix to a data frame
rf_cm_df = as.data.frame(rf_cm$table)
# Changing test set into matrix
test_matrix = test_set[,-which(colnames(test_set) == "DEPRESSED"),
with = FALSE]
test_matrix = as.matrix(test_matrix)
# Best tuned lambda
lambda_best = lrm$bestTune$lambda
# # Logistic Regression predictions
lrm_pred_prod = predict(lrm_best_model,
newx = test_matrix,
s = lambda_best,
type = "response")
# Setting seed for reproducibility
set.seed(991)
# Creating lrm_pred into a factor of 1 and 0
lrm_pred = as.factor(ifelse(lrm_pred_prod > 0.5, 1, 0))
# Confusion matrix logistic regression
lrm_cm = confusionMatrix(lrm_pred,test_set$DEPRESSED)
# Converting confusion matrix to a data frame
lrm_cm_df = as.data.frame(lrm_cm$table)
# Setting seed for reproducibility
set.seed(981)
# Gradient Boosting predictions
gbm_pred = predict(gbm,test_set)
# Confusion matrix for Gradient Boosting
gbm_cm = confusionMatrix(gbm_pred,test_set$DEPRESSED)
# Converting confusion matrix to a data frame
gbm_cm_df = as.data.frame(gbm_cm$table)
# Plot of the confusion matrix
ggplot(rf_cm_df,
aes(x = Reference, y = Prediction, fill = Freq)) +
geom_tile() +
geom_text(aes(label = Freq),color = "white", vjust = 1) +
#scale_fill_gradient(low = "white", high = "red") +
labs(title = "Confusion Matrix Random Forest",
x = "Actual",
y = "Predicted") +
theme_minimal()
# Plot of the confusion matrix logistic regression
ggplot(lrm_cm_df,
aes(x = Reference, y = Prediction, fill = Freq)) +
geom_tile() +
geom_text(aes(label = Freq),color = "white", vjust = 1) +
#scale_fill_gradient(low = "white", high = "red") +
labs(title = "Confusion Matrix Logistic Regression",
x = "Actual",
y = "Predicted") +
theme_minimal()
# Plot of the confusion matrix
ggplot(gbm_cm_df,
aes(x = Reference, y = Prediction, fill = Freq)) +
geom_tile() +
geom_text(aes(label = Freq),color = "white", vjust = 1) +
#scale_fill_gradient(low = "white", high = "red") +
labs(title = "Confusion Matrix Gradient Boosting",
x = "Actual",
y = "Predicted") +
theme_minimal()
# Creating predictions of the type probability
rfpred_prob = predict(rf_best_model, test_set, type = "prob")
# Computing ROC curve
rf_roc = roc(test_set$DEPRESSED,rfpred_prob[, 2])
# Plotting ROC curve
plot(rf_roc, main = "Random Forest ROC Curve")
# Computing ROC curve
lrm_roc = roc(test_set$DEPRESSED,lrm_pred_prod)
# AUC
auc(lrm_roc)
# Plotting ROC curve
plot(lrm_roc, main = "Logistic Regression ROC Curve")
# Creating predictions of the type probability
gbmpred_prob = predict(gbm, test_set, type = "prob")
# Computing ROC curve
gbm_roc = roc(test_set$DEPRESSED,gbmpred_prob[, 2])
# AUC
auc(gbm_roc)
# Plotting ROC curve
plot(gbm_roc , main = "Gradient Boosting ROC Curve")
# Getting the best thresholds
rf_threshold = coords(rf_roc, "best", ret = "threshold")
lrm_threshold = coords(lrm_roc, "best", ret = "threshold")
gbm_threshold = coords(gbm_roc, "best", ret = "threshold")
thresh_auc_dt = data.table(Model = c("Random Forest",
"Logistic Regression",
"Gradient Boosting"),
AUC = c(auc(rf_roc),
auc(lrm_roc),
auc(gbm_roc)),
Best_Threshold = c(rf_threshold,
lrm_threshold,
gbm_threshold))
# Displaying the results
knitr::kable(thresh_auc_dt,
booktabs=TRUE,
format="latex",
caption = "AUC and Best Thresholds")%>%
kable_styling(latex_options = "HOLD_position")
holder_colnames = c("Model", "Sensitivity","Specificity",
"Pos Pred Value" ,"Neg Pred Value",
"Precision","Recall","F1",
"Prevalence","Detection Rate" ,
"Detection Prevalence" ,"Balanced Accuracy")
# Creating a data table of best results
best_metrics = data.table(rbind(c("Random Forest",
round(as.numeric(rf_cm$byClass),3)),
c("Logistic Regression",
round(as.numeric(lrm_cm$byClass),3)),
c("Gradient Boosting",
round(as.numeric(gbm_cm$byClass),3))
))
# Adding column names
setnames(best_metrics, holder_colnames)
# Changing columns to be numeric instead of character
best_metrics[,(names(best_metrics)[-1]):= lapply(.SD, as.numeric),
.SDcols = names(best_metrics)[-1]]
# Displaying the results
knitr::kable(best_metrics,
booktabs=TRUE,
format="latex",
caption = "AUC and Best Thresholds")%>%
kable_styling(latex_options = "HOLD_position")
# Best Model for Gradient Boosting
# Splitting the data again
# Setting seed for reproducibility
set.seed(311)
# Second partition of dataset. Training is
train_index2 = createDataPartition(DIDA_Sub$DEPRESSED,
p = 0.65,
list = FALSE)
# Training set 65%
train_set2 = DIDA_Sub[train_index2]
# Testing set 35%
test_set2 = DIDA_Sub[-train_index2]
# Best hyper-parameters
gbm_grid = expand.grid(
n.trees = gbm_best_model$tuneValue$n.trees,
interaction.depth = gbm_best_model$tuneValue$interaction.depth,
shrinkage = gbm_best_model$tuneValue$shrinkage,
n.minobsinnode = gbm_best_model$tuneValue$n.minobsinnode
)
# # # Training model with the best parameters
# Commented out because the results are saved as RDS
# final_gbm = train(
# DEPRESSED ~ .,
# data = train_set2,
# method = "gbm",
# preProcess = c("scale", "center"),
# trControl = tc,
# tuneGrid = gbm_grid,
# verbose = FALSE
# )
# #
# # # Saving best gbm
# saveRDS(final_gbm, file = "data/final_gbm.rds")
# Loading the stored results
final_gbm =readRDS(file = "data/final_gbm.rds")
# Setting seed for reproducibility
set.seed(89)
# Getting predictions of the new model
fgbm_pred = predict(final_gbm, newdata = test_set2, type = "prob")
# ROC calculations for ROC curve
fgbm_roc = roc(test_set2$DEPRESSED,fgbm_pred[,2])
# ROC curve of the best gradient boosting model
plot(fgbm_roc,main = "ROC Curve for Final GB Model")
# Getting 1 and 0 predictions
fgbm_pred2 = predict(final_gbm, newdata = test_set2)
# Confusion matrix for Gradient Boosting
fgbm_cm = confusionMatrix(fgbm_pred2,test_set2$DEPRESSED)
# Converting confusion matrix to a data frame
fgbm_cm_df = as.data.frame(fgbm_cm$table)
# Plot of the confusion matrix
ggplot(fgbm_cm_df,
aes(x = Reference, y = Prediction, fill = Freq)) +
geom_tile() +
geom_text(aes(label = Freq),color = "white", vjust = 1) +
labs(title = "Confusion Matrix GB-Model",
x = "Actual",
y = "Predicted")
# Getting the names of the metric
fgbm_names = names(fgbm_cm$byClass)
# Creating a data table of results
fgbm_metrics = data.table(Metric = c("AUC",fgbm_names),
Values = c(as.numeric(auc(fgbm_roc)),
as.numeric(fgbm_cm$byClass)))
# Table of Gradient boosting metrics
knitr::kable(fgbm_metrics,booktabs=TRUE,
format="latex",
caption = "Best Gradient Boosting Model Results")%>%
kable_styling(latex_options = "HOLD_position")
# variable importance
VI = summary(final_gbm$finalModel, plotit = F)
# Variable iportance plot
ggplot(VI, aes(x = reorder(var, rel.inf),
y = rel.inf)) +
geom_bar(stat = "identity") +
geom_text(aes(label = round(rel.inf, 2)),
hjust = -0.1,
size = 3) +
coord_flip() +
labs(title = "Variable Importance GB Model",
x = "Variable",
y = "Relative Influence")
# Creating a pdp plot for the predictor ANXI
pdp_anxi = plot(final_gbm$finalModel,'ANXI', return.grid=TRUE)
ggplot(pdp_anxi, aes(x = ANXI, y = y)) +
geom_line() +
labs(title = "Partial Dependence Plot for ANXI",
x = "ANXI",
y = "Predicted Response")
# Creating a pdp plot for the predictor POSSAT
pdp_POSSAT = plot(final_gbm$finalModel,'POSSAT', return.grid=TRUE)
ggplot(pdp_POSSAT , aes(x = POSSAT, y = y)) +
geom_line() +
labs(title = "Partial Dependence Plot for POSSAT",
x = "POSSAT",
y = "Predicted Response")
# Creating a pdp plot for the predictor FINSTR
pdp_FINSTR = plot(final_gbm$finalModel,'FINSTR', return.grid=TRUE)
ggplot(pdp_FINSTR , aes(x = FINSTR, y = y)) +
geom_line() +
labs(title = "Partial Dependence Plot for FINSTR",
x = "FINSTR",
y = "Predicted Response")
# Creating hyperparameters for Random Forest
rf_hyper_grid2 = expand.grid(
mtry = 3
)
# # Training model with the best parameters