]> code.communitydata.science - ml_measurement_error_public.git/blob - simulations/simulation_base.R
Added, but didn't test the remaining robustness checks.
[ml_measurement_error_public.git] / simulations / simulation_base.R
1 library(predictionError)
2 library(mecor)
3 options(amelia.parallel="no",
4         amelia.ncpus=1)
5 library(Amelia)
6 library(Zelig)
7 library(bbmle)
8 library(matrixStats) # for numerically stable logsumexps
9
10 source("pl_methods.R")
11 source("measerr_methods.R") ## for my more generic function.
12
13 ## This uses the pseudolikelihood approach from Carroll page 349.
14 ## assumes MAR
15 ## assumes differential error, but that only depends on Y
16 ## inefficient, because pseudolikelihood
17     
18 ## This uses the pseudo-likelihood approach from Carroll page 346.
19 my.pseudo.mle <- function(df){
20     p1.est <- mean(df[w_pred==1]$y.obs==1,na.rm=T)
21     p0.est <- mean(df[w_pred==0]$y.obs==0,na.rm=T)
22     
23     nll <- function(B0, Bxy, Bzy){
24
25         pw <- vector(mode='numeric',length=nrow(df))
26         dfw1 <- df[w_pred==1]
27         dfw0 <- df[w_pred==0]
28         pw[df$w_pred==1] <- plogis(B0 + Bxy * dfw1$x + Bzy * dfw1$z, log=T)
29         pw[df$w_pred==0] <- plogis(B0 + Bxy * dfw0$x + Bzy * dfw0$z, lower.tail=FALSE, log=T)
30         
31         probs <- colLogSumExps(rbind(log(1 - p0.est), log(p1.est + p0.est - 1) + pw))
32         return(-1*sum(probs))
33     }
34     
35     mlefit <- mle2(minuslogl = nll, start = list(B0=0.0, Bxy=0.0, Bzy=0.0), control=list(maxit=1e6),method='L-BFGS-B')
36     return(mlefit)
37
38 }
39
40  
41 ## This uses the likelihood approach from Carroll page 353.
42 ## assumes that we have a good measurement error model
43 my.mle <- function(df){
44     
45     ## liklihood for observed responses
46     nll <- function(B0, Bxy, Bzy, gamma0, gamma_y, gamma_z, gamma_yz){
47         df.obs <- df[!is.na(y.obs)]
48         yobs0 <- df.obs$y==0 
49         yobs1 <- df.obs$y==1
50         p.y.obs <- vector(mode='numeric', length=nrow(df.obs))
51         
52         p.y.obs[yobs1] <- plogis(B0 + Bxy * df.obs[yobs1]$x + Bzy*df.obs[yobs1]$z,log=T)
53         p.y.obs[yobs0] <- plogis(B0 + Bxy * df.obs[yobs0]$x + Bzy*df.obs[yobs0]$z,lower.tail=FALSE,log=T)
54
55         wobs0 <- df.obs$w_pred==0
56         wobs1 <- df.obs$w_pred==1
57         p.w.obs <- vector(mode='numeric', length=nrow(df.obs))
58
59         p.w.obs[wobs1] <- plogis(gamma0 + gamma_y * df.obs[wobs1]$y + gamma_z*df.obs[wobs1]$z + df.obs[wobs1]$z*df.obs[wobs1]$y* gamma_yz, log=T)
60         p.w.obs[wobs0] <- plogis(gamma0 + gamma_y * df.obs[wobs0]$y + gamma_z*df.obs[wobs0]$z + df.obs[wobs0]$z*df.obs[wobs0]$y* gamma_yz, lower.tail=FALSE, log=T)
61         
62         p.obs <- p.w.obs + p.y.obs
63
64         df.unobs <- df[is.na(y.obs)]
65
66         p.unobs.0 <- vector(mode='numeric',length=nrow(df.unobs))
67         p.unobs.1 <- vector(mode='numeric',length=nrow(df.unobs))
68
69         wunobs.0 <- df.unobs$w_pred == 0
70         wunobs.1 <- df.unobs$w_pred == 1
71         
72         p.unobs.0[wunobs.1] <- plogis(B0 + Bxy * df.unobs[wunobs.1]$x + Bzy*df.unobs[wunobs.1]$z, log=T) + plogis(gamma0 + gamma_y + gamma_z*df.unobs[wunobs.1]$z + df.unobs[wunobs.1]$z*gamma_yz, log=T)
73
74         p.unobs.0[wunobs.0] <- plogis(B0 + Bxy * df.unobs[wunobs.0]$x + Bzy*df.unobs[wunobs.0]$z, log=T) + plogis(gamma0 + gamma_y + gamma_z*df.unobs[wunobs.0]$z + df.unobs[wunobs.0]$z*gamma_yz, lower.tail=FALSE, log=T)
75
76         p.unobs.1[wunobs.1] <- plogis(B0 + Bxy * df.unobs[wunobs.1]$x + Bzy*df.unobs[wunobs.1]$z, log=T, lower.tail=FALSE) + plogis(gamma0 + gamma_z*df.unobs[wunobs.1]$z, log=T)
77
78         p.unobs.1[wunobs.0] <- plogis(B0 + Bxy * df.unobs[wunobs.0]$x + Bzy*df.unobs[wunobs.0]$z, log=T, lower.tail=FALSE) + plogis(gamma0 + gamma_z*df.unobs[wunobs.0]$z, lower.tail=FALSE, log=T)
79
80         p.unobs <- colLogSumExps(rbind(p.unobs.1, p.unobs.0))
81
82         p <- c(p.obs, p.unobs)
83
84         return(-1*(sum(p)))
85     }
86
87     mlefit <- mle2(minuslogl = nll, start = list(B0=0, Bxy=0,Bzy=0, gamma0=0, gamma_y=0, gamma_z=0, gamma_yz=0), control=list(maxit=1e6),method='L-BFGS-B')
88
89     return(mlefit)
90 }
91
92 run_simulation_depvar <- function(df, result, outcome_formula=y~x+z, proxy_formula=w_pred~y){
93
94     (accuracy <- df[,mean(w_pred==y)])
95     result <- append(result, list(accuracy=accuracy))
96     (error.cor.z <- cor(df$z, df$y - df$w_pred))
97     (error.cor.x <- cor(df$x, df$y - df$w_pred))
98     (error.cor.y <- cor(df$y, df$y - df$w_pred))
99     result <- append(result, list(error.cor.x = error.cor.x,
100                                   error.cor.z = error.cor.z,
101                                   error.cor.y = error.cor.y))
102
103     model.null <- glm(y~1, data=df,family=binomial(link='logit'))
104     (model.true <- glm(y ~ x + z, data=df,family=binomial(link='logit')))
105     (lik.ratio <- exp(logLik(model.true) - logLik(model.null)))
106
107     true.ci.Bxy <- confint(model.true)['x',]
108     true.ci.Bzy <- confint(model.true)['z',]
109
110     result <- append(result, list(cor.xz=cor(df$x,df$z)))
111     result <- append(result, list(lik.ratio=lik.ratio))
112
113     result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
114                                   Bzy.est.true=coef(model.true)['z'],
115                                   Bxy.ci.upper.true = true.ci.Bxy[2],
116                                   Bxy.ci.lower.true = true.ci.Bxy[1],
117                                   Bzy.ci.upper.true = true.ci.Bzy[2],
118                                   Bzy.ci.lower.true = true.ci.Bzy[1]))
119                                   
120     (model.feasible <- glm(y.obs~x+z,data=df,family=binomial(link='logit')))
121
122     feasible.ci.Bxy <- confint(model.feasible)['x',]
123     result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x'],
124                                   Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
125                                   Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))
126
127     feasible.ci.Bzy <- confint(model.feasible)['z',]
128     result <- append(result, list(Bzy.est.feasible=coef(model.feasible)['z'],
129                                   Bzy.ci.upper.feasible = feasible.ci.Bzy[2],
130                                   Bzy.ci.lower.feasible = feasible.ci.Bzy[1]))
131
132     (model.naive <- glm(w_pred~x+z, data=df, family=binomial(link='logit')))
133
134     naive.ci.Bxy <- confint(model.naive)['x',]
135     naive.ci.Bzy <- confint(model.naive)['z',]
136
137     result <- append(result, list(Bxy.est.naive=coef(model.naive)['x'],
138                                   Bzy.est.naive=coef(model.naive)['z'],
139                                   Bxy.ci.upper.naive = naive.ci.Bxy[2],
140                                   Bxy.ci.lower.naive = naive.ci.Bxy[1],
141                                   Bzy.ci.upper.naive = naive.ci.Bzy[2],
142                                   Bzy.ci.lower.naive = naive.ci.Bzy[1]))
143
144
145     (model.naive.cont <- lm(w~x+z, data=df))
146     naivecont.ci.Bxy <- confint(model.naive.cont)['x',]
147     naivecont.ci.Bzy <- confint(model.naive.cont)['z',]
148
149     ## my implementation of liklihood based correction
150
151     temp.df <- copy(df)
152     temp.df[,y:=y.obs]
153     mod.caroll.lik <- measerr_mle_dv(temp.df, outcome_formula=outcome_formula, proxy_formula=proxy_formula)
154     fischer.info <- solve(mod.caroll.lik$hessian)
155     coef <- mod.caroll.lik$par
156     ci.upper <- coef + sqrt(diag(fischer.info)) * 1.96
157     ci.lower <- coef - sqrt(diag(fischer.info)) * 1.96
158     result <- append(result,
159                      list(Bxy.est.mle = coef['x'],
160                           Bxy.ci.upper.mle = ci.upper['x'],
161                           Bxy.ci.lower.mle = ci.lower['x'],
162                           Bzy.est.mle = coef['z'],
163                           Bzy.ci.upper.mle = ci.upper['z'],
164                           Bzy.ci.lower.mle = ci.lower['z']))
165
166
167     ## my implementatoin of liklihood based correction
168     mod.zhang <- zhang.mle.dv(df)
169     coef <- coef(mod.zhang)
170     ci <- confint(mod.zhang,method='quad')
171
172     result <- append(result,
173                      list(Bxy.est.zhang = coef['Bxy'],
174                           Bxy.ci.upper.zhang = ci['Bxy','97.5 %'],
175                           Bxy.ci.lower.zhang = ci['Bxy','2.5 %'],
176                           Bzy.est.zhang = coef['Bzy'],
177                           Bzy.ci.upper.zhang = ci['Bzy','97.5 %'],
178                           Bzy.ci.lower.zhang = ci['Bzy','2.5 %']))
179
180     
181
182     # amelia says use normal distribution for binary variables.
183
184     amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('y','ystar','w'))
185     mod.amelia.k <- zelig(y.obs~x+z, model='ls', data=amelia.out.k$imputations, cite=FALSE)
186     (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))
187     est.x.mi <- coefse['x','Estimate']
188     est.x.se <- coefse['x','Std.Error']
189     result <- append(result,
190                      list(Bxy.est.amelia.full = est.x.mi,
191                           Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
192                           Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
193                           ))
194
195     est.z.mi <- coefse['z','Estimate']
196     est.z.se <- coefse['z','Std.Error']
197
198     result <- append(result,
199                      list(Bzy.est.amelia.full = est.z.mi,
200                           Bzy.ci.upper.amelia.full = est.z.mi + 1.96 * est.z.se,
201                           Bzy.ci.lower.amelia.full = est.z.mi - 1.96 * est.z.se
202                           ))
203
204     return(result)
205
206 }
207
208
209 ## outcome_formula, proxy_formula, and truth_formula are passed to measerr_mle 
210 run_simulation <-  function(df, result, outcome_formula=y~x+z, proxy_formula=NULL, truth_formula=NULL){
211
212     accuracy <- df[,mean(w_pred==x)]
213     accuracy.y0 <- df[y<=0,mean(w_pred==x)]
214     accuracy.y1 <- df[y>=0,mean(w_pred==x)]
215     cor.y.xi <- cor(df$x - df$w_pred, df$y)
216
217     fnr <- df[w_pred==0,mean(w_pred!=x)]
218     fnr.y0 <- df[(w_pred==0) & (y<=0),mean(w_pred!=x)]
219     fnr.y1 <- df[(w_pred==0) & (y>=0),mean(w_pred!=x)]
220
221     fpr <- df[w_pred==1,mean(w_pred!=x)]
222     fpr.y0 <- df[(w_pred==1) & (y<=0),mean(w_pred!=x)]
223     fpr.y1 <- df[(w_pred==1) & (y>=0),mean(w_pred!=x)]
224     cor.resid.w_pred <- cor(resid(lm(y~x+z,df)),df$w_pred)
225
226     result <- append(result, list(accuracy=accuracy,
227                                   accuracy.y0=accuracy.y0,
228                                   accuracy.y1=accuracy.y1,
229                                   cor.y.xi=cor.y.xi,
230                                   fnr=fnr,
231                                   fnr.y0=fnr.y0,
232                                   fnr.y1=fnr.y1,
233                                   fpr=fpr,
234                                   fpr.y0=fpr.y0,
235                                   fpr.y1=fpr.y1,
236                                   cor.resid.w_pred=cor.resid.w_pred
237                                   ))
238
239     result <- append(result, list(cor.xz=cor(df$x,df$z)))
240     (model.true <- lm(y ~ x + z, data=df))
241     true.ci.Bxy <- confint(model.true)['x',]
242     true.ci.Bzy <- confint(model.true)['z',]
243
244     result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
245                                   Bzy.est.true=coef(model.true)['z'],
246                                   Bxy.ci.upper.true = true.ci.Bxy[2],
247                                   Bxy.ci.lower.true = true.ci.Bxy[1],
248                                   Bzy.ci.upper.true = true.ci.Bzy[2],
249                                   Bzy.ci.lower.true = true.ci.Bzy[1]))
250                                   
251     (model.feasible <- lm(y~x.obs+z,data=df))
252
253     feasible.ci.Bxy <- confint(model.feasible)['x.obs',]
254     result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x.obs'],
255                                   Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
256                                   Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))
257
258     feasible.ci.Bzy <- confint(model.feasible)['z',]
259     result <- append(result, list(Bzy.est.feasible=coef(model.feasible)['z'],
260                                   Bzy.ci.upper.feasible = feasible.ci.Bzy[2],
261                                   Bzy.ci.lower.feasible = feasible.ci.Bzy[1]))
262
263     (model.naive <- lm(y~w_pred+z, data=df))
264     
265     naive.ci.Bxy <- confint(model.naive)['w_pred',]
266     naive.ci.Bzy <- confint(model.naive)['z',]
267
268     result <- append(result, list(Bxy.est.naive=coef(model.naive)['w_pred'],
269                                   Bzy.est.naive=coef(model.naive)['z'],
270                                   Bxy.ci.upper.naive = naive.ci.Bxy[2],
271                                   Bxy.ci.lower.naive = naive.ci.Bxy[1],
272                                   Bzy.ci.upper.naive = naive.ci.Bzy[2],
273                                   Bzy.ci.lower.naive = naive.ci.Bzy[1]))
274                                   
275
276
277     amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('x','w'))
278     mod.amelia.k <- zelig(y~x.obs+z, model='ls', data=amelia.out.k$imputations, cite=FALSE)
279     (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))
280
281     est.x.mi <- coefse['x.obs','Estimate']
282     est.x.se <- coefse['x.obs','Std.Error']
283     result <- append(result,
284                      list(Bxy.est.amelia.full = est.x.mi,
285                           Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
286                           Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
287                           ))
288
289     est.z.mi <- coefse['z','Estimate']
290     est.z.se <- coefse['z','Std.Error']
291
292     result <- append(result,
293                      list(Bzy.est.amelia.full = est.z.mi,
294                           Bzy.ci.upper.amelia.full = est.z.mi + 1.96 * est.z.se,
295                           Bzy.ci.lower.amelia.full = est.z.mi - 1.96 * est.z.se
296                           ))
297
298
299         temp.df <- copy(df)
300         temp.df <- temp.df[,x:=x.obs]
301         mod.caroll.lik <- measerr_mle(temp.df, outcome_formula=outcome_formula, proxy_formula=proxy_formula, truth_formula=truth_formula)
302
303     ## tryCatch({
304     ## mod.calibrated.mle <- mecor(y ~ MeasError(w_pred, reference = x.obs) + z, df, B=400, method='efficient')
305     ## (mod.calibrated.mle)
306     ## (mecor.ci <- summary(mod.calibrated.mle)$c$ci['x.obs',])
307     ## result <- append(result, list(
308     ##                              Bxy.est.mecor = mecor.ci['Estimate'],
309     ##                              Bxy.ci.upper.mecor = mecor.ci['UCI'],
310     ##                              Bxy.ci.lower.mecor = mecor.ci['LCI'])
311     ##                  )
312
313
314
315     fischer.info <- NA
316     ci.upper <- NA
317     ci.lower <- NA
318
319     tryCatch({fischer.info <- solve(mod.caroll.lik$hessian)
320         ci.upper <- coef + sqrt(diag(fischer.info)) * 1.96
321         ci.lower <- coef - sqrt(diag(fischer.info)) * 1.96
322     },
323
324     error=function(e) {result[['error']] <- as.character(e)
325     })
326
327     coef <- mod.caroll.lik$par
328         
329         result <- append(result,
330                          list(Bxy.est.mle = coef['x'],
331                               Bxy.ci.upper.mle = ci.upper['x'],
332                               Bxy.ci.lower.mle = ci.lower['x'],
333                               Bzy.est.mle = coef['z'],
334                               Bzy.ci.upper.mle = ci.upper['z'],
335                               Bzy.ci.lower.mle = ci.lower['z']))
336
337         mod.zhang.lik <- zhang.mle.iv(df)
338         coef <- coef(mod.zhang.lik)
339         ci <- confint(mod.zhang.lik,method='quad')
340         result <- append(result,
341                          list(Bxy.est.zhang = coef['Bxy'],
342                               Bxy.ci.upper.zhang = ci['Bxy','97.5 %'],
343                               Bxy.ci.lower.zhang = ci['Bxy','2.5 %'],
344                               Bzy.est.zhang = coef['Bzy'],
345                               Bzy.ci.upper.zhang = ci['Bzy','97.5 %'],
346                               Bzy.ci.lower.zhang = ci['Bzy','2.5 %']))
347
348     ## What if we can't observe k -- most realistic scenario. We can't include all the ML features in a model.
349     ## amelia.out.nok <- amelia(df, m=200, p2s=0, idvars=c("x","w_pred"), noms=noms)
350     ## mod.amelia.nok <- zelig(y~x.obs+g, model='ls', data=amelia.out.nok$imputations, cite=FALSE)
351     ## (coefse <- combine_coef_se(mod.amelia.nok, messages=FALSE))
352
353     ## est.x.mi <- coefse['x.obs','Estimate']
354     ## est.x.se <- coefse['x.obs','Std.Error']
355     ## result <- append(result,
356     ##                  list(Bxy.est.amelia.nok = est.x.mi,
357     ##                       Bxy.ci.upper.amelia.nok = est.x.mi + 1.96 * est.x.se,
358     ##                       Bxy.ci.lower.amelia.nok = est.x.mi - 1.96 * est.x.se
359     ##                       ))
360
361     ## est.g.mi <- coefse['g','Estimate']
362     ## est.g.se <- coefse['g','Std.Error']
363
364     ## result <- append(result,
365     ##                  list(Bgy.est.amelia.nok = est.g.mi,
366     ##                       Bgy.ci.upper.amelia.nok = est.g.mi + 1.96 * est.g.se,
367     ##                       Bgy.ci.lower.amelia.nok = est.g.mi - 1.96 * est.g.se
368     ##                       ))
369
370     N <- nrow(df)
371     m <- nrow(df[!is.na(x.obs)])
372     p <- v <- train <- rep(0,N)
373     M <- m
374     p[(M+1):(N)] <- 1
375     v[1:(M)] <- 1
376     df <- df[order(x.obs)]
377     y <- df[,y]
378     x <- df[,x.obs]
379     z <- df[,z]
380     w <- df[,w_pred]
381     # gmm gets pretty close
382     (gmm.res <- predicted_covariates(y, x, z, w, v, train, p, max_iter=100, verbose=TRUE))
383
384     result <- append(result,
385                      list(Bxy.est.gmm = gmm.res$beta[1,1],
386                           Bxy.ci.upper.gmm = gmm.res$confint[1,2],
387                           Bxy.ci.lower.gmm = gmm.res$confint[1,1],
388                           gmm.ER_pval = gmm.res$ER_pval
389                           ))
390
391     result <- append(result,
392                      list(Bzy.est.gmm = gmm.res$beta[2,1],
393                           Bzy.ci.upper.gmm = gmm.res$confint[2,2],
394                           Bzy.ci.lower.gmm = gmm.res$confint[2,1]))
395
396
397     ## tryCatch({
398     ## mod.calibrated.mle <- mecor(y ~ MeasError(w_pred, reference = x.obs) + z, df, B=400, method='efficient')
399     ## (mod.calibrated.mle)
400     ## (mecor.ci <- summary(mod.calibrated.mle)$c$ci['x.obs',])
401     ## result <- append(result, list(
402     ##                              Bxy.est.mecor = mecor.ci['Estimate'],
403     ##                              Bxy.ci.upper.mecor = mecor.ci['UCI'],
404     ##                              Bxy.ci.lower.mecor = mecor.ci['LCI'])
405     ##                  )
406
407     ## (mecor.ci <- summary(mod.calibrated.mle)$c$ci['z',])
408
409     ## result <- append(result, list(
410     ##                              Bzy.est.mecor = mecor.ci['Estimate'],
411     ##                              Bzy.ci.upper.mecor = mecor.ci['UCI'],
412     ##                              Bzy.ci.lower.mecor = mecor.ci['LCI'])
413     ##                  )
414     ## },
415     ## error = function(e){
416     ##     message("An error occurred:\n",e)
417     ##     result$error <- paste0(result$error, '\n', e)
418     ## }
419     ## )
420 ##    clean up memory
421 ##    rm(list=c("df","y","x","g","w","v","train","p","amelia.out.k","amelia.out.nok", "mod.calibrated.mle","gmm.res","mod.amelia.k","mod.amelia.nok", "model.true","model.naive","model.feasible"))
422     
423 ##    gc()
424     return(result)
425 }

Community Data Science Collective || Want to submit a patch?