forked from wpgp/Malawi_Project
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_Pop_Model_Workflow_2018.R
More file actions
1722 lines (1303 loc) · 59.4 KB
/
Copy path03_Pop_Model_Workflow_2018.R
File metadata and controls
1722 lines (1303 loc) · 59.4 KB
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
library(INLA)
library(sf)
library(gstat)
library(spdep)
#library(olsrr)
library(car)
library(caret)
library(tictoc)
library(terra)
library(kableExtra)
library(inlabru)
library(feather)
library(tidyverse)
set.seed(1234) #set seed for reproducibility
options(scipen = 999) # turn off scientific notation for all variables
#options(digits = 3)
#Specify Drive Path
drive_path <- "//Working/MALAWI/Ortis/"
input_path <- paste0(drive_path, "Output_Data/")
shapefile_path <- paste0(drive_path, "Input_Data/Shapefiles/")
output_path <- paste0(drive_path, "Output_Data/")
output_path1 <- paste0(drive_path, "Output_Data/Pop_Rasters/")
#Load data
pop_data <- read.csv(paste0(input_path, "Malawi_2018_data.csv"))
shapefile <- st_read(paste0(shapefile_path, "2018_MPHC_EAs_Final_for_Use_Corrected.shp"))
#create unique id for each district
pop_data <- pop_data %>%
group_by(DIST_NAME) %>%
mutate(dist_id = cur_group_id()) %>%
ungroup()
#Create id for rural urban
pop_data <- pop_data %>%
mutate(rural_urban_id = case_when(
ADM_STATUS == "Rural" ~ 1,
ADM_STATUS == "Urban" ~ 2,
ADM_STATUS == "NA" ~ 1))
#Calculate pop density
pop_data <- pop_data %>%
mutate(pop_density = mphc_total_pop/google_v2_5)
#filter pop_density which is NA
EA_pop <- pop_data %>%
drop_na(pop_density) %>%
filter(!is.infinite(pop_density))
#check summary stats
summary(EA_pop$pop_density)
#Boxplot of density distribution
ggplot(data = EA_pop, aes(y=pop_density))+
geom_boxplot(color="blue", alpha=0.2)
# Density plot of household density
ggplot(data = EA_pop, aes(x = pop_density)) +
geom_density(
fill = "blue",
alpha = 0.4,
color = "blue"
) +
labs(
x = "Pop Density",
y = "Density",
title = "Density Plot of Pop Density"
) +
theme_minimal()
# Remove pop density below 30
EA_pop <- EA_pop %>%
filter(pop_density < 30)
#plot Pop Density
ggplot(data = EA_pop, aes(x = pop_density)) +
geom_histogram(
fill = "blue",
alpha = 0.4,
color = "blue"
) +
labs(
x = "Pop Density",
y = "Density",
title = "Density Plot"
) +
theme_minimal()
#Boxplot of density
ggplot(data = EA_pop, aes(y=pop_density))+
geom_boxplot(color="blue", alpha=0.2)
#check summary stats
summary(EA_pop$pop_density)
##########################################################################################################
# Covariate selection -----------------------------------------------------
#Covs selection
covs <- EA_pop %>%
select(starts_with("x"))
# Calcute mean and standard deviation of covariates
cov_stats <- data.frame(Covariate = colnames(covs),
Mean = apply(covs, 2, mean, na.rm = TRUE),
Std_Dev = apply(covs, 2, sd, na.rm = TRUE))
#Scaling function to scale covariates
stdize <- function(x)
{ stdz <- (x - mean(x, na.rm=T))/sd(x, na.rm=T)
return(stdz) }
#apply scaling function
covs <- apply(covs, 2, stdize) %>% #z-score
as_tibble()
#Select response variable and cbind covs
covs_selection <- EA_pop %>%
select(pop_density) %>%
cbind(covs)
#drop columns with NAs
covs_selection <- covs_selection %>%
select(where(~ !all(is.na(.))))
# Covariate Selection -----------------------------------------------------
#Stepwise covariates selection for pop data
#fit a glm model with poisson distribution
full_model <- glm(pop_density ~ ., data = covs_selection, family = gaussian)
#stepwise selection
step_model1 <- MASS::stepAIC(full_model, direction = "both")
summary(step_model1)
vif(step_model1)
# Function to iteratively drop variables with high VIF
drop_high_vif <- function(model, threshold = 5) {
# Calcuye VIFs
vif_values <- vif(model)
# Loop until all VIFs are below the threshold
while (any(vif_values > threshold)) {
# Find the variable with the highest VIF
max_vif_var <- names(which.max(vif_values))
# Update the formula to exclude the variable with the highest VIF
formula <- as.formula(paste(". ~ . -", max_vif_var))
model <- update(model, formula)
# Recalcuye VIFs
vif_values <- vif(model)
}
return(model)
}
# Apply the function to drop high VIF variables
step1_updated <- drop_high_vif(step_model1)
summary(step1_updated)
vif(step1_updated)
# Extract selected variables
selected_vars <- step1_updated$coefficients%>%
names() # Get the selected variables
# Create model formula
formula_string <- paste("pop_density ~", paste(selected_vars, collapse = " + "))
final_formula <- as.formula(formula_string)
# Print final model formula
print(final_formula)
#function to drop non-significant variables
# Start with full model
current_formula <- as.formula("pop_density ~ x14 + x39 + x41 + x43 + x45 + x46 +
x48 + x49 + x50 + x51 + x52 + x54 + x56 + x57 + x58 + x59 +
x61 + x62 + x63 + x64")
# Loop to drop non-significant variables
repeat {
model <- glm(current_formula, data = covs_selection, family = gaussian)
model_summary <- summary(model)
# Extract p-values (skip intercept)
p_vals <- coef(model_summary)[-1, "Pr(>|t|)"]
# Identify variable with highest p-value
max_pval <- max(p_vals, na.rm = TRUE)
worst_var <- names(p_vals)[which.max(p_vals)]
# Stop if all p-values < 0.05
if (max_pval < 0.05) break
# Drop the variable with the highest p-value
message("Dropping variable: ", worst_var, " (p = ", signif(max_pval, 4), ")")
rhs <- attr(terms(current_formula), "term.labels")
new_rhs <- setdiff(rhs, worst_var)
current_formula <- as.formula(paste("pop_density ~", paste(new_rhs, collapse = " + ")))
}
# Final model
final_model <- model
summary(final_model)
vif(final_model)
# Extract the formula from final model
final_model <- formula(final_model)
final_model
#selected covariates are still many use LASSO regression to rank covariate importance and drop less
#important covariates
#Fit a model using the LASSO with the caret package
#drop NAs in covariates for LASSO fitting
covs_selection1 <- covs_selection %>%
drop_na()
#Lasso Regression
fit1_lasso <- train(
pop_density ~ x14 + x39 + x41 + x43 + x45 + x46 + x48 + x50 +
x51 + x52 + x54 + x56 + x57 + x58 + x59 + x61 + x62 + x63 +
x64,
data = covs_selection1,
method = "glmnet",
metric = "RMSE", # Choose from RMSE, RSquared, AIC, BIC, ...others?
tuneGrid = expand.grid(
.alpha = 1, # optimize a ridge regression
.lambda = seq(0, 5, length.out = 101)))
fit1_lasso
#Select important variables
varImp(fit1_lasso)
#Rank variables
plot(varImp(fit1_lasso))
#Selecting covariates with variable importance above 30
# x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48
#select important variables from pop_data and cbind scaled covariates for model fitting
EA_pop <- EA_pop %>%
select(-starts_with("x")) %>%
cbind(covs)
#
#Assign unique values to each row
EA_pop <- EA_pop %>%
tibble::rowid_to_column("id")
#get distinct count of rural urban
rural_urban_group <- EA_pop %>%
distinct(rural_urban_id) %>%
nrow()
# #get distinct count of district
dist_groups <- EA_pop %>%
distinct(dist_id) %>%
nrow()
# #get distinct count of EA
ea_groups <- EA_pop %>%
distinct(id) %>%
nrow()
#define priors
#hyper.prec = list(theta = list(prior="pc.prec", param=c(0.01,0.01)))
#control.fixed = list(mean=0, prec=1/1000, mean.intercept=0, prec.intercept=1/1000)
#########################################################################
#########################################################################
# Fit Models --------------------------------------------------------------
#Model1 - Fixed Effect + Urban_Rural_Random_Effect
formula1 <- pop_density ~ x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban(rural_urban_id, model = "iid", mapper = bru_mapper_index(n = rural_urban_group))
#fit model using a gamma distribution
mod1_count <- bru(formula1,
data = EA_pop,
family = "gamma",
options = list(
#control.fixed = control.fixed,
control.compute = list(waic = TRUE, cpo = TRUE, dic = TRUE),
control.inla = list(int.strategy = "eb"),
verbose = FALSE,
num.threads = "1"))
summary(mod1_count)
#Extract in-sample predictions
in_sample_predictions1 <- predict(mod1_count, newdata = EA_pop, formula = ~ Intercept +
x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban_eval(rural_urban_id),
n.samples = 100,
seed = 2,
num.threads = "1" )
#Back transform the mean
in_sample_predictions1 <- in_sample_predictions1 %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#sum population
sum(in_sample_predictions1$predicted_population) # Predicted population
sum(in_sample_predictions1$observed_population, na.rm = T) # Observed population
#Compute model performance metrics
#Density metrics
density_metrics1 <- in_sample_predictions1 %>%
# drop_na(observed_density) %>%
mutate(residual = observed_density - predicted_density) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_density, predicted_density))
density_metrics1 %>%
kable()
#Population Metrics
pop_metrics1 <- in_sample_predictions1 %>%
# filter(observed_population > 0) %>%
mutate(residual = observed_population - predicted_population) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_population, predicted_population))
pop_metrics1 %>%
kable()
#############################################################################
#############################################################################
###############################################################################
#Model 2 - Fixed Effect + Urban_Rural_Random_Effect + Dist_Random_Effect
formula2 <- pop_density ~ x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban(rural_urban_id, model = "iid", mapper = bru_mapper_index(n = rural_urban_group))+
Random_dist(dist_id, model = "iid", mapper = bru_mapper_index(n = dist_groups))
#fit model using a gamma distribution
mod2_count <- bru(formula2,
data = EA_pop,
family = "gamma",
options = list(
#control.fixed = control.fixed,
control.compute = list(waic = TRUE, cpo = TRUE, dic = TRUE),
control.inla = list(int.strategy = "eb"),
verbose = FALSE,
num.threads = "1"))
summary(mod2_count)
#Extract in-sample predictions
in_sample_predictions2 <- predict(mod2_count, newdata = EA_pop, formula = ~ Intercept +
x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban_eval(rural_urban_id)+
Random_dist_eval(dist_id),
n.samples = 100,
seed = 2,
num.threads = "1" )
#Back transform the mean
in_sample_predictions2 <- in_sample_predictions2 %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#sum population
sum(in_sample_predictions2$predicted_population) # Predicted population
sum(in_sample_predictions2$observed_population) # Observed population
#Compute model performance metrics
#Density metrics
density_metrics2 <- in_sample_predictions2 %>%
#drop_na(observed_density) %>%
mutate(residual = observed_density - predicted_density) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_density, predicted_density))
density_metrics2 %>%
kable()
#Population Metrics
pop_metrics2 <- in_sample_predictions2 %>%
#filter(observed_population > 0) %>%
mutate(residual = observed_population - predicted_population) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_population, predicted_population))
pop_metrics2 %>%
kable()
#############################################################################
#############################################################################
###############################################################################
#Model 3 - Fixed Effect + Urban_Rural_Random_Effect + Dist_Random_Effect + EA Random_Effect
formula3 <- pop_density ~ x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban(rural_urban_id, model = "iid", mapper = bru_mapper_index(n = rural_urban_group))+
Random_dist(dist_id, model = "iid", mapper = bru_mapper_index(n = dist_groups))+
Random_EA(id, model = "iid", mapper = bru_mapper_index(n = ea_groups))
#fit model using a gamma distribution
mod3_count <- bru(formula3,
data = EA_pop,
family = "gamma",
options = list(
#control.fixed = control.fixed,
control.compute = list(waic = TRUE, cpo = TRUE, dic = TRUE),
control.inla = list(int.strategy = "eb"),
verbose = FALSE,
num.threads = "1"))
summary(mod3_count)
#Extract in-sample predictions
in_sample_predictions3 <- predict(mod3_count, newdata = EA_pop, formula = ~ Intercept +
x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban_eval(rural_urban_id)+
Random_EA_eval(id)+
Random_dist_eval(dist_id),
n.samples = 100,
seed = 2,
num.threads = "1" )
#Back transform the mean
in_sample_predictions3 <- in_sample_predictions3 %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#sum population
sum(in_sample_predictions3$predicted_population) # Predicted population
sum(in_sample_predictions3$observed_population) # Observed population
#Compute model performance metrics
#Density metrics
density_metrics3 <- in_sample_predictions3 %>%
#drop_na(observed_density) %>%
mutate(residual = observed_density - predicted_density) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_density, predicted_density))
density_metrics3 %>%
kable()
#Pop metrics
pop_metrics3 <- in_sample_predictions3 %>%
#filter(observed_population > 0) %>%
mutate(residual = observed_population - predicted_population) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_population, predicted_population))
pop_metrics3 %>%
kable()
##############################################################################
#############################################################################
# Geostatistical Model - INLA SPDE ----------------------------------------
#-Define the coordinates of centroids
coords <- cbind(EA_pop$long, EA_pop$lat)
#measure distance between coordinates
summary(dist(coords)) #summarizes the Euclidean distance between points in the spatial domain
#build non-convex hull mesh
non_convex_bdry <- inla.nonconvex.hull(coords, -0.03, -0.05, resolution = c(100, 100))
mesh <- fm_mesh_2d_inla(boundary = non_convex_bdry, max.edge=c(0.1, 1),
offset = c(0.05, 1),
cutoff = 0.003)
plot(mesh)
plot(mesh, add=T)
points(coords, col="red", pch="*")
#Count of mesh nodes
mesh$n
#Build the SPDE
spde <- inla.spde2.matern(mesh = mesh, alpha = 2, constr = TRUE)
#specify model
formula4 <- pop_density ~ x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban(rural_urban_id, model = "iid", mapper = bru_mapper_index(n = rural_urban_group))+
Random_dist(dist_id, model = "iid", mapper = bru_mapper_index(n = dist_groups))+
Random_EA(id, model = "iid", mapper = bru_mapper_index(n = ea_groups))+
Random_Spat(main = coords, model = spde)
#fit model using a gamma distribution
mod4_count <- bru(formula4,
data = EA_pop,
family = "gamma",
options = list(
#control.fixed = control.fixed,
control.compute = list(waic = TRUE, cpo = TRUE, dic = TRUE),
control.inla = list(int.strategy = "eb"),
verbose = FALSE,
num.threads = "1"))
summary(mod4_count)
#Extract in-sample predictions
in_sample_predictions4 <- predict(mod4_count, newdata = EA_pop, formula = ~ Intercept +
x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban_eval(rural_urban_id)+
Random_EA_eval(id)+
Random_dist_eval(dist_id)+
Random_Spat_eval(cbind(long, lat)),
n.samples = 100,
seed = 2,
num.threads = "1" )
#Back transform the mean
in_sample_predictions4 <- in_sample_predictions4 %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#sum population
sum(in_sample_predictions4$predicted_population) # Predicted population
sum(in_sample_predictions4$observed_population) # Observed population
#Compute model performance metrics
#Density metrics
density_metrics4 <- in_sample_predictions4 %>%
#drop_na(observed_density) %>%
mutate(residual = observed_density - predicted_density) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_density, predicted_density))
density_metrics4 %>%
kable()
#Total Population
pop_metrics4 <- in_sample_predictions4 %>%
# filter(observed_population > 0) %>%
mutate(residual = observed_population - predicted_population) %>%
summarise(
Bias= mean(residual),
Imprecision = sd(residual),
mae = mean(abs(residual)),
mse = mean((residual)^2),
rmse = sqrt(mse),
Corr = cor(observed_population, predicted_population))
pop_metrics4 %>%
kable()
# Model Checks ------------------------------------------------------------
t(c(mod1_count=mod1_count$dic$dic, mod2_count=mod2_count$dic$dic,
mod3_count=mod3_count$dic$dic, mod4_count=mod4_count$dic$dic))
#compare models
pop <- rbind(pop_metrics1, pop_metrics2, pop_metrics3, pop_metrics4)
pop%>% kable()
dens <- rbind(density_metrics1, density_metrics2, density_metrics3, density_metrics4)
dens %>% kable()
##############################################################################################
##############################################################################################
########## CROSS VALIDATION #############################################################
#Xval data
xval_data <- EA_pop
# K-Fold Cross Validation for Model 4-------------------------------------------------
# function to calculate k-fold
kfold_cv <- function(data, k) {
n <- nrow(data)
fold_size <- n %/% k
folds <- sample(rep(1:k, each = fold_size, length.out = n))
# Create separate dataframes for train and test metrics
train_metrics <- data.frame()
test_metrics <- data.frame()
# Place holder for train metrics calculation ----------------------------
#density metrics
dens_train_rmse_values <- numeric(k) # Placeholder for RMSE
dens_train_pearson_values <- numeric(k) # Placeholder for corr
dens_train_mae_values <- numeric(k) # Placeholder for MAE
dens_train_bias_values <- numeric(k) # Placeholder for bias
#HH metrics
pop_train_rmse_values <- numeric(k) # Placeholder for RMSE
pop_train_pearson_values <- numeric(k) # Placeholder for corr
pop_train_mae_values <- numeric(k) # Placeholder for MAE
pop_train_bias_values <- numeric(k) # Placeholder for bias
# Place holder for test metrics calculation -------------------------
#Density metrics
dens_test_rmse_values <- numeric(k) # Placeholder for RMSE
dens_test_pearson_values <- numeric(k) # Placeholder for corr
dens_test_mae_values <- numeric(k) # Placeholder for MAE
dens_test_bias_values <- numeric(k) # Placeholder for bias
#HH metrics
pop_test_rmse_values <- numeric(k) # Placeholder for RMSE
pop_test_pearson_values <- numeric(k) # Placeholder for corr
pop_test_mae_values <- numeric(k) # Placeholder for MAE
pop_test_bias_values <- numeric(k) # Placeholder for bias
# Initialize data frame to store test values and predictions outside the loop
results_df <- data.frame(random_effect = numeric(), Total_Building_Count = numeric(),
folds = numeric(), observed_density = numeric(),
predicted_density = numeric(), observed_population = numeric(),
predicted_population =numeric())
train_results_df <- data.frame(random_effect = numeric(), Total_Building_Count = numeric(),
folds = numeric(), observed_density = numeric(),
predicted_density = numeric(), observed_population = numeric(),
predicted_population =numeric())
# For loop for implementation ---------------------------------------------
for (i in 1:k) {
test_indices <- which(folds == i)
train_indices <- which(folds != i)
train_data <- data[train_indices, ]
test_data <- data[test_indices, ]
#create a new cluster id for the train data
train_data <- train_data %>%
rowid_to_column("idx")
# #get distinct count of idx
train_id_groups <- train_data %>%
distinct(idx) %>%
nrow()
#create a new idx in test data for evaluation
test_data <- test_data %>%
mutate(idx = (train_id_groups+1) : (train_id_groups + nrow(test_data)))
print(paste("Processing fold", i, "out of", k))
#-Define the coordinates of centroids
coords <- cbind(train_data$long, train_data$lat)
#measure distance between coordinates
summary(dist(coords)) #summarizes the Euclidean distance between points in the spatial domain
#build non-convex hull mesh
non_convex_bdry <- inla.nonconvex.hull(coords, -0.03, -0.05, resolution = c(100, 100))
mesh <- fm_mesh_2d_inla(boundary = non_convex_bdry, max.edge=c(0.1, 1),
offset = c(0.05, 1),
cutoff = 0.003)
#Build the SPDE
spde <- inla.spde2.matern(mesh = mesh, alpha = 2, constr = TRUE)
#Model formula
formula4 <- pop_density ~ x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban(rural_urban_id, model = "iid", mapper = bru_mapper_index(n = rural_urban_group))+
Random_dist(dist_id, model = "iid", mapper = bru_mapper_index(n = dist_groups))+
Random_EA(idx, model = "iid", mapper = bru_mapper_index(n = train_id_groups))+
Random_Spat(main = coords, model = spde)
#fit model using a gamma distribution
mod2 <- bru(formula4,
data = train_data,
family = "gamma",
options = list(
control.compute = list(waic = TRUE, cpo = TRUE, dic = TRUE),
control.inla = list(int.strategy = "eb"),
verbose = FALSE))
#summary(mod2)
#Make Predictions for train data
train_predictions <- predict(mod2, newdata = train_data, formula = ~ Intercept +
x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban_eval(rural_urban_id)+
Random_EA_eval(idx)+
Random_dist_eval(dist_id)+
Random_Spat_eval(cbind(long, lat)),
n.samples = 100,
seed = 2)
#Back transform the mean
train_predictions <- train_predictions %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#Train data metrics
#Density
dens_train_rmse_values[i] <- sqrt(mean((train_predictions$observed_density - train_predictions$predicted_density)^2))
dens_train_pearson_values[i] <- cor(train_predictions$observed_density, train_predictions$predicted_density)
dens_train_mae_values[i] <- mean(abs(train_predictions$observed_density - train_predictions$predicted_density))
dens_train_bias_values[i] <- mean(train_predictions$observed_density - train_predictions$predicted_density)
#Population
pop_train_rmse_values[i] <- sqrt(mean((train_predictions$observed_population - train_predictions$predicted_population)^2))
pop_train_pearson_values[i] <- cor(train_predictions$observed_population, train_predictions$predicted_population)
pop_train_mae_values[i] <- mean(abs(train_predictions$observed_population - train_predictions$predicted_population))
pop_train_bias_values[i] <- mean(train_predictions$observed_population - train_predictions$predicted_population)
# Make Predictions for Test Data ------------------------------------------
#Make Predictions for test data
test_predictions <- predict(mod2, newdata = test_data, formula = ~ Intercept +
x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban_eval(rural_urban_id)+
Random_EA_eval(idx)+
Random_dist_eval(dist_id)+
Random_Spat_eval(cbind(long, lat)),
n.samples = 100,
seed = 2)
#Back transform the mean
test_predictions <- test_predictions %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#Test data metrics
#Density
dens_test_rmse_values[i] <- sqrt(mean((test_predictions$observed_density - test_predictions$predicted_density)^2))
dens_test_pearson_values[i] <- cor(test_predictions$observed_density, test_predictions$predicted_density)
dens_test_mae_values[i] <- mean(abs(test_predictions$observed_density - test_predictions$predicted_density))
dens_test_bias_values[i] <- mean(test_predictions$observed_density - test_predictions$predicted_density)
#Population
pop_test_rmse_values[i] <- sqrt(mean((test_predictions$observed_population - test_predictions$predicted_population)^2))
pop_test_pearson_values[i] <- cor(test_predictions$observed_population, test_predictions$predicted_population)
pop_test_mae_values[i] <- mean(abs(test_predictions$observed_population - test_predictions$predicted_population))
pop_test_bias_values[i] <- mean(test_predictions$observed_population - test_predictions$predicted_population)
# Append observed and predictions to results_df with fold information
fold_results <- data.frame(random_effect = test_predictions$id,
Total_Building_Count = test_predictions$google_v2_5,
folds = i, observed_density = test_predictions$observed_density,
predicted_density = test_predictions$predicted_density,
observed_population= test_predictions$observed_population,
predicted_population = test_predictions$predicted_population)
results_df <- rbind(results_df, fold_results)
# Train metrics
train_metrics <- data.frame(Model = "Model 4",
dens_train_rmse = mean(dens_train_rmse_values),
dens_train_corr = mean(dens_train_pearson_values),
dens_train_mae = mean(dens_train_mae_values),
dens_train_bias = mean(dens_train_bias_values),
pop_train_rmse = mean(pop_train_rmse_values),
pop_train_corr = mean(pop_train_pearson_values),
pop_train_mae = mean(pop_train_mae_values),
pop_train_bias = mean(pop_train_bias_values)
)
# Test metrics
test_metrics <- data.frame(Model = "Model 4",
dens_test_rmse = mean(dens_test_rmse_values),
dens_test_corr = mean(dens_test_pearson_values),
dens_test_mae = mean(dens_test_mae_values),
dens_test_bias = mean(dens_test_bias_values),
pop_test_rmse = mean(pop_test_rmse_values),
pop_test_corr = mean(pop_test_pearson_values),
pop_test_mae = mean(pop_test_mae_values),
pop_test_bias = mean(pop_test_bias_values)
)
}
# Return separate lists for density and population metrics
list(train_metrics = train_metrics, test_metrics = test_metrics,
results_df = results_df, train_results_df = train_results_df)
}
# Apply function
result1 <- kfold_cv(data = xval_data, k = 10)
#Train data results
result1$train_metrics %>%
kable()
#Test data results
result1$test_metrics %>%
kable()
#Get results as a dataframe
result_df <- result1$results_df %>%
as_tibble()
#write to file
#write.csv(paste0(output_path1, "random_kfold_prediction.csv"), row.names = T)
############################################################################################
############################################################################################
# INLA Group CV Model 2-------------------------------------------------
# function to calculate k-fold
lgocv <- function(data, k) {
n <- nrow(data)
fold_size <- n %/% k
folds <- sample(rep(1:k, each = fold_size, length.out = n))
# Create separate dataframes for train and test metrics
train_metrics <- data.frame()
test_metrics <- data.frame()
# Place holder for train metrics calculation ----------------------------
#density metrics
dens_train_rmse_values <- numeric(k) # Placeholder for RMSE
dens_train_pearson_values <- numeric(k) # Placeholder for corr
dens_train_mae_values <- numeric(k) # Placeholder for MAE
dens_train_bias_values <- numeric(k) # Placeholder for bias
#HH metrics
pop_train_rmse_values <- numeric(k) # Placeholder for RMSE
pop_train_pearson_values <- numeric(k) # Placeholder for corr
pop_train_mae_values <- numeric(k) # Placeholder for MAE
pop_train_bias_values <- numeric(k) # Placeholder for bias
# Place holder for test metrics calculation -------------------------
#Density metrics
dens_test_rmse_values <- numeric(k) # Placeholder for RMSE
dens_test_pearson_values <- numeric(k) # Placeholder for corr
dens_test_mae_values <- numeric(k) # Placeholder for MAE
dens_test_bias_values <- numeric(k) # Placeholder for bias
#HH metrics
pop_test_rmse_values <- numeric(k) # Placeholder for RMSE
pop_test_pearson_values <- numeric(k) # Placeholder for corr
pop_test_mae_values <- numeric(k) # Placeholder for MAE
pop_test_bias_values <- numeric(k) # Placeholder for bias
# Initialize data frame to store test values and predictions outside the loop
results_df <- data.frame(random_effect = numeric(), Total_Building_Count = numeric(),
folds = numeric(), observed_density = numeric(),
predicted_density = numeric(), observed_population = numeric(),
predicted_population =numeric())
# For loop for implementation ---------------------------------------------
for (i in 1:k) {
test_indices <- which(folds == i)
train_indices <- which(folds != i)
train_data <- data[train_indices, ]
test_data <- data[test_indices, ]
#tag train dataset
train_data <- train_data %>%
mutate(observed_data = pop_density, dataset = "train")
#tag test dataset
test_data <- test_data %>%
mutate(observed_data = NA, dataset = "test")
#combine data
xval_data <- rbind(train_data, test_data)
#-Define the coordinates of centroids
coords <- cbind(xval_data$long, xval_data$lat)
#measure distance between coordinates
summary(dist(coords)) #summarizes the Euclidean distance between points in the spatial domain
#build non-convex hull mesh
non_convex_bdry <- inla.nonconvex.hull(coords, -0.03, -0.05, resolution = c(100, 100))
mesh <- fm_mesh_2d_inla(boundary = non_convex_bdry, max.edge=c(0.1, 1),
offset = c(0.05, 1),
cutoff = 0.003)
#Build the SPDE
spde <- inla.spde2.matern(mesh = mesh, alpha = 2, constr = TRUE)
#print fold
print(paste("Processing fold", i, "out of", k))
formula4 <- observed_data ~ x14 + x63 + x59 + x45 + x54 + x52 + x50 + x48 +
Random_rural_urban(rural_urban_id, model = "iid", mapper = bru_mapper_index(n = rural_urban_group))+
Random_dist(dist_id, model = "iid", mapper = bru_mapper_index(n = dist_groups))+
Random_EA(id, model = "iid", mapper = bru_mapper_index(n = ea_groups))+
Random_Spat(main = coords, model = spde)
#fit model using a gamma distribution
mod2 <- bru(formula4,
data = xval_data,
family = "gamma",
options = list(
control.compute = list(waic = TRUE, cpo = TRUE, dic = TRUE),
control.inla = list(int.strategy = "eb"),
verbose = FALSE))
#summary(mod2)
#LGOCV
results <- inla.group.cv(mod2, num.level.sets = 3)
#Mean predictions
cv <- data.frame(mean = results$mean)
predictions <- cbind(xval_data, cv) %>%
as_tibble()
#Back transform the mean
train_predictions <- predictions %>%
filter(dataset == "train") %>%
mutate (predicted_density = exp(mean),
predicted_population = predicted_density * google_v2_5) %>%
rename(observed_population = mphc_total_pop, observed_density = pop_density)
#Train data metrics
#Density
dens_train_rmse_values[i] <- sqrt(mean((train_predictions$observed_density - train_predictions$predicted_density)^2))
dens_train_pearson_values[i] <- cor(train_predictions$observed_density, train_predictions$predicted_density)
dens_train_mae_values[i] <- mean(abs(train_predictions$observed_density - train_predictions$predicted_density))
dens_train_bias_values[i] <- mean(train_predictions$observed_density - train_predictions$predicted_density)