-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.syn.r
1405 lines (1170 loc) · 47.5 KB
/
functions.syn.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
# Functions for synthesising data, some of which are adapted
# from mice package by S. van Buuren and K. Groothuis-Oudshoorn,
# TNO Quality of Life
###-----.norm.fix.syn------------------------------------------------------
.norm.fix.syn <- function(y, x, ridge = 0.00001, ...)
{
# Calculates regression coefficients + error estimate
xtx <- t(x) %*% x
pen <- ridge * diag(xtx)
if (length(pen)==1) pen <- matrix(pen)
v <- solve(xtx + diag(pen))
coef <- t(y %*% x %*% v)
residuals <- y - x %*% coef
sigma <- sqrt((sum(residuals^2))/(length(y)-ncol(x)-1))
parm <- list(coef, sigma)
names(parm) <- c("beta","sigma")
return(parm)
}
###-----.norm.draw.syn-----------------------------------------------------
.norm.draw.syn <- function(y, x, ridge = 0.00001, ...)
{
# Draws values of beta and sigma for Bayesian linear regression synthesis
# of y given x according to Rubin p.167
xtx <- t(x) %*% x
pen <- ridge * diag(xtx)
if (length(pen)==1) pen <- matrix(pen)
v <- solve(xtx + diag(pen))
coef <- t(y %*% x %*% v)
residuals <- y - x %*% coef
sigma.star <- sqrt(sum((residuals)^2)/rchisq(1, length(y) - ncol(x)))
beta.star <- coef + (t(chol((v + t(v))/2)) %*% rnorm(ncol(x))) * sigma.star
parm <- list(coef, beta.star, sigma.star)
names(parm) <- c("coef","beta","sigma")
return(parm)
}
###-----syn.norm-----------------------------------------------------------
syn.norm <- function(y, x, xp, proper = FALSE, ...)
{
x <- cbind(1, as.matrix(x))
xp <- cbind(1, as.matrix(xp))
if (proper == FALSE){
parm <- .norm.fix.syn(y, x, ...)
} else {
parm <- .norm.draw.syn(y, x, ...)
}
res <- xp %*% parm$beta + rnorm(nrow(xp)) * parm$sigma
res <- round(res, max(sapply(y, decimalplaces)))
return(list(res = res, fit = parm))
}
###-----syn.lognorm--------------------------------------------------------
syn.lognorm <- function(y, x, xp, proper = FALSE, ...)
{
addbit <- FALSE
if (any(y < 0)) stop("Log transformation not appropriate for negative values.\n", call. = FALSE)
if (any(y == 0)) {y <- y + .5*min(y[y != 0]); y <- log(y); addbit <- TRUE} ## warning about this and above should be in check model
else y <- log(y)
x <- cbind(1, as.matrix(x))
xp <- cbind(1, as.matrix(xp))
if (proper == FALSE) {
parm <- .norm.fix.syn(y, x, ...)
} else {
parm <- .norm.draw.syn(y, x, ...)
}
res <- xp %*% parm$beta + rnorm(nrow(xp)) * parm$sigma
if (addbit) {res <- res - .5 * min(y[y != 0]); res[res <= 0] <- 0}
res <- exp(res)
res <- round(res, max(sapply(y, decimalplaces)))
return(list(res = res, fit = parm))
}
###-----syn.sqrtnorm-------------------------------------------------------
syn.sqrtnorm <- function(y, x, xp, proper = FALSE, ...)
{
addbit <- FALSE
if (any(y < 0)) stop("Square root transformation not appropriate for negative values.\n", call. = FALSE) ## needs check in checkmodel
else y <- sqrt(y)
x <- cbind(1, as.matrix(x))
xp <- cbind(1, as.matrix(xp))
if (proper == FALSE) {
parm <- .norm.fix.syn(y, x, ...)
} else {
parm <- .norm.draw.syn(y, x, ...)
}
res <- xp %*% parm$beta + rnorm(nrow(xp)) * parm$sigma
res <- res^2
res <- round(res, max(sapply(y, decimalplaces)))
return(list(res = res, fit = parm))
}
###-----syn.cubertnorm-----------------------------------------------------
syn.cubertnorm <- function(y, x, xp, proper = FALSE, ...)
{
addbit <- FALSE
y <- sign(y)*abs(y)^(1/3)
x <- cbind(1, as.matrix(x))
xp <- cbind(1, as.matrix(xp))
if (proper == FALSE) {
parm <- .norm.fix.syn(y, x, ...)
} else {
parm <- .norm.draw.syn(y, x, ...)
}
res <- xp %*% parm$beta + rnorm(nrow(xp)) * parm$sigma
res <- res^3
res <- round(res, max(sapply(y, decimalplaces)))
return(list(res = res, fit = parm))
}
###-----syn.normrank-------------------------------------------------------
syn.normrank <- function(y, x, xp, smoothing = "", proper = FALSE, ...)
{
# Regression synthesis of y given x, with a fixed regression
# line, and with random draws of the residuals around the line.
# Adapted from norm by carrying out regression on Z scores from ranks
# predicting new Z scores and then transforming back
# similar to method by ? and ?
#
# First get approx rank position of vector in one of another length
# so that result returned has correct length for xp
# matters for sub-samples and missing data
z <- qnorm(rank(y)/(length(y) + 1))
x <- cbind(1, as.matrix(x))
xp <- cbind(1, as.matrix(xp))
if (proper == FALSE) {
parm <- .norm.fix.syn(z, x, ...)
} else {
parm <- .norm.draw.syn(z, x, ...)
}
pred <- (xp %*% parm$beta + rnorm(nrow(xp)) * parm$sigma)
res <- round(pnorm(pred)*(length(y) + 1))
res[res < 1] <- 1
res[res > length(y)] <- length(y)
res <- sort(y)[res]
if (smoothing != "") {
res <- syn.smooth(res, y, smoothing = smoothing)
}
# if (smoothing == "") res <- sort(y)[res]
#
# if (smoothing == "density") {
# ydsamp <- y
# ys <- 1:length(y)
# maxfreq <- which.max(table(y))
# maxcat <- as.numeric(names(table(y))[maxfreq])
# if (table(y)[maxfreq]/sum(table(y)) > .7) ys <- which(y != maxcat)
# if (10 * table(y)[length(table(y)) - 1] <
# tail(table(y), n = 1) - table(y)[length(table(y)) - 1]) {
# ys <- ys[-which(y == max(y))]
# maxy <- max(y)
# }
# densbw <- density(y[ys], width = "SJ")$bw
# ydsamp[ys] <- rnorm(length(ydsamp[ys]),
# mean = sample(ydsamp[ys], length(ydsamp[ys]), replace = TRUE), sd = densbw)
# if (!exists("maxy")) maxy <- max(y) + densbw
# ydsamp[ys] <- pmax(pmin(ydsamp[ys],maxy),min(y))
# res <- sort(ydsamp)[res]
# }
return(list(res = res, fit = parm))
}
###-----.pmm.match---------------------------------------------------------
.pmm.match <- function(z, yhat = yhat, y = y, donors = 3, ...)
{
# Auxilary function for syn.pmm.
# z = target predicted value (scalar)
# yhat = array of fitted values, to be matched against z
# y = array of donor data values
# Finds the three cases for which abs(yhat-z) is minimal,
# and makes a random draw from these.
d <- abs(yhat - z)
m <- sample(y[rank(d, ties.method = "random") <= donors], 1)
return(m)
}
###-----syn.pmm------------------------------------------------------------
syn.pmm <- function(y, x, xp, smoothing = "", proper = FALSE, ...)
{
# Synthesis of y by predictive mean matching
# Warning: can be slow for large data sets
# for which syn.normrank may be a better choice
x <- cbind(1, as.matrix(x))
xp <- cbind(1, as.matrix(xp))
if (proper == FALSE) {
parm <- .norm.fix.syn(y, x, ...)
} else {
parm <- .norm.draw.syn(y, x, ...)
}
yhatobs <- x %*% parm$coef
yhatmis <- xp %*% parm$beta
res <- apply(as.array(yhatmis), 1, .pmm.match, yhat = yhatobs, y = y, ...)
if (smoothing != "") {
res <- syn.smooth(res, y, smoothing = smoothing)
}
return(list(res = res, fit = parm))
}
###-----augment.syn--------------------------------------------------------
augment.syn <- function(y, x, ...)
{
# define augmented data for stabilizing logreg and polyreg
# by the ad hoc procedure of White, Daniel & Royston, CSDA, 2010
# This function will prevent augmented data beyond the min and
# the max of the data
# Input:
# x: numeric data.frame (n rows)
# y: factor or numeric vector (length n)
# Output:
# return a list with elements y, x, and w with length n+2*(ncol(x))*length(levels(y))
x <- as.data.frame(x)
icod <- sort(unique(unclass(y)))
ki <- length(icod)
# if (ki>maxcat) stop(paste("Maximum number of categories (",maxcat,") exceeded", sep=""))
p <- ncol(x)
# skip augmentation if there are no predictors
if (p == 0) return(list(y = y, x = x, w = rep(1, length(y))))
# skip augmentation if there is only 1 missing value
if (length(y) == 1) return(list(y = y, x = x, w = rep(1, length(y))))
# calculate values to augment
mean <- apply(x,2,mean)
sd <- sqrt(apply(x,2,var))
minx <- apply(x,2,min)
maxx <- apply(x,2,max)
nr <- 2 * p * ki
a <- matrix(mean, nrow = nr, ncol = p, byrow = TRUE)
b <- matrix(rep(c(rep(c(0.5, -0.5), ki), rep(0,nr)), length = nr*p),
nrow = nr, ncol = p, byrow = FALSE)
c <- matrix(sd, nrow = nr, ncol = p, byrow = TRUE)
d <- a + b * c
d <- pmax(matrix(minx, nrow = nr, ncol = p, byrow = TRUE), d)
d <- pmin(matrix(maxx, nrow = nr, ncol = p, byrow = TRUE), d)
e <- rep(rep(icod, each = 2), p)
dimnames(d) <- list(paste("AUG", 1:nrow(d), sep = ""), dimnames(x)[[2]])
xa <- rbind.data.frame(x, d)
# beware, concatenation of factors
# this change needed to avoid reordering of factors
# if (is.factor(y)) ya <- as.factor(levels(y)[c(y,e)]) else ya <- c(y, e)
if (is.factor(y)) ya <- addNA(factor(levels(y)[c(y, e)],
levels = levels(y)), ifany = TRUE) else ya <- c(y, e)
wa <- c(rep(1, length(y)),rep((p + 1)/nr, nr))
return(list(y = ya, x = xa, w = wa))
}
###-----syn.logreg---------------------------------------------------------
syn.logreg <- function(y, x, xp, denom = NULL, denomp = NULL,
proper = FALSE, ...)
{
# Synthesis for binary or binomial response variables by
# logistic regression model. See Rubin (1987, p. 169-170) for
# a description of the method.
# The method consists of the following steps:
# 1. Fit a logit, and find (bhat, V(bhat))
# 2. Draw BETA from N(bhat, V(bhat))
# 3. Compute predicted scores for m.d., i.e. logit-1(X BETA)
# 4. Compare the score to a random (0,1) deviate, and synthesise.
xmeans <- lapply(x, mean) ## x matrix centred
x <- mapply(function(x, y) x - y, x, xmeans)
xp <- mapply(function(x, y) x - y, xp, xmeans) ## also xp to match
if (is.null(denom)) {
aug <- augment.syn(y, x, ...)
# when no missing data must set xf to augmented version
xf <- aug$x
y <- aug$y
w <- aug$w
xf <- cbind(1, as.matrix(xf))
xp <- cbind(1, as.matrix(xp))
expr <- expression(glm.fit(xf, y, family = binomial(link = logit), weights = w))
fit <- suppressWarnings(eval(expr))
fit.sum <- summary.glm(fit)
beta <- coef(fit)
if (proper == TRUE) {
rv <- t(chol(fit.sum$cov.unscaled))
beta <- beta + rv %*% rnorm(ncol(rv))
}
p <- 1/(1 + exp(-(xp %*% beta)))
vec <- (runif(nrow(p)) <= p)
if (!is.logical(y)) vec <- as.numeric(vec)
if (is.factor(y)) vec <- factor(vec,c(0,1), labels = levels(y))
} else {
aug <- augment.syn(y, x, ...)
# when no missing data must set xf to augmented version
xf <- aug$x
y <- aug$y
w <- aug$w
xf <- cbind(1, as.matrix(xf))
xp <- cbind(1, as.matrix(xp))
den <- w
denind <- which(den == 1)
den[denind] <- denom
yy <- y/den #denom give then average response
yy[den < 1] <- mean(yy[denind])
expr <- expression(glm.fit(xf, yy, family = binomial(link = logit), weights = den))
fit <- suppressWarnings(eval(expr))
fit.sum <- summary.glm(fit)
beta <- coef(fit.sum)[, 1]
if (proper == TRUE) {
rv <- t(chol(fit.sum$cov.unscaled))
beta <- beta + rv %*% rnorm(ncol(rv))
}
p <- 1/(1 + exp(-(xp %*% beta)))
vec <- rbinom(nrow(p),denomp, p)
}
return(list(res = vec, fit = fit.sum))
}
###-----
syn.bayesian.norm <- function(y, ry, x, wy = NULL, ...) {
if (is.null(wy)) wy <- !ry
x <- cbind(1, as.matrix(x))
parm <- .norm.draw(y, ry, x, ...)
x[wy, ] %*% parm$beta + rnorm(sum(wy)) * parm$sigma
}
syn.lasso.norm <- function(y, ry, x, wy = NULL, nfolds = 10, ...) {
install.on.demand("glmnet", ...)
# Bootstrap sample
if (is.null(wy)) wy <- !ry
n1 <- sum(ry)
s <- sample(n1, n1, replace = TRUE)
x_glmnet <- cbind(1, x)
dotxobs <- x_glmnet[ry, , drop = FALSE][s, , drop = FALSE]
dotyobs <- y[ry][s]
# Train imputation model
cv_lasso <- glmnet::cv.glmnet(
x = dotxobs, y = dotyobs,
family = "gaussian",
nfolds = nfolds,
alpha = 1
)
# Obtain imputations
s2hat <- mean((predict(cv_lasso, dotxobs, s = "lambda.min") - dotyobs)^2)
as.vector(predict(cv_lasso, x_glmnet[wy, ], s = "lambda.min")) +
rnorm(sum(wy), 0, sqrt(s2hat))
}
syn.lasso.logreg <- function(y, ry, x, wy = NULL, nfolds = 10, ...) {
install.on.demand("glmnet", ...)
if (is.null(wy)) wy <- !ry
# Bootstrap sample
n1 <- sum(ry)
s <- sample(n1, n1, replace = TRUE)
x_glmnet <- cbind(1, x)
dotxobs <- x_glmnet[ry, , drop = FALSE][s, , drop = FALSE]
dotyobs <- y[ry][s]
# Train imputation model
cv_lasso <- glmnet::cv.glmnet(
x = dotxobs, y = dotyobs,
family = "binomial",
nfolds = nfolds,
alpha = 1
)
# Obtain imputation
p <- 1 / (1 + exp(-predict(cv_lasso, x_glmnet[wy, ], s = "lambda.min")))
vec <- (runif(nrow(p)) <= p)
vec[vec] <- 1
if (is.factor(y)) {
vec <- factor(vec, c(0, 1), levels(y))
}
vec
}
syn.proportional.odds.model <- function(y, ry, x, wy = NULL, nnet.maxit = 100,
nnet.trace = FALSE, nnet.MaxNWts = 1500,
polr.to.loggedEvents = FALSE, ...) {
if (is.null(wy)) wy <- !ry
# augment data to evade issues with perfect prediction
x <- as.matrix(x)
aug <- augment(y, ry, x, wy)
x <- aug$x
y <- aug$y
ry <- aug$ry
wy <- aug$wy
w <- aug$w
xy <- cbind.data.frame(y = y, x = x)
## polr may fail on sparse data. We revert to multinom in such cases.
fit <- try(
suppressWarnings(MASS::polr(formula(xy),
data = xy[ry, , drop = FALSE],
weights = w[ry],
control = list(...)
)),
silent = TRUE
)
if (inherits(fit, "try-error")) {
if (polr.to.loggedEvents) {
updateLog(out = "polr falls back to multinom", frame = 6)
}
fit <- nnet::multinom(formula(xy),
data = xy[ry, , drop = FALSE],
weights = w[ry],
maxit = nnet.maxit, trace = nnet.trace,
MaxNWts = nnet.MaxNWts, ...
)
}
post <- predict(fit, xy[wy, , drop = FALSE], type = "probs")
if (sum(wy) == 1) {
post <- matrix(post, nrow = 1, ncol = length(post))
}
fy <- as.factor(y)
nc <- length(levels(fy))
un <- rep(runif(sum(wy)), each = nc)
if (is.vector(post)) {
post <- matrix(c(1 - post, post), ncol = 2)
}
draws <- un > apply(post, 1, cumsum)
idx <- 1 + apply(draws, 2, sum)
levels(fy)[idx]
}
syn.lda <- function(y, ry, x, wy = NULL, ...) {
install.on.demand("MASS", ...)
if (is.null(wy)) wy <- !ry
fy <- as.factor(y)
nc <- length(levels(fy))
# SvB June 2009 - take bootstrap sample of training data
# idx <- sample((1:length(y))[ry], size=sum(ry), replace=TRUE)
# x[ry,] <- x[idx,]
# y[ry] <- y[idx]
# end bootstrap
fit <- MASS::lda(x, fy, subset = ry)
post <- predict(fit, x[wy, , drop = FALSE])$posterior
un <- rep(runif(sum(wy)), each = nc)
idx <- 1 + apply(un > apply(post, 1, cumsum), 2, sum)
levels(fy)[idx]
}
###-----syn.polyreg--------------------------------------------------------
syn.polyreg <- function(y, x, xp, proper = FALSE, maxit = 1000,
trace = FALSE, MaxNWts = 10000, ...)
{
# synthesis for categorical response variables by the Bayesian
# polytomous regression model. See J.P.L. Brand (1999), Chapter 4,
# Appendix B.
#
# The method consists of the following steps:
# 1. Fit categorical response as a multinomial model
# 2. Compute predicted categories
# 3. Add appropriate noise to predictions.
#
# This algorithm uses the function multinom from the libraries nnet and MASS
# (Venables and Ripley).
x <- as.matrix(x)
xp <- as.matrix(xp)
if (proper == TRUE) { # bootstrap to make proper
s <- sample(length(y), replace = TRUE)
x <- x[s, , drop = FALSE]
y <- y[s]
y <- factor(y)
}
aug <- augment.syn(y, x, ...)
# yf and xf needed for augmented data to save x as non augmented not now needed can tidy
xf <- aug$x
yf <- aug$y
w <- aug$w
### rescaling numeric to [0,1]
toscale <- sapply(xf, function(z) (is.numeric(z) & (any(z < 0) | any(z > 1))))
rsc <- sapply(xf[, toscale, drop = FALSE], range)
xf_sc <- xf
for (i in names(toscale[toscale == TRUE])) xf_sc[, i] <- (xf_sc[, i] - rsc[1,i])/(rsc[2,i] - rsc[1,i])
for (i in names(toscale[toscale == TRUE])) xp[, i] <- (xp[, i] - rsc[1,i])/(rsc[2,i] - rsc[1,i])
###
xfy <- cbind.data.frame(yf, xf_sc)
fit <- multinom(formula(xfy), data = xfy, weights = w,
maxit = maxit, trace = trace, MaxNWts = MaxNWts, ...)
if (fit$convergence == 1) cat("\nReached max number of iterations for a multinomial model\nsuggest rerunning with polyreg.maxit increased (default 1000)\n")
post <- predict(fit, xp, type = "probs")
if (length(y) == 1) post <- matrix(post, nrow = 1, ncol = length(post))
if (!is.factor(y)) y <- as.factor(y)
nc <- length(levels(yf))
un <- rep(runif(nrow(xp)), each = nc)
if (is.vector(post)) post <- matrix(c(1 - post, post), ncol = 2)
draws <- un > apply(post, 1, cumsum)
idx <- 1 + apply(draws, 2, sum)
res <- levels(yf)[idx]
if (length(table(res)) == 1) {
cat("\n***************************************************************************************")
cat("\nWarning the polyreg fit produces only one category for the variable being synthesised." )
cat("\nThis may indicate that the function multinom used in polyreg failed to iterate, possibly")
cat("\nbecause the variable is sparse. Check results for this variable carefully.")
cat("\n****************************************************************************************\n")
}
fitted <- summary(fit)
return(list(res = res, fit = fitted))
}
###-----syn.polr-----------------------------------------------------------
syn.polr <- function(y, x, xp, proper = FALSE, maxit = 1000,
trace = FALSE, MaxNWts = 10000, ...)
{
x <- as.matrix(x)
xp <- as.matrix(xp)
if (proper == TRUE) { # bootstrap to make proper
s <- sample(length(y), replace = TRUE)
x <- x[s,]
y <- y[s]
y <- factor(y)
}
aug <- augment.syn(y, x, ...)
# yf, wf and xf needed for augmented data to save x as non augmented GR
xf <- aug$x
yf <- aug$y
wf <- aug$w
#xy <- cbind.data.frame(y = y, x = xp)
xfy <- cbind.data.frame(yf, xf)
## polr may fail on sparse data. We revert to multinom in such cases.
fit <- try(suppressWarnings(polr(formula(xfy), data = xfy, Hess = TRUE, weights = wf, ...)), silent = TRUE)
if (inherits(fit, "try-error")) {
fit <- multinom(formula(xfy), data = xfy, weights = wf,
maxit = maxit, trace = trace, Hess = TRUE, MaxNWts = MaxNWts, ...)
cat("\tMethod changed to multinomial")
if (fit$convergence == 1) cat("\nReached max number of iterations for a multinomial model\nRerun with polyreg.maxit increased (default 100)\n")
}
post <- predict(fit, xp, type = "probs")
if (length(y) == 1) post <- matrix(post, nrow = 1, ncol = length(post))
y <- as.factor(y)
nc <- length(levels(yf))
un <- rep(runif(nrow(xp)), each = nc)
if (is.vector(post)) post <- matrix(c(1 - post, post), ncol = 2)
draws <- un > apply(post, 1, cumsum)
idx <- 1 + apply(draws, 2, sum)
# this slightly clumsy code needed to ensure y retains its labels and levels
# y[1:length(y)]<-(levels(y)[idx])
res <- levels(yf)[idx]
fitted <- summary(fit)
return(list(res = res, fit = fitted))
}
###-----syn.sample---------------------------------------------------
syn.sample <- function(y, xp, smoothing = "", cont.na = NA, proper = FALSE, ...)
{
# Generates random sample from the observed y's
# with bootstrap if proper == TRUE
if (proper == TRUE) y <- sample(y, replace = TRUE)
yp <- sample(y, size = xp, replace = TRUE)
if (smoothing != "") yp[!(yp %in% cont.na)] <-
syn.smooth(yp[!(yp %in% cont.na)], y[!(y %in% cont.na)],
smoothing = smoothing)
return(list(res = yp, fit = "sample"))
}
###-----syn.passive--------------------------------------------------------
syn.passive <- function(data, func)
{
# Special elementary synthesis method for transformed data.
# SuppressWarnings to avoid message 'NAs by coercion for NAtemp
res <- suppressWarnings(model.frame(as.formula(func), data,
na.action = na.pass))
return(list(res = res, fit = "passive"))
}
###-----syn.cart-----------------------------------------------------------
syn.cart <- function(y, x, xp, smoothing = "", proper = FALSE,
minbucket = 5, cp = 1e-08, ...)
{
ylogical <- is.logical(y)
if (proper == TRUE) {
s <- sample(length(y), replace = TRUE)
x <- x[s,,drop = FALSE]
y <- y[s]
}
#for (j in 1:ncol(x)){
# if(is.factor(x[,j])) {
# attributes(x[,j])$contrasts <- NULL
# attributes(xp[,j])$contrasts <- NULL
# }
#}
minbucket <- max(1, minbucket) # safety
if (!is.factor(y) & !is.logical(y)) {
fit <- rpart(y ~ ., data = as.data.frame(cbind(y, x)), method = "anova",
minbucket = minbucket, cp = cp, ...)
# get leaf number for observed data
leafnr <- floor(as.numeric(row.names(fit$frame[fit$where,])))
# replace yval with leaf number in order to predict later node number
# rather than yval (mean y for observations classified to a leaf)
fit$frame$yval <- as.numeric(row.names(fit$frame))
# predict leaf number
nodes <- predict(object = fit, newdata = xp)
# BN:16/06/20
# node numbering: node * 2 + 0:1
notleaf <- setdiff(nodes, leafnr)
# if (length(notleaf) > 0) {
# for (i in notleaf){
# nodes[which(nodes == i)] <- 2 * i + sample(0:1, 1)
# }
# }
if (length(notleaf) > 0) {
for (i in notleaf){
j <- i
while(!(j %in% leafnr)){
j <- 2 * j + sample(0:1, 1)
}
nodes[which(nodes == i)] <- j
}
}
uniquenodes <- unique(nodes)
new <- vector("numeric",nrow(xp))
for (j in uniquenodes) {
donors <- y[leafnr == j] # values of y in a leaf
new[nodes == j] <- resample(donors, size = sum(nodes == j),
replace = TRUE)
}
if (smoothing != "") new <- syn.smooth(new, y, smoothing = smoothing)
#donor <- lapply(nodes, function(s) y[leafnr == s])
#new <- sapply(1:length(donor),function(s) resample(donor[[s]], 1))
} else {
y <- factor(y)
fit <- rpart(y ~ ., data = as.data.frame(cbind(y, x)), method = "class",
minbucket = minbucket, cp = cp, ...)
nodes <- predict(object = fit, newdata = xp)
new <- apply(nodes, MARGIN = 1, FUN = function(s) resample(colnames(nodes),
size = 1, prob = s))
if (ylogical) {
new <- as.logical(new)
} else {
new <- factor(new, levels = levels(y))
}
}
return(list(res = new, fit = fit))
}
###-----syn.ctree----------------------------------------------------------
syn.ctree <- function(y, x, xp, smoothing = "", proper = FALSE, minbucket = 5,
mincriterion = 0.9, ...)
{
if (proper == TRUE) {
s <- sample(length(y), replace = truehist())
y <- y[s]
x <- x[s, , drop = FALSE]
}
for (i in which(sapply(x, class) != sapply(xp,class))) xp[,i] <-
eval(parse(text = paste0("as.", class(x[,i]), "(xp[,i])", sep = "")))
# Fit a tree
# datact <- partykit::ctree(y ~ ., data = as.data.frame(cbind(y, x)),
# control = partykit::ctree_control(minbucket = minbucket,
# mincriterion = mincriterion, ...))
datact <- ctree(y ~ ., data = as.data.frame(cbind(y,x)),
controls = ctree_control(minbucket = minbucket,
mincriterion = mincriterion, ...))
# fit.nodes <- predict(datact, type = "node")
fit.nodes <- where(datact)
nodes <- unique(fit.nodes)
no.nodes <- length(nodes)
# pred.nodes <- predict(datact, type = "node", newdata = xp)
pred.nodes <- where(datact, newdata = xp)
# Get row numbers for predicted by sampling with replacement from existing data
rowno <- 1:length(y)
newrowno <- vector("integer", nrow(xp))
for (i in nodes) {
newrowno[pred.nodes == i] <- sample(rowno[fit.nodes == i],
length(newrowno[pred.nodes == i]),
replace = TRUE)
}
new <- y[newrowno]
if (!is.factor(y) & smoothing != "") new <-
syn.smooth(new, y, smoothing = smoothing )
return(list(res = new, fit = datact))
}
###-----syn.survctree------------------------------------------------------
syn.survctree <- function(y, yevent, x, xp, proper = FALSE, minbucket = 5, ...)
# time, event - data column numbers
{
if (proper == TRUE) {
s <- sample(length(y), replace = TRUE)
y <- y[s]
x <- x[s, , drop = FALSE]
yevent <- yevent[s]
}
for (i in which(sapply(x, class) != sapply(xp,class))) xp[,i] <-
eval(parse(text = paste0("as.", class(x[,i]), "(xp[,i])", sep = "")))
if (is.factor(yevent)) {
yevent0 <- as.numeric(yevent) - 1
} else {
yevent0 <- yevent
}
# Fit a tree
datact <- ctree(Surv(y, yevent0) ~ .,
data = as.data.frame(cbind(y, yevent0, x)),
controls = ctree_control(minbucket = minbucket, ...))
# fit.nodes <- predict(datact, type = "node")
fit.nodes <- where(datact)
nodes <- unique(fit.nodes)
no.nodes <- length(nodes)
# pred.nodes <- predict(datact, type = "node", newdata = xp)
pred.nodes <- where(datact, newdata = xp)
# Get row numbers for predicted by sampling
# with replacement from existing data
rowno <- 1:length(y)
newrowno <- rep(0,nrow(xp))
for (i in nodes) {
newrowno[pred.nodes == i] <- sample(rowno[fit.nodes == i],
length(newrowno[pred.nodes == i]), replace = TRUE)
}
#Predicte node & sample time+event
faketime <- y[newrowno]
fakeevent <- yevent[newrowno]
return(list(syn.time = faketime, syn.event = fakeevent, fit = datact))
}
###-----syn.rf-------------------------------------------------------------
# bagging when mtry = ncol(x) - using all predictors
syn.rf <- function(y, x, xp, smoothing = "", proper = FALSE, ntree = 10, ...)
{
#nodesize <- max(1, nodesize) # safety
#if (proper == TRUE) {
# s <- sample(length(y), replace = T); y <- y[s]
# x <- x[s, , drop = FALSE]
#}
for (i in which(sapply(x,class) != sapply(xp, class))) xp[,i] <-
do.call(paste0("as.", class(x[,i])[1]), unname(xp[, i]))
if (is.factor(y)) {
obslevels <- levels(y)
y <- droplevels(y)
}
# fit a random forest
# regression (mtry = p/3), classification (mtry = sqrt(p))
rf.fit <- randomForest(y ~ ., data = cbind.data.frame(y,x), ntree = ntree, ...)
nodessyn <- attr(predict(rf.fit, newdata = xp, nodes = T), "nodes")
nodesobs <- attr(predict(rf.fit, newdata = x, nodes = T), "nodes")
ndonors <- vector("list", nrow(xp))
n0 <- vector("list", ntree)
for (j in 1:nrow(xp)) {
for (i in 1:ntree) {
n0[[i]] <- y[nodesobs[,i] == nodessyn[j,i]]
}
empty <- sapply(n0, length)
ndonors[[j]] <- unlist(n0[empty != 0])
}
yhat <- sapply(ndonors, sample, size = 1)
if (is.factor(y)) yhat <- factor(yhat, levels = obslevels)
if (!is.factor(y) & smoothing != "") yhat <-
syn.smooth(yhat, y, smoothing = smoothing)
return(list(res = yhat, fit = rf.fit))
}
###-----syn.ranger---------------------------------------------------------
# bagging when mtry = ncol(x) - using all predictors
# contributed by Caspar J. van Lissa
syn.ranger <- function(y, x, xp, smoothing = "", proper = FALSE, ...)
{
dots <- list(...)
dots[c("formula", "data")] <- NULL
if("min.node.size" %in% names(dots)){
dots[["min.node.size"]] <- max(1, dots[["min.node.size"]]) # safety
}
if (proper == TRUE) {
s <- sample(length(y), replace = TRUE)
y <- y[s]
x <- x[s, , drop = FALSE]
}
for (i in which(sapply(x,class) != sapply(xp, class))) xp[,i] <-
do.call(paste0("as.", class(x[,i])[1]), unname(xp[, i]))
if (is.factor(y)) {
obslevels <- levels(y)
y <- droplevels(y)
}
# fit a random forest
Args <- c(list(formula = y ~ ., data = cbind.data.frame(y,x)), dots)
rf.fit <- do.call(ranger, Args)
nodessyn <- predict(rf.fit, data = xp, type = "terminalNodes")$predictions
nodesobs <- predict(rf.fit, data = x, type = "terminalNodes")$predictions
ntree <- rf.fit$num.trees
ndonors <- vector("list", nrow(xp))
n0 <- vector("list", ntree)
for (j in 1:nrow(xp)) {
for (i in 1:ntree) {
n0[[i]] <- y[nodesobs[,i] == nodessyn[j,i]]
}
empty <- sapply(n0, length)
ndonors[[j]] <- unlist(n0[empty != 0])
}
yhat <- sapply(ndonors, sample, size = 1)
if (is.factor(y)) yhat <- factor(yhat, levels = obslevels)
if (!is.factor(y) & smoothing != "") yhat <-
syn.smooth(yhat, y, smoothing = "smoothing")
return(list(res = yhat, fit = rf.fit))
}
###-----syn.bag-------------------------------------------------------------
# bagging when mtry = ncol(x) - using all predictors
syn.bag <- function(y, x, xp, smoothing = "", proper = FALSE, ntree = 10, ...)
{
#nodesize <- max(1, nodesize) # safety
#if (proper == TRUE) {
# s <- sample(length(y), replace = T); y <- y[s]
# x <- x[s, , drop = FALSE]
#}
for (i in which(sapply(x,class) != sapply(xp, class))) xp[,i] <-
do.call(paste0("as.", class(x[,i])[1]), unname(xp[, i]))
if (is.factor(y)) {
obslevels <- levels(y)
y <- droplevels(y)
}
# fit a random forest
# regression (mtry = p/3), classification (mtry = sqrt(p))
rf.fit <- randomForest(y ~ ., data = cbind.data.frame(y,x),
ntree = ntree, mtry = ncol(x), ...)
nodessyn <- attr(predict(rf.fit, newdata = xp, nodes = T), "nodes")
nodesobs <- attr(predict(rf.fit, newdata = x, nodes = T), "nodes")
ndonors <- vector("list", nrow(xp))
n0 <- vector("list", ntree)
for (j in 1:nrow(xp)) {
for (i in 1:ntree) {
n0[[i]] <- y[nodesobs[,i] == nodessyn[j,i]]
}
empty <- sapply(n0, length)
ndonors[[j]] <- unlist(n0[empty != 0])
}
yhat <- sapply(ndonors, sample, size = 1)
if (is.factor(y)) yhat <- factor(yhat, levels = obslevels)
if (!is.factor(y) & smoothing != "") yhat <-
syn.smooth(yhat,y, smoothing = smoothing)
return(list(res = yhat, fit = rf.fit))
}
###-----syn.nested---------------------------------------------------------
# function for allocating to subcategories (random sampling within groups)
syn.nested <- function(y, x, xp, smoothing = "", cont.na = NA, ...)
{
xr <- x[,1]
xpr <- xp[,1]
uxpr <- sort(unique(xpr))
index <- 1:length(y)
indexp <- rep(0, nrow(xp))
for (i in uxpr) {
indexp[xpr == i] <- sample(index[xr == i], sum(xpr == i), TRUE)
}
yp <- y[indexp]
if (smoothing != "") yp[!(yp %in% cont.na)] <-
syn.smooth(yp[!(yp %in% cont.na)], y[!(y %in% cont.na)],
smoothing = smoothing)
return(list(res = yp, fit = "nested"))
}
###-----syn.satcat---------------------------------------------------------
syn.satcat <- function(y, x, xp, proper = FALSE, ...)
{
# Fits a saturated model to combinations of variables.
# Method fails if the predictor variables generate
# a combination of variables not found in the original data.
if (proper == TRUE) {
s <- sample(length(y), replace = TRUE)
y <- y[s]
x <- x[s, , drop = FALSE]
}
xr <- apply(x, 1, function(x) paste(x, collapse = "-"))
syn.categories <- apply(xp, 1, function(x) paste(x, collapse = "-"))
if (!all(names(table(syn.categories)) %in% names(table(xr)))) {
cat("\n\n")
print(table(syn.categories)[!names(table(syn.categories)) %in% names(table(xr))])
stop('The combined groups above for "satcat" have no records in original data.\n
Consider using grouped synthesis with "syn.catall" to overcome this', call. = FALSE)
}
uxpr <- sort(unique(syn.categories))
index <- 1:length(y)
indexp <- rep(0, nrow(xp))
for (i in uxpr) {
indexp[syn.categories == i] <- sample(index[xr == i], sum(syn.categories == i), TRUE)
}
yp <- y[indexp]
fit <- table(xr)