-
Notifications
You must be signed in to change notification settings - Fork 16
/
prediction-disease-modeling_windowpane.qmd
1209 lines (898 loc) · 35 KB
/
prediction-disease-modeling_windowpane.qmd
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
---
title: "correl"
format: html
editor_options:
chunk_output_type: console
---
```{r}
library(gsheet)
library(tidyverse)
library(nasapower)
library(lubridate)
library(progress)
library(r4pde)
# Load data from Google Sheets
```
## load the data
```{r}
trials <- BlastWheat
# Data preparation
trials2 <- trials |>
#filter(study %in% c(1, 2, 3, 4)) |>
mutate(
heading = as.Date(heading, format = "%d-%m-%Y") # Convert to Date format
)
```
## Get weather
```{r}
# Example usage with a specified number of days around a date
weather_data <- get_nasapower(
data = trials2,
days_around = 28,
date_col = "heading"
)
```
## Join trial and weather
```{r}
trials3 <- full_join(trials2, weather_data)
head(trials3)
```
## windowpane single variable and window
```{r}
wp1 <- windowpane(
data = trials3,
end_date_col = heading,
date_col = YYYYMMDD,
variable = T2M, # Example variable
summary_type = "mean",
threshold = NULL,
window_lengths = c(7, 28),
direction = "both",
group_by_cols =
"study", # Grouping by 'study'
)
wp_1 <- wp_1 |>
mutate(inc = trials$inc_mean,
inc2 = case_when(inc > 20 ~ 1,
TRUE ~ 0))
```
## window pane multiple variables
```{r}
## By multiple variables
# Define the variables you want to analyze
variables <- c("T2M", "T2M_MIN", "T2M_MAX", "RH2M") # Add more variables as needed
# Apply the function to each variable and combine the results
wp_means <- map(variables, function(var) {
windowpane(
data = trials3,
end_date_col = heading,
date_col = YYYYMMDD,
variable = !!sym(var), # Example variable
summary_type = "mean",
threshold = NULL,
window_lengths = c(7, 14, 21, 28),
direction = "both",
group_by_cols = "study", # Grouping by 'study'
)
})
wp_means_df <- reduce(wp_means, left_join, by = c("study", "heading")) # Replace with your grouping columns
# sum rainfall
wp_sums_df <- windowpane(
data = trials3,
end_date_col = heading,
date_col = YYYYMMDD,
variable = PRECTOTCORR, # Example variable
summary_type = "sum",
threshold = NULL,
window_lengths = c(7, 14, 21, 28),
direction = "both",
group_by_cols = "study", # Grouping by 'study'
)
wp_sums_df <- wp_sums_df |>
select(-heading, -study)
## count
wp_count_df <- windowpane(
data = trials3,
end_date_col = heading,
date_col = YYYYMMDD,
variable = T2M_MIN, # Example variable
summary_type = "below_threshold",
threshold = 15,
window_lengths = c(7, 14, 21, 28),
direction = "both",
group_by_cols = "study", # Grouping by 'study'
)
wp_count_df <- wp_count_df |>
select(-heading, -study)
wp_all <- cbind(wp_means_df, wp_sums_df, wp_count_df)
duplicated(names(wp_all))
wp_all <- wp_all |>
mutate(inc = trials$inc_mean,
inc2 = case_when(inc > 20 ~ 1,
TRUE ~ 0))
T2M_7day <- wp_all |>
select(starts_with("length7_T2M_mean")) |>
mutate(inc = trials$inc_mean,
inc2 = case_when(inc > 20 ~ 1,
TRUE ~ 0))
```
## function correlations and simes method
```{r}
# Define the simplified function for correlation analysis
variable_selection <- function(data, response_var, corr_type = "spearman", alpha = 0.05) {
# Define predictors and response
predictors <- setdiff(names(data), response_var)
response <- data[[response_var]]
# Ensure predictors are numeric
data[predictors] <- lapply(data[predictors], as.numeric)
# Initialize the results data frame
results <- data.frame(variable = predictors, correlation = NA, p_value = NA)
# Loop through each predictor
for (var in predictors) {
var_data <- data[[var]]
# Ensure the variable is numeric and not constant
if (is.numeric(var_data) && length(unique(var_data)) > 1) {
# Check if enough complete cases exist
complete_cases <- complete.cases(var_data, response)
if (sum(complete_cases) > 2) {
# Extract complete cases only
var_data <- var_data[complete_cases]
response_data <- response[complete_cases]
# Compute the specified type of correlation
corr <- cor(var_data, response_data, method = corr_type)
# Compute the p-value using cor.test()
p_value <- cor.test(var_data, response_data, method = corr_type)$p.value
# Store the correlation and p-value in the results data frame
results[results$variable == var, c('correlation', 'p_value')] <- c(corr, p_value)
}
}
}
# Apply Simes method
results <- results %>%
arrange(p_value) %>%
mutate(rank = row_number(),
m = n(),
threshold = alpha * rank / m,
significant_simes = p_value <= threshold)
# Select significant variables by Simes
selected_simes_variables <- results %>%
filter(significant_simes == TRUE) %>%
pull(variable)
# Apply Benjamini-Hochberg FDR correction
results <- results %>%
mutate(fdr_threshold = p.adjust(p_value, method = "BH"),
significant_fdr = fdr_threshold < alpha)
# Select significant variables by FDR
selected_fdr_variables <- results %>%
filter(significant_fdr == TRUE) %>%
pull(variable)
# Return the results data frame and selected variables
return(list(
results = results,
selected_simes = selected_simes_variables,
selected_fdr = selected_fdr_variables
))
}
# Example usage
data <- wp_all |> select(-study, -heading, -inc) # Example data selection
response_var <- 'inc2'
# Call the simplified function
results <- variable_selection(data, response_var, corr_type = "spearman", alpha = 0.05)
# Print the results
print(results$results)
cat("Selected variables by Simes method:", results$selected_simes, "\n")
cat("Selected variables by FDR method:", results$selected_fdr, "\n")
# Example usage
names(wp_all)
data <- wp_all |> select(-study, -heading, -inc, - `T2M_MIN_0_-27`)
response_var <- 'inc2'
# Call the function
results <- variable_selection(data, response_var, corr_type = "kendall")
view(results$results)
# Print the results
print(results$results)
cat("Selected variables by Simes method:", results$selected_simes, "\n")
cat("Selected variables by FDR method:", results$selected_fdr, "\n")
```
## Function bootstrapping correlations
```{r}
# Define the function for bootstrapping correlation analysis with refined Simes method
variable_selection_with_refined_simes <- function(data, response_var, corr_type = "spearman", R = 1000, global_alpha = 0.05, individual_alpha = 0.005) {
# Define predictors and response
predictors <- setdiff(names(data), response_var)
response <- data[[response_var]]
# Ensure predictors are numeric
data[predictors] <- lapply(data[predictors], as.numeric)
# Initialize the results data frame
results <- data.frame(variable = predictors, correlation = NA, p_value = NA,
mean_corr = NA, sd_corr = NA, median_corr = NA)
# Define the internal function for bootstrapping
calc_correlation <- function(data, indices, var, response_var) {
# Subset data for bootstrap sample
sample_data <- data[indices, ]
var_data <- sample_data[[var]]
response_data <- sample_data[[response_var]]
# Calculate correlation for the given sample
corr_result <- cor.test(var_data, response_data, method = corr_type)
# Return the correlation estimate and p-value
return(c(as.numeric(corr_result$estimate), corr_result$p.value))
}
# Loop through each predictor
for (var in predictors) {
var_data <- data[[var]]
# Ensure the variable is numeric and not constant
if (is.numeric(var_data) && length(unique(var_data)) > 1) {
# Check if enough complete cases exist
complete_cases <- complete.cases(var_data, response)
if (sum(complete_cases) > 5) { # Minimum sample size of 5
# Prepare data for bootstrapping
data_boot <- data.frame(var_data = var_data[complete_cases], response = response[complete_cases])
# Run the bootstrap (using boot package)
boot_result <- boot(data = data_boot, statistic = function(data, indices) {
calc_correlation(data, indices, "var_data", "response")
}, R = R)
# Prepare bootstrap summary
bootstrap_df <- as.data.frame(boot_result$t)
colnames(bootstrap_df) <- c("correlation", "p_value")
# Calculate mean, standard deviation, and median of the correlation estimates
mean_corr <- mean(bootstrap_df$correlation, na.rm = TRUE)
sd_corr <- sd(bootstrap_df$correlation, na.rm = TRUE)
median_corr <- median(bootstrap_df$correlation, na.rm = TRUE)
# Extract the initial correlation and p-value from the bootstrap
corr <- boot_result$t0[1]
p_value <- boot_result$t0[2]
# Store results
results[results$variable == var, c('correlation', 'p_value', 'mean_corr', 'sd_corr', 'median_corr')] <-
c(corr, p_value, mean_corr, sd_corr, median_corr)
}
}
}
# Apply Simes method to adjust for multiple testing
results <- results %>%
arrange(p_value) %>%
mutate(rank = row_number(),
m = n(),
simes_threshold = global_alpha * rank / m,
significant_simes = p_value <= simes_threshold,
individual_significant = p_value <= individual_alpha) # Use individual_alpha = 0.005
# Calculate the global p-value (Pg) as the minimum of the Simes-adjusted p-values
Pg <- min(results$p_value / (results$rank / results$m), na.rm = TRUE)
# Determine global significance
global_significant <- Pg < global_alpha
# Select significant variables by refined Simes method
selected_simes_variables <- results %>%
filter(significant_simes == TRUE) %>%
pull(variable)
# Select significant variables by individual alpha threshold (0.005)
selected_individual_variables <- results %>%
filter(individual_significant == TRUE) %>%
pull(variable)
# Return the results data frame and selected variables
return(list(
results = results,
selected_simes = selected_simes_variables,
selected_individual = selected_individual_variables,
global_significant = global_significant,
Pg = Pg
))
}
# Example usage
data <- wp_all |> select(-study, -heading, -inc2) # Example data selection
response_var <- 'inc'
library(boot)
# Call the function with refined Simes adjustment
results <- variable_selection_with_refined_simes(data, response_var, corr_type = "spearman", R = 1000, global_alpha = 0.05, individual_alpha = 0.005)
# Print the results
view(results$results)
cat("Selected variables by Simes method:", results$selected_simes, "\n")
cat("Selected variables by individual significance (alpha=0.005):", results$selected_individual, "\n")
cat("Global significance (Pg):", results$Pg, "\n")
cat("Is globally significant?", results$global_significant, "\n")
```
## bootstraping correlation simes in table
```{r}
T2M_MAX_7 <- wp_all |>
select(starts_with("length7_T2M_MAX_mean"))
```
```{r}
windowpane_tests <- function(data, response_var, corr_type = "spearman", R = 1000, global_alpha = 0.05, individual_alpha = 0.005) {
# Define predictors and response
predictors <- setdiff(names(data), response_var)
response <- data[[response_var]]
# Ensure predictors are numeric
data[predictors] <- lapply(data[predictors], as.numeric)
# Initialize the results data frame
results <- data.frame(variable = predictors,
correlation = NA,
p_value = NA,
mean_corr = NA,
sd_corr = NA,
median_corr = NA)
# Define the internal function for bootstrapping
calc_correlation <- function(data, indices, var, response_var) {
# Subset data for bootstrap sample
sample_data <- data[indices, ]
var_data <- sample_data[[var]]
response_data <- sample_data[[response_var]]
# Calculate correlation for the given sample
corr_result <- cor.test(var_data, response_data,
method = corr_type, exact = FALSE)
# Return the correlation estimate and p-value
return(c(as.numeric(corr_result$estimate), corr_result$p.value))
}
# Loop through each predictor
for (var in predictors) {
var_data <- data[[var]]
# Ensure the variable is numeric and not constant
if (is.numeric(var_data) && length(unique(var_data)) > 1) {
# Check if enough complete cases exist
complete_cases <- complete.cases(var_data, response)
if (sum(complete_cases) > 5) { # Minimum sample size of 5
# Prepare data for bootstrapping
data_boot <- data.frame(var_data = var_data[complete_cases], response = response[complete_cases])
# Run the bootstrap (using boot package)
boot_result <- boot(data = data_boot, statistic = function(data, indices) {
calc_correlation(data, indices, "var_data", "response")
}, R = R)
# Prepare bootstrap summary
bootstrap_df <- as.data.frame(boot_result$t)
colnames(bootstrap_df) <- c("correlation", "p_value")
# Calculate mean, standard deviation, and median of the correlation estimates
mean_corr <- mean(bootstrap_df$correlation, na.rm = TRUE)
sd_corr <- sd(bootstrap_df$correlation, na.rm = TRUE)
median_corr <- median(bootstrap_df$correlation, na.rm = TRUE)
# Extract the initial correlation and p-value from the bootstrap
corr <- boot_result$t0[1]
p_value <- boot_result$t0[2]
# Store results
results[results$variable == var, c('correlation', 'p_value', 'mean_corr', 'sd_corr', 'median_corr')] <-
c(corr, p_value, mean_corr, sd_corr, median_corr)
}
}
}
# Apply Simes method to adjust for multiple testing
results <- results %>%
arrange(p_value) %>%
mutate(rank = row_number(),
m = n(),
simes_threshold = global_alpha * rank / m,
significant_simes = p_value <= simes_threshold,
individual_significant = p_value <= individual_alpha) # Use individual_alpha = 0.005
# Calculate the global p-value (Pg) as the minimum of the Simes-adjusted p-values
Pg <- min(results$p_value / (results$rank / results$m), na.rm = TRUE)
# Determine global significance
global_significant <- Pg < global_alpha
# Find the maximum correlation
max_correlation <- max(results$correlation, na.rm = TRUE)
# Add global Pg and max correlation as a separate row
summary_table <- data.frame(
Metric = c("Global P-value (Pg)", "Max Correlation"),
Value = c(Pg, max_correlation)
)
# Return the results data frame and summary table
return(list(
results = results,
summary_table = summary_table,
global_significant = global_significant
))
}
# Example usage
data <- T2M_MAX_7
data$inc <- trials$inc_mean
response_var <- 'inc'
library(boot)
# Call the function with refined Simes adjustment
results <- variable_selection_with_refined_simes_table(data, response_var, corr_type = "spearman", R = 1000)
# View the results
view(results$results)
print(results$summary_table)
cat("Is globally significant?", results$global_significant, "\n")
# Define a function to identify clusters of significant correlations
windowpane_clusters <- function(results_df, min_cluster_size = 5) {
# Create a logical vector indicating whether each correlation is significant
is_significant <- results_df$individual_significant
# Initialize variables to track clusters
cluster_starts <- c()
cluster_ends <- c()
current_cluster_size <- 0
cluster_start <- NULL
# Loop through the significance vector
for (i in seq_along(is_significant)) {
if (is_significant[i]) {
# Start or extend a cluster
if (current_cluster_size == 0) {
cluster_start <- i
}
current_cluster_size <- current_cluster_size + 1
} else {
# End a cluster
if (current_cluster_size >= min_cluster_size) {
cluster_starts <- c(cluster_starts, cluster_start)
cluster_ends <- c(cluster_ends, i - 1)
}
# Reset cluster size
current_cluster_size <- 0
}
}
# Check if the last cluster was not closed
if (current_cluster_size >= min_cluster_size) {
cluster_starts <- c(cluster_starts, cluster_start)
cluster_ends <- c(cluster_ends, length(is_significant))
}
# Create a data frame to summarize clusters
clusters_df <- data.frame(
Cluster_Start = cluster_starts,
Cluster_End = cluster_ends,
Cluster_Size = cluster_ends - cluster_starts + 1
)
return(clusters_df)
}
```
## Elastic net
```{r}
# Elastic net
library(glmnet) # For Elastic Net model
library(caret) # For data splitting and cross-validation
# Load your dataset
data <- wp_all |> select(-study, -heading, -inc)
# Define predictors and response (now 'inc2' for binary response)
response_var <- 'inc2'
predictors <- setdiff(names(data), response_var)
response <- data[[response_var]]
# Convert predictors to numeric matrix
X <- as.matrix(data[predictors])
y <- as.numeric(response)
# Remove rows with missing values
complete_cases <- complete.cases(X, y)
X <- X[complete_cases, ]
y <- y[complete_cases]
set.seed(123) # For reproducibility
# Create training and testing sets
train_index <- createDataPartition(y, p = 0.8, list = FALSE)
X_train <- X[train_index, ]
y_train <- y[train_index]
X_test <- X[-train_index, ]
y_test <- y[-train_index]
# Define the range of alpha to explore
alpha_values <- seq(0, 1, by = 0.1) # Alpha ranges from 0 (Ridge) to 1 (Lasso)
# Initialize storage for results
cv_results <- list()
# Perform cross-validation for each alpha
for (alpha in alpha_values) {
cv_fit <- cv.glmnet(X_train, y_train, alpha = alpha,
family = "binomial", # For binary response
nfolds = 10, # 10-fold cross-validation
type.measure = "class") # Classification error
cv_results[[paste0("alpha_", alpha)]] <- cv_fit
}
# Find the best alpha and lambda based on cross-validation
best_alpha <- 0
best_lambda <- Inf
min_error <- Inf
for (alpha in names(cv_results)) {
fit <- cv_results[[alpha]]
if (min(fit$cvm) < min_error) {
min_error <- min(fit$cvm)
best_alpha <- as.numeric(gsub("alpha_", "", alpha))
best_lambda <- fit$lambda.min
}
}
cat("Best alpha:", best_alpha, "\n")
cat("Best lambda:", best_lambda, "\n")
# Fit the final Elastic Net model with optimal alpha and lambda
final_fit <- glmnet(X_train, y_train,
alpha = best_alpha,
lambda = best_lambda,
family = "binomial")
# Print the coefficients of the selected variables
selected_coefficients <- coef(final_fit, s = best_lambda)
# Convert to a matrix for easier subsetting
selected_coefficients <- as.matrix(selected_coefficients)
# Extract the names of the variables with non-zero coefficients
selected_variables <- rownames(selected_coefficients)[selected_coefficients != 0]
# Remove the intercept from the selected variables
selected_variables <- selected_variables[selected_variables != "(Intercept)"]
cat("Selected variables by Elastic Net:", selected_variables, "\n")
# Predict on the test set (probabilities)
y_pred_prob <- predict(final_fit, newx = X_test, s = best_lambda, type = "response")
# Convert probabilities to binary predictions
y_pred <- ifelse(y_pred_prob > 0.5, 1, 0)
# Calculate accuracy
accuracy <- mean(y_pred == y_test)
cat("Accuracy on Test Set:", accuracy, "\n")
# Calculate confusion matrix
conf_matrix <- table(Predicted = y_pred, Actual = y_test)
print(conf_matrix)
# Calculate AUC
library(pROC)
roc_obj <- roc(y_test, y_pred_prob)
auc <- auc(roc_obj)
cat("AUC on Test Set:", auc, "\n")
# Plot ROC curve
plot(roc_obj, main = "ROC Curve for Logistic Elastic Net Model")
```
## Elastic net top 15
```{r}
# Elastic net
library(glmnet) # For Elastic Net model
library(caret) # For data splitting and cross-validation
# Load your dataset
data <- wp_all |> select(-study, -heading, -inc)
# Define predictors and response (now 'inc2' for binary response)
response_var <- 'inc2'
predictors <- setdiff(names(data), response_var)
response <- data[[response_var]]
# Convert predictors to numeric matrix
X <- as.matrix(data[predictors])
y <- as.numeric(response)
# Remove rows with missing values
complete_cases <- complete.cases(X, y)
X <- X[complete_cases, ]
y <- y[complete_cases]
set.seed(123) # For reproducibility
# Create training and testing sets
train_index <- createDataPartition(y, p = 0.8, list = FALSE)
X_train <- X[train_index, ]
y_train <- y[train_index]
X_test <- X[-train_index, ]
y_test <- y[-train_index]
# Define the range of alpha to explore
alpha_values <- seq(0, 1, by = 0.1)
# Initialize storage for results
cv_results <- list()
# Perform cross-validation for each alpha
for (alpha in alpha_values) {
cv_fit <- cv.glmnet(X_train, y_train, alpha = alpha,
family = "binomial",
nfolds = 10,
type.measure = "class")
cv_results[[paste0("alpha_", alpha)]] <- cv_fit
}
# Find the best alpha and lambda based on cross-validation
best_alpha <- 0
best_lambda <- Inf
min_error <- Inf
for (alpha in names(cv_results)) {
fit <- cv_results[[alpha]]
if (min(fit$cvm) < min_error) {
min_error <- min(fit$cvm)
best_alpha <- as.numeric(gsub("alpha_", "", alpha))
best_lambda <- fit$lambda.min
}
}
cat("Best alpha:", best_alpha, "\n")
cat("Best lambda:", best_lambda, "\n")
# Fit the final Elastic Net model with optimal alpha and lambda
final_fit <- glmnet(X_train, y_train,
alpha = best_alpha,
lambda = best_lambda,
family = "binomial")
# Extract coefficients of the final model
selected_coefficients <- coef(final_fit, s = best_lambda)
# Convert coefficients to a matrix for easier manipulation
selected_coefficients <- as.matrix(selected_coefficients)
# Remove the intercept from the selected coefficients
selected_coefficients <- selected_coefficients[-1, , drop = FALSE]
# Select the top 15 variables with the highest absolute coefficients
top_15_indices <- order(abs(selected_coefficients), decreasing = TRUE)[1:15]
top_15_variables <- rownames(selected_coefficients)[top_15_indices]
cat("Top 15 selected variables:", top_15_variables, "\n")
# Refit the model using only the top 15 predictors
X_train_top15 <- X_train[, top_15_variables]
X_test_top15 <- X_test[, top_15_variables]
final_fit_top15 <- glmnet(X_train_top15, y_train,
alpha = best_alpha,
lambda = best_lambda,
family = "binomial")
# Predict on the test set (probabilities)
y_pred_prob <- predict(final_fit_top15, newx = X_test_top15, s = best_lambda, type = "response")
# Convert probabilities to binary predictions
y_pred <- ifelse(y_pred_prob > 0.5, 1, 0)
# Calculate accuracy
accuracy <- mean(y_pred == y_test)
cat("Accuracy on Test Set:", accuracy, "\n")
# Calculate confusion matrix
conf_matrix <- table(Predicted = y_pred, Actual = y_test)
print(conf_matrix)
# Calculate AUC
library(pROC)
roc_obj <- roc(y_test, y_pred_prob)
auc <- auc(roc_obj)
cat("AUC on Test Set:", auc, "\n")
# Plot ROC curve
plot(roc_obj, main = "ROC Curve for Logistic Elastic Net Model with Top 15 Predictors")
```
## best glm
```{r}
## Best glm
# Load the necessary libraries
library(bestglm)
# Prepare the data frame for bestglm
data_subset <- data.frame(data[, top_15_variables], inc2 = response)
# Remove rows with missing values
data_subset <- na.omit(data_subset)
data_subset <- data_subset
names(data_subset)
# Convert the response variable to a factor for logistic regression
data_subset$inc2 <- as.factor(data_subset$inc2)
# Fit the Best Subset Selection model with bestglm
bestglm_fit <- bestglm(
data_subset,
family = binomial, # Logistic regression
IC = "BIC" ,
method = "exhaustive"# Use BIC as the information criterion
)
# Print the summary of the best model
summary(bestglm_fit)
# Extract the names of the selected variables
selected_bestglm_variables <- names(coef(bestglm_fit$BestModel))[-1] # Exclude intercept
cat("Variables selected by Best Subset Selection (bestglm):", selected_bestglm_variables, "\n")
# Predict probabilities on the training set
y_pred_prob <- predict(bestglm_fit$BestModel, type = "response")
# Convert probabilities to binary predictions
y_pred <- ifelse(y_pred_prob > 0.5, 1, 0)
# Calculate accuracy
accuracy <- mean(y_pred == data_subset$inc2)
cat("Accuracy of Best Subset Model:", accuracy, "\n")
# Calculate confusion matrix
conf_matrix <- table(Predicted = y_pred, Actual = data_subset$inc2)
print(conf_matrix)
# Calculate AUC
library(pROC)
roc_obj <- roc(data_subset$inc2, y_pred_prob)
auc <- auc(roc_obj)
cat("AUC of Best Subset Model:", auc, "\n")
# Plot ROC curve
plot(roc_obj, main = "ROC Curve for Best Subset Logistic Model")
```
## Logistic after bestglm
```{r}
# Get the selected variables from the bestglm model
selected_vars <- names(bestglm_fit$BestModel$coefficients)[-1] # Exclude intercept
cat("Selected variables by bestglm:", selected_vars, "\n")
# Split the data into training and testing sets
set.seed(123) # For reproducibility
train_index <- createDataPartition(data_subset$inc2, p = 0.8, list = FALSE)
train_data <- data_subset[train_index, ]
test_data <- data_subset[-train_index, ]
# Fit a logistic regression model using the selected variables
formula <- as.formula(paste("inc2 ~", paste(selected_vars, collapse = " + ")))
logistic_model <- glm(formula, data = train_data, family = binomial)
# Print model summary
summary(logistic_model)
# Predict probabilities on the test set
y_pred_prob <- predict(logistic_model, newdata = test_data, type = "response")
# Convert probabilities to binary predictions
y_pred <- ifelse(y_pred_prob > 0.5, 1, 0)
# Calculate accuracy
accuracy <- mean(y_pred == as.numeric(test_data$inc2) - 1)
cat("Accuracy on Test Set:", accuracy, "\n")
# Calculate confusion matrix
conf_matrix <- table(Predicted = y_pred, Actual = as.numeric(test_data$inc2) - 1)
print(conf_matrix)
# Calculate AUC
roc_obj <- roc(as.numeric(test_data$inc2) - 1, y_pred_prob)
auc <- auc(roc_obj)
cat("AUC on Test Set:", auc, "\n")
# Plot ROC curve
plot(roc_obj, main = "ROC Curve for Logistic Regression Model")
## Youden vallue
# Load the pROC package
library(pROC)
# Ensure 'rf_pred_prob' is numeric and 'actual_binary' is binary (0 and 1)
rf_pred_prob <- as.numeric(y_pred_prob)
actual_binary <- as.numeric(as.factor(test_data$inc2)) - 1
# Calculate the ROC curve
roc_obj <- roc(actual_binary, rf_pred_prob, levels = c(0, 1), direction = "<")
# Find the threshold that maximizes Youden's Index (sensitivity + specificity - 1)
optimal_coords <- coords(roc_obj, "best", best.method = "youden", ret = "threshold")
# Apply the optimal threshold to generate binary predictions
optimal_pred <- ifelse(rf_pred_prob >= as.numeric(optimal_coords), 1, 0)
# Calculate confusion matrix
conf_matrix <- table(Predicted = optimal_pred, Actual = actual_binary)
print(conf_matrix)
# Calculate sensitivity and specificity
sensitivity <- sum(optimal_pred == 1 & actual_binary == 1) / sum(actual_binary == 1)
specificity <- sum(optimal_pred == 0 & actual_binary == 0) / sum(actual_binary == 0)
cat("Sensitivity:", sensitivity, "\n")
cat("Specificity:", specificity, "\n")
# Calculate the AUC
auc_value <- auc(roc_obj)
cat("AUC on Test Set:", auc_value, "\n")
# Plot the ROC curve
plot(roc_obj, main = "ROC Curve with Optimal Threshold (Youden's Index)")
abline(v = optimal_coords, col = "red", lty = 2) # Add vertical line for optimal threshold
# Convert vectors to factors to use with confusionMatrix()
optimal_pred_factor <- as.factor(optimal_pred)
actual_binary_factor <- as.factor(actual_binary)
# Create a confusion matrix and calculate all statistics
conf_matrix <- confusionMatrix(data = optimal_pred_factor,
reference = actual_binary_factor,
positive = "1", # Set the positive class as "1"
mode = "everything")
# Print the confusion matrix
print(conf_matrix)
## Using ROCR
library(ROCR)
# Create prediction object
pred_obj <- prediction(y_pred_prob, actual_binary)
# Calculate performance for sensitivity + specificity (Youden's Index)
perf_obj <- performance(pred_obj, measure = "tpr", x.measure = "fpr")
# Calculate Youden's Index and find the optimal threshold
youden_index <- [email protected][[1]] + (1 - [email protected][[1]]) - 1
optimal_threshold_rocr <- pred_obj@cutoffs[[1]][which.max(youden_index)]
cat("Optimal threshold (ROCR):", optimal_threshold_rocr, "\n")
# Generate binary predictions based on the optimal threshold
optimal_pred <- ifelse(rf_pred_prob >= optimal_threshold_rocr, 1, 0)
# Calculate confusion matrix using caret
conf_matrix <- confusionMatrix(as.factor(optimal_pred), as.factor(actual_binary), positive = "1")
print(conf_matrix)
```
## Random forest model
```{r}
library(randomForest) # For Random Forest model
library(caret) # For data partitioning and model evaluation
library(pROC)
# Subset the data to include only the top 15 variables
data_rf <- data.frame(data[selected_variables], inc2 = as.factor(data$inc2))
# Split the data into training and testing sets
set.seed(123) # For reproducibility
train_index <- createDataPartition(data_rf$inc2, p = 0.8, list = FALSE)
train_data <- data_rf[train_index, ]
test_data <- data_rf[-train_index, ]
# Fit a Random Forest model using the training data