]> code.communitydata.science - ml_measurement_error_public.git/blob - simulations/example_2_B_mecor.R
add missing simulation code
[ml_measurement_error_public.git] / simulations / example_2_B_mecor.R
1 ### EXAMPLE 2_b: demonstrates how measurement error can lead to a type sign error in a covariate
2 ### This is the same as example 2, only instead of x->k we have k->x.
3 ### Even when you have a good predictor, if it's biased against a covariate you can get the wrong sign.
4 ### Even when you include the proxy variable in the regression.
5 ### But with some ground truth and multiple imputation, you can fix it.
6
7 library(argparser)
8 library(mecor)
9 library(ggplot2)
10 library(data.table)
11 library(filelock)
12 library(arrow)
13 library(Amelia)
14 library(Zelig)
15 library(predictionError)
16 options(amelia.parallel="no",
17         amelia.ncpus=1)
18
19 source("simulation_base_mecor.R")
20
21 ## SETUP:
22 ### we want to estimate x -> y; x is MAR
23 ### we have x -> k; k -> w; x -> w is used to predict x via the model w.
24 ### A realistic scenario is that we have an NLP model predicting something like "racial harassment" in social media comments
25 ### The labels x are binary, but the model provides a continuous predictor
26
27 ### simulation:
28 #### how much power do we get from the model in the first place? (sweeping N and m)
29 #### 
30 logistic <- function(x) {1/(1+exp(-1*x))}
31
32 simulate_latent_cocause <- function(N, m, B0, Bxy, Bgy, Bkx, Bgx, seed){
33     set.seed(seed)
34
35     ## the true value of x
36
37     g <- rbinom(N, 1, 0.5)
38     xprime <- Bgx * g + rnorm(N,0,1)
39
40     k <- Bkx*xprime + rnorm(N,0,3)
41
42     x <- as.integer(logistic(scale(xprime)) > 0.5)
43
44     y <-  Bxy * x  + Bgy * g + rnorm(N, 0, 1) + B0
45     df <- data.table(x=x,k=k,y=y,g=g)
46
47     if( m < N){
48         df <- df[sample(nrow(df), m), x.obs := x]
49     } else {
50         df <- df[, x.obs := x]
51     }
52
53     w.model <- glm(x ~ k,df, family=binomial(link='logit'))
54     w <- predict(w.model,data.frame(k=k)) + rnorm(N,0,1)
55     ## y = B0 + B1x + e
56
57     df[,':='(w=w, w_pred = as.integer(w>0.5))]
58     return(df)
59 }
60
61 schennach <- function(df){
62
63     fwx <- glm(x.obs~w, df, family=binomial(link='logit'))
64     df[,xstar_pred := predict(fwx, df)]
65     gxt <- lm(y ~ xstar_pred+g, df)
66
67 }
68
69 parser <- arg_parser("Simulate data and fit corrected models")
70 parser <- add_argument(parser, "--N", default=100, help="number of observations of w")
71 parser <- add_argument(parser, "--m", default=20, help="m the number of ground truth observations")
72 parser <- add_argument(parser, "--seed", default=4321, help='seed for the rng')
73 parser <- add_argument(parser, "--outfile", help='output file', default='example_2_B.feather')
74 args <- parse_args(parser)
75
76 B0 <- 0
77 Bxy <- 0.2
78
79 Bkx <- 0.5
80
81 rows <- list()
82
83 B0 <- 0
84 Bxy <- 0.4
85 Bgy <- 0.25
86 Bkx <- 3.2
87 Bgx <- -0.5
88
89 outline <- run_simulation(simulate_latent_cocause(args$N, args$m, B0, Bxy, Bgy, Bkx, Bgx, args$seed)
90                          ,list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'Bkx'=Bkx, 'Bgx'=Bgx, 'seed'=args$seed))
91
92 outfile_lock <- lock(paste0(args$outfile, '_lock'))
93 if(file.exists(args$outfile)){
94     logdata <- read_feather(args$outfile)
95     logdata <- rbind(logdata,as.data.table(outline))
96 } else {
97     logdata <- as.data.table(outline)
98 }
99
100 print(outline)
101 write_feather(logdata, args$outfile)
102 unlock(outfile_lock)
103
104 ## Ns <- c(1e6, 5e4, 1000)
105 ## ms <- c(100, 250, 500, 1000)
106 ## seeds <- 1:500
107
108 ## rowssets <- list()
109 ## library(doParallel)
110 ## options(mc.cores = parallel::detectCores())
111 ## cl <- makeCluster(20)
112 ## registerDoParallel(cl)
113
114 ## ## library(future)
115
116 ## ## plan(multiprocess,workers=40,gc=TRUE)
117
118 ## for(N in Ns){
119 ##     print(N)
120 ##     for(m in ms){
121 ##         if(N>m){
122 ##             new.rows <- foreach(iter=seeds, .combine=rbind, .packages = c('mecor','Amelia','Zelig','predictionError','data.table'),
123 ##                                 .export = c("run_simulation","simulate_latent_cocause","logistic","N","m","B0","Bxy","Bgy","Bkx","Bgx")) %dopar%
124                 
125 ##                 {run_simulation(simulate_latent_cocause(N, m, B0, Bxy, Bgy, Bkx, Bgx, iter)
126 ##                                ,list('N'=N,'m'=m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'Bkx'=Bkx, 'Bgx'=Bgx, 'seed'=iter))}
127 ##             rowsets <- append(rowssets, list(data.table(new.rows)))
128 ##        }
129
130 ##     }
131 ##                 ## rows <- append(rows, list(future({run_simulation(simulate_latent_cocause(N, m, B0, Bxy, Bgy, Bkx, Bgx, seed)
132 ## }
133                 ##                                                 ,list(N=N,m=m,B0=B0,Bxy=Bxy,Bgy=Bgy, Bkx=Bkx, Bgx=Bgx, seed=seed))w},
134                 ##                                  packages=c('mecor','Amelia','Zelig','predictionError'),
135                 ##                                  seed=TRUE)))
136
137
138 ## df <- rbindlist(rowsets)
139
140 ## write_feather(df,"example_2B_simulation.feather")
141
142 ## run_simulation <-  function(N, m, B0, Bxy, Bgy, Bkx, Bgx, seed){
143 ##     result <- list()
144 ##     df <- simulate_latent_cocause(N, m, B0, Bxy, Bgy, Bkx, Bgx, seed)
145
146 ##     result <- append(result, list(N=N,
147 ##                                   m=m,
148 ##                                   B0=B0,
149 ##                                   Bxy=Bxy,
150 ##                                   Bgy=Bgy,
151 ##                                   Bkx=Bkx,
152 ##                                   seed=seed))
153
154 ##     (accuracy <- df[,.(mean(w_pred==x))])
155 ##     result <- append(result, list(accuracy=accuracy))
156
157 ##     (model.true <- lm(y ~ x + g, data=df))
158 ##     true.ci.Bxy <- confint(model.true)['x',]
159 ##     true.ci.Bgy <- confint(model.true)['g',]
160
161 ##     result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
162 ##                                   Bgy.est.true=coef(model.true)['g'],
163 ##                                   Bxy.ci.upper.true = true.ci.Bxy[2],
164 ##                                   Bxy.ci.lower.true = true.ci.Bxy[1],
165 ##                                   Bgy.ci.upper.true = true.ci.Bgy[2],
166 ##                                   Bgy.ci.lower.true = true.ci.Bgy[1]))
167                                   
168 ##     (model.feasible <- lm(y~x.obs+g,data=df))
169
170 ##     feasible.ci.Bxy <- confint(model.feasible)['x.obs',]
171 ##     result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x.obs'],
172 ##                                   Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
173 ##                                   Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))
174
175 ##     feasible.ci.Bgy <- confint(model.feasible)['g',]
176 ##     result <- append(result, list(Bgy.est.feasible=coef(model.feasible)['g'],
177 ##                                   Bgy.ci.upper.feasible = feasible.ci.Bgy[2],
178 ##                                   Bgy.ci.lower.feasible = feasible.ci.Bgy[1]))
179
180 ##     (model.naive <- lm(y~w+g, data=df))
181     
182 ##     naive.ci.Bxy <- confint(model.naive)['w',]
183 ##     naive.ci.Bgy <- confint(model.naive)['g',]
184
185 ##     result <- append(result, list(Bxy.est.naive=coef(model.naive)['w'],
186 ##                                   Bgy.est.naive=coef(model.naive)['g'],
187 ##                                   Bxy.ci.upper.naive = naive.ci.Bxy[2],
188 ##                                   Bxy.ci.lower.naive = naive.ci.Bxy[1],
189 ##                                   Bgy.ci.upper.naive = naive.ci.Bgy[2],
190 ##                                   Bgy.ci.lower.naive = naive.ci.Bgy[1]))
191                                   
192
193 ##     ## multiple imputation when k is observed
194 ##     ## amelia does great at this one.
195 ##     amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('x','w_pred'),noms=c("x.obs","g"),lgstc=c('w'))
196 ##     mod.amelia.k <- zelig(y~x.obs+g, model='ls', data=amelia.out.k$imputations, cite=FALSE)
197 ##     (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))
198
199 ##     est.x.mi <- coefse['x.obs','Estimate']
200 ##     est.x.se <- coefse['x.obs','Std.Error']
201 ##     result <- append(result,
202 ##                      list(Bxy.est.amelia.full = est.x.mi,
203 ##                           Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
204 ##                           Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
205 ##                           ))
206
207 ##     est.g.mi <- coefse['g','Estimate']
208 ##     est.g.se <- coefse['g','Std.Error']
209
210 ##     result <- append(result,
211 ##                      list(Bgy.est.amelia.full = est.g.mi,
212 ##                           Bgy.ci.upper.amelia.full = est.g.mi + 1.96 * est.g.se,
213 ##                           Bgy.ci.lower.amelia.full = est.g.mi - 1.96 * est.g.se
214 ##                           ))
215
216 ##     ## What if we can't observe k -- most realistic scenario. We can't include all the ML features in a model.
217 ##     amelia.out.nok <- amelia(df, m=200, p2s=0, idvars=c("x","k"), noms=c("x.obs",'g'),lgstc = c("w"))
218 ##     mod.amelia.nok <- zelig(y~x.obs+g, model='ls', data=amelia.out.nok$imputations, cite=FALSE)
219 ##     (coefse <- combine_coef_se(mod.amelia.nok, messages=FALSE))
220
221 ##     est.x.mi <- coefse['x.obs','Estimate']
222 ##     est.x.se <- coefse['x.obs','Std.Error']
223 ##     result <- append(result,
224 ##                      list(Bxy.est.amelia.nok = est.x.mi,
225 ##                           Bxy.ci.upper.amelia.nok = est.x.mi + 1.96 * est.x.se,
226 ##                           Bxy.ci.lower.amelia.nok = est.x.mi - 1.96 * est.x.se
227 ##                           ))
228
229 ##     est.g.mi <- coefse['g','Estimate']
230 ##     est.g.se <- coefse['g','Std.Error']
231
232 ##     result <- append(result,
233 ##                      list(Bgy.est.amelia.nok = est.g.mi,
234 ##                           Bgy.ci.upper.amelia.nok = est.g.mi + 1.96 * est.g.se,
235 ##                           Bgy.ci.lower.amelia.nok = est.g.mi - 1.96 * est.g.se
236 ##                           ))
237
238 ##     p <- v <- train <- rep(0,N)
239 ##     M <- m
240 ##     p[(M+1):(N)] <- 1
241 ##     v[1:(M)] <- 1
242 ##     df <- df[order(x.obs)]
243 ##     y <- df[,y]
244 ##     x <- df[,x.obs]
245 ##     g <- df[,g]
246 ##     w <- df[,w]
247 ##     # gmm gets pretty close
248 ##     (gmm.res <- predicted_covariates(y, x, g, w, v, train, p, max_iter=100, verbose=FALSE))
249
250 ##     result <- append(result,
251 ##                      list(Bxy.est.gmm = gmm.res$beta[1,1],
252 ##                           Bxy.ci.upper.gmm = gmm.res$confint[1,2],
253 ##                           Bxy.ci.lower.gmm = gmm.res$confint[1,1]))
254
255 ##     result <- append(result,
256 ##                      list(Bgy.est.gmm = gmm.res$beta[2,1],
257 ##                           Bgy.ci.upper.gmm = gmm.res$confint[2,2],
258 ##                           Bgy.ci.lower.gmm = gmm.res$confint[2,1]))
259
260
261 ##     mod.calibrated.mle <- mecor(y ~ MeasError(w, reference = x.obs) + g, df, B=400, method='efficient')
262 ##     (mod.calibrated.mle)
263 ##     (mecor.ci <- summary(mod.calibrated.mle)$c$ci['x.obs',])
264 ##     result <- append(result, list(
265 ##                                  Bxy.est.mecor = mecor.ci['Estimate'],
266 ##                                  Bxy.upper.mecor = mecor.ci['UCI'],
267 ##                                  Bxy.lower.mecor = mecor.ci['LCI'])
268 ##                      )
269
270 ##     (mecor.ci <- summary(mod.calibrated.mle)$c$ci['g',])
271
272 ##     result <- append(result, list(
273 ##                                  Bxy.est.mecor = mecor.ci['Estimate'],
274 ##                                  Bxy.upper.mecor = mecor.ci['UCI'],
275 ##                                  Bxy.lower.mecor = mecor.ci['LCI'])
276 ##                      )
277
278
279 ##     return(result)
280 ## }
281

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