1 ### EXAMPLE 2: demonstrates how measurement error can lead to a type sign error in a covariate
2 ### Even when you have a good predictor, if it's biased against a covariate you can get the wrong sign.
3 ### Even when you include the proxy variable in the regression.
4 ### But with some ground truth and multiple imputation, you can fix it.
14 library(predictionError)
16 source("simulation_base.R")
19 ### we want to estimate x -> y; x is MAR
20 ### we have x -> k; k -> w; x -> w is used to predict x via the model w.
21 ### A realistic scenario is that we have an NLP model predicting something like "racial harassment" in social media comments
22 ### The labels x are binary, but the model provides a continuous predictor
25 #### how much power do we get from the model in the first place? (sweeping N and m)
27 logistic <- function(x) {1/(1+exp(-1*x))}
29 simulate_latent_cocause <- function(N, m, B0, Bxy, Bgy, Bkx, Bgx, seed){
32 ## the true value of x
34 g <- rbinom(N, 1, 0.5)
35 xprime <- Bgx * g + rnorm(N,0,1)
37 k <- Bkx*xprime + rnorm(N,0,3)
39 x <- as.integer(logistic(scale(xprime)) > 0.5)
41 y <- Bxy * x + Bgy * g + rnorm(N, 0, 2) + B0
42 df <- data.table(x=x,k=k,y=y,g=g)
45 df <- df[sample(nrow(df), m), x.obs := x]
47 df <- df[, x.obs := x]
50 w.model <- glm(x ~ k,df, family=binomial(link='logit'))
51 w <- predict(w.model,data.frame(k=k)) + rnorm(N,0,1)
54 df[,':='(w=w, w_pred = as.integer(w>0.5))]
59 parser <- arg_parser("Simulate data and fit corrected models")
60 parser <- add_argument(parser, "--N", default=1000, help="number of observations of w")
61 parser <- add_argument(parser, "--m", default=100, help="m the number of ground truth observations")
62 parser <- add_argument(parser, "--seed", default=432, help='seed for the rng')
63 parser <- add_argument(parser, "--outfile", help='output file', default='example_2_B.feather')
64 args <- parse_args(parser)
73 df <- simulate_latent_cocause(args$N, args$m, B0, Bxy, Bgy, Bkx, Bgx, args$seed)
75 outline <- run_simulation(df
76 ,list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=0, 'Bkx'=Bkx, 'Bgx'=0, 'seed'=args$seed))
78 outfile_lock <- lock(paste0(args$outfile, '_lock'))
79 if(file.exists(args$outfile)){
80 logdata <- read_feather(args$outfile)
81 logdata <- rbind(logdata,as.data.table(outline))
83 logdata <- as.data.table(outline)
87 write_feather(logdata, args$outfile)
94 ## for(seed in seeds){
95 ## rows <- append(rows, list(run_simulation(N, m, B0, Bxy, Bkx, seed)))
102 ## run_simulation <- function(N, m, B0, Bxy, Bkx, seed){
104 ## df <- simulate_latent_cocause(N, m, B0, Bxy, Bkx, seed)
106 ## result <- append(result, list(N=N,
113 ## (correlation <- cor(df$w,df$x,method='spearman'))
114 ## result <- append(result, list(correlation=correlation))
116 ## (accuracy <- mean(df$x == df$w_pred))
118 ## result <- append(result, list(accuracy=accuracy))
120 ## (model.true <- lm(y ~ x, data=df))
122 ## (cor(resid(model.true),df$w))
124 ## true.ci.Bxy <- confint(model.true)['x',]
126 ## result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
127 ## Bxy.ci.upper.true = true.ci.Bxy[2],
128 ## Bxy.ci.lower.true = true.ci.Bxy[1]))
130 ## (model.naive <- lm(y~w, data=df))
132 ## (model.feasible <- lm(y~x.obs,data=df))
134 ## feasible.ci.Bxy <- confint(model.feasible)['x.obs',]
135 ## result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x.obs'],
136 ## Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
137 ## Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))
140 ## naive.ci.Bxy <- confint(model.naive)['w',]
142 ## result <- append(result, list(Bxy.est.naive=coef(model.naive)['w'],
143 ## Bxy.ci.upper.naive = naive.ci.Bxy[2],
144 ## Bxy.ci.lower.naive = naive.ci.Bxy[1]))
147 ## ## multiple imputation when k is observed
149 ## amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('x','w_pred'), noms=c("x.obs"),lgstc=c('w'))
150 ## mod.amelia.k <- zelig(y~x.obs, model='ls', data=amelia.out.k$imputations, cite=FALSE)
151 ## (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))
153 ## est.x.mi <- coefse['x.obs','Estimate']
154 ## est.x.se <- coefse['x.obs','Std.Error']
155 ## result <- append(result,
156 ## list(Bxy.est.amelia.full = est.x.mi,
157 ## Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
158 ## Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
162 ## ## What if we can't observe k -- most realistic scenario. We can't include all the ML features in a model.
163 ## amelia.out.nok <- amelia(df, m=200, p2s=0, idvars=c("x","k","w_pred"),noms=c("x.obs"),lgstc=c('w'))
164 ## mod.amelia.nok <- zelig(y~x.obs, model='ls', data=amelia.out.nok$imputations, cite=FALSE)
165 ## (coefse <- combine_coef_se(mod.amelia.nok, messages=FALSE))
167 ## est.x.mi <- coefse['x.obs','Estimate']
168 ## est.x.se <- coefse['x.obs','Std.Error']
169 ## result <- append(result,
170 ## list(Bxy.est.amelia.nok = est.x.mi,
171 ## Bxy.ci.upper.amelia.nok = est.x.mi + 1.96 * est.x.se,
172 ## Bxy.ci.lower.amelia.nok = est.x.mi - 1.96 * est.x.se
175 ## p <- v <- train <- rep(0,N)
179 ## df <- df[order(x.obs)]
183 ## (gmm.res <- predicted_covariates(y, x, g, w, v, train, p, max_iter=100, verbose=FALSE))
185 ## result <- append(result,
186 ## list(Bxy.est.gmm = gmm.res$beta[1,1],
187 ## Bxy.ci.upper.gmm = gmm.res$confint[1,2],
188 ## Bxy.ci.lower.gmm = gmm.res$confint[1,1]))
190 ## mod.calibrated.mle <- mecor(y ~ MeasError(w, reference = x.obs), df, B=400, method='efficient')
192 ## (mecor.ci <- summary(mod.calibrated.mle)$c$ci['x.obs',])
194 ## result <- append(result, list(
195 ## Bxy.est.mecor = mecor.ci['Estimate'],
196 ## Bxy.upper.mecor = mecor.ci['UCI'],
197 ## Bxy.lower.mecor = mecor.ci['LCI'])