}
df <- df[,w_pred:=x]
-
df <- df[sample(1:N,(1-prediction_accuracy)*N),w_pred:=(w_pred-1)**2]
+ w <- predict(glm(x ~ w_pred,data=df,family=binomial(link='logit')),type='response')
df <- df[,':='(w=w, w_pred = w_pred)]
return(df)
}
parser <- add_argument(parser, "--m", default=100, help="m the number of ground truth observations")
parser <- add_argument(parser, "--seed", default=4321, help='seed for the rng')
parser <- add_argument(parser, "--outfile", help='output file', default='example_1.feather')
+parser <- add_argument(parser, "--y_explained_variance", help='what proportion of the variance of y can be explained?', default=0.005)
+parser <- add_argument(parser, "--gx_explained_variance", help='what proportion of the variance of x can be explained by g?', default=0.15)
+parser <- add_argument(parser, "--prediction_accuracy", help='how accurate is the predictive model?', default=0.73)
+
args <- parse_args(parser)
B0 <- 0
Bxy <- 0.2
Bgy <- -0.2
-Bgx <- 0.5
+Bgx <- 0.4
+
+df <- simulate_data(args$N, args$m, B0, Bxy, Bgy, Bgx, seed=args$seed, y_explained_variance = args$y_explained_variance, gx_explained_variance = args$gx_explained_variance, prediction_accuracy=args$prediction_accuracy)
-df <- simulate_data(args$N, args$m, B0, Bxy, Bgy, Bgx, seed=args$seed, y_explained_variance = 0.025, gx_explained_variance = 0.15)
-result <- list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'Bgx'=Bgx, 'seed'=args$seed)
+result <- list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'Bgx'=Bgx, 'seed'=args$seed, 'y_explained_variance' = args$y_explained_variance, 'gx_explained_variance' = args$gx_explained_variance, "prediction_accuracy"=args$prediction_accuracy)
outline <- run_simulation(df, result)
outfile_lock <- lock(paste0(args$outfile, '_lock'),exclusive=TRUE)
## one way to do it is by adding correlation to x.obs and y that isn't in w.
## in other words, the model is missing an important feature of x.obs that's related to y.
-simulate_data <- function(N, m, B0, Bxy, Bgy, Bkx, Bgx, seed, xy.explained.variance=0.01, u.explained.variance=0.1){
+simulate_data <- function(N, m, B0, Bxy, Bgy, seed, y_explained_variance=0.025, prediction_accuracy=0.73, accuracy_imbalance_difference=0.3){
set.seed(seed)
-
- ## the true value of x
-
- g <- rbinom(N, 1, 0.5)
-
# make w and y dependent
- u <- rnorm(N,0,)
-
- xprime <- Bgx * g + rnorm(N,0,1)
-
- k <- Bkx*xprime + rnorm(N,0,1.5) + 1.1*Bkx*u
-
- x <- as.integer(logistic(scale(xprime)) > 0.5)
-
- y <- Bxy * x + Bgy * g + B0 + u + rnorm(N, 0, 1)
+ g <- rbinom(N, 1, 0.5)
+ x <- rbinom(N, 1, 0.5)
- df <- data.table(x=x,k=k,y=y,g=g)
+ y.var.epsilon <- (var(Bgy * g) + var(Bxy *x) + 2*cov(Bgy*g,Bxy*x)) * ((1-y_explained_variance)/y_explained_variance)
+ y.epsilon <- rnorm(N, sd = sqrt(y.var.epsilon))
+ y <- Bgy * g + Bxy * x + y.epsilon
- w.model <- glm(x ~ k,df, family=binomial(link='logit'))
+ df <- data.table(x=x,y=y,g=g)
- if( m < N){
+ if(m < N){
df <- df[sample(nrow(df), m), x.obs := x]
} else {
df <- df[, x.obs := x]
}
- df[, x.obs := x.obs]
+ df <- df[,w_pred:=x]
- w <- predict(w.model, df) + rnorm(N, 0, 1)
- ## y = B0 + B1x + e
+ pg <- mean(g)
+ px <- mean(x)
+ accuracy_imbalance_ratio <- (prediction_accuracy + accuracy_imbalance_difference/2) / (prediction_accuracy - accuracy_imbalance_difference/2)
- df[,':='(w=w, w_pred = as.integer(w>0.5),u=u)]
- return(df)
-}
+ # this works because of conditional probability
+ accuracy_g0 <- prediction_accuracy / (pg*(accuracy_imbalance_ratio) + (1-pg))
+ accuracy_g1 <- accuracy_imbalance_ratio * accuracy_g0
-schennach <- function(df){
+ dfg0 <- df[g==0]
+ ng0 <- nrow(dfg0)
+ dfg1 <- df[g==1]
+ ng1 <- nrow(dfg1)
- fwx <- glm(x.obs~w, df, family=binomial(link='logit'))
- df[,xstar_pred := predict(fwx, df)]
- gxt <- lm(y ~ xstar_pred+g, df)
+ dfg0 <- dfg0[sample(ng0, (1-accuracy_g0)*ng0), w_pred := (w_pred-1)**2]
+ dfg1 <- dfg1[sample(ng1, (1-accuracy_g1)*ng1), w_pred := (w_pred-1)**2]
-}
+ df <- rbind(dfg0,dfg1)
+ w <- predict(glm(x ~ w_pred,data=df,family=binomial(link='logit')),type='response')
+ df <- df[,':='(w=w, w_pred = w_pred)]
+ return(df)
+}
parser <- arg_parser("Simulate data and fit corrected models")
parser <- add_argument(parser, "--N", default=5000, help="number of observations of w")
parser <- add_argument(parser, "--m", default=200, help="m the number of ground truth observations")
parser <- add_argument(parser, "--seed", default=432, help='seed for the rng')
parser <- add_argument(parser, "--outfile", help='output file', default='example_2.feather')
+parser <- add_argument(parser, "--y_explained_variance", help='what proportion of the variance of y can be explained?', default=0.01)
+parser <- add_argument(parser, "--prediction_accuracy", help='how accurate is the predictive model?', default=0.73)
+parser <- add_argument(parser, "--accuracy_imbalance_difference", help='how much more accurate is the predictive model for one class than the other?', default=0.3)
+
args <- parse_args(parser)
B0 <- 0
Bxy <- 0.2
-Bgy <- 0
-Bkx <- 2
-Bgx <- 0
+Bgy <- -0.2
+
+df <- simulate_data(args$N, args$m, B0, Bxy, Bgy, args$seed, args$y_explained_variance, args$prediction_accuracy, args$accuracy_imbalance_difference)
+
+result <- list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'seed'=args$seed, 'y_explained_variance'=args$y_explained_variance, 'prediction_accuracy'=args$prediction_accuracy, 'accuracy_imbalance_difference'=args$accuracy_imbalance_difference)
+outline <- run_simulation_depvar(df=df, result)
-outline <- run_simulation(simulate_data(args$N, args$m, B0, Bxy, Bgy, Bkx, Bgx, args$seed)
- ,list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'Bkx'=Bkx, 'Bgx'=Bgx, 'seed'=args$seed))
outfile_lock <- lock(paste0(args$outfile, '_lock'),exclusive=TRUE)
if(file.exists(args$outfile)){
--- /dev/null
+### EXAMPLE 1: demonstrates how measurement error can lead to a type sign error in a covariate
+### What kind of data invalidates fong + tyler?
+### Even when you have a good predictor, if it's biased against a covariate you can get the wrong sign.
+### Even when you include the proxy variable in the regression.
+### But with some ground truth and multiple imputation, you can fix it.
+
+library(argparser)
+library(mecor)
+library(ggplot2)
+library(data.table)
+library(filelock)
+library(arrow)
+library(Amelia)
+library(Zelig)
+library(predictionError)
+options(amelia.parallel="no",
+ amelia.ncpus=1)
+setDTthreads(40)
+
+source("simulation_base.R")
+
+## SETUP:
+### we want to estimate x -> y; x is MAR
+### we have x -> k; k -> w; x -> w is used to predict x via the model w.
+### A realistic scenario is that we have an NLP model predicting something like "racial harassment" in social media comments
+### The labels x are binary, but the model provides a continuous predictor
+
+### simulation:
+#### how much power do we get from the model in the first place? (sweeping N and m)
+####
+
+## one way to do it is by adding correlation to x.obs and y that isn't in w.
+## in other words, the model is missing an important feature of x.obs that's related to y.
+simulate_data <- function(N, m, B0, Bxy, Bgy, seed, prediction_accuracy=0.73, accuracy_imbalance_difference=0.3){
+ set.seed(seed)
+ # make w and y dependent
+ g <- rbinom(N, 1, 0.5)
+ x <- rbinom(N, 1, 0.5)
+
+ ystar <- Bgy * g + Bxy * x
+ y <- rbinom(N,1,logistic(ystar))
+
+ # glm(y ~ x + g, family="binomial")
+
+ df <- data.table(x=x,y=y,ystar=ystar,g=g)
+
+ if(m < N){
+ df <- df[sample(nrow(df), m), y.obs := y]
+ } else {
+ df <- df[, y.obs := y]
+ }
+
+ df <- df[,w_pred:=y]
+
+ pg <- mean(g)
+
+ accuracy_imbalance_ratio <- (prediction_accuracy + accuracy_imbalance_difference/2) / (prediction_accuracy - accuracy_imbalance_difference/2)
+
+ # this works because of conditional probability
+ accuracy_g0 <- prediction_accuracy / (pg*(accuracy_imbalance_ratio) + (1-pg))
+ accuracy_g1 <- accuracy_imbalance_ratio * accuracy_g0
+
+ dfg0 <- df[g==0]
+ ng0 <- nrow(dfg0)
+ dfg1 <- df[g==1]
+ ng1 <- nrow(dfg1)
+
+ dfg0 <- dfg0[sample(ng0, (1-accuracy_g0)*ng0), w_pred := (w_pred-1)**2]
+ dfg1 <- dfg1[sample(ng1, (1-accuracy_g1)*ng1), w_pred := (w_pred-1)**2]
+
+ df <- rbind(dfg0,dfg1)
+
+ wmod <- glm(y.obs ~ w_pred,data=df[!is.null(y.obs)],family=binomial(link='logit'))
+ w <- predict(wmod,df,type='response')
+
+ df <- df[,':='(w=w)]
+
+ return(df)
+}
+
+parser <- arg_parser("Simulate data and fit corrected models")
+parser <- add_argument(parser, "--N", default=5000, help="number of observations of w")
+parser <- add_argument(parser, "--m", default=200, help="m the number of ground truth observations")
+parser <- add_argument(parser, "--seed", default=4321, help='seed for the rng')
+parser <- add_argument(parser, "--outfile", help='output file', default='example_2.feather')
+parser <- add_argument(parser, "--y_explained_variance", help='what proportion of the variance of y can be explained?', default=0.005)
+parser <- add_argument(parser, "--prediction_accuracy", help='how accurate is the predictive model?', default=0.73)
+parser <- add_argument(parser, "--accuracy_imbalance_difference", help='how much more accurate is the predictive model for one class than the other?', default=0.3)
+
+args <- parse_args(parser)
+
+B0 <- 0
+Bxy <- 0.2
+Bgy <- -0.2
+
+df <- simulate_data(args$N, args$m, B0, Bxy, Bgy, args$seed, args$prediction_accuracy, args$accuracy_imbalance_difference)
+
+result <- list('N'=args$N,'m'=args$m,'B0'=B0,'Bxy'=Bxy,'Bgy'=Bgy, 'seed'=args$seed, 'y_explained_variance'=args$y_explained_variance, 'prediction_accuracy'=args$prediction_accuracy, 'accuracy_imbalance_difference'=args$accuracy_imbalance_difference)
+
+outline <- run_simulation_depvar(df=df, result)
+
+
+outfile_lock <- lock(paste0(args$outfile, '_lock'),exclusive=TRUE)
+if(file.exists(args$outfile)){
+ logdata <- read_feather(args$outfile)
+ logdata <- rbind(logdata,as.data.table(outline))
+} else {
+ logdata <- as.data.table(outline)
+}
+
+print(outline)
+write_feather(logdata, args$outfile)
+unlock(outfile_lock)
sbatch --wait --verbose --array=3001-6001 run_simulation.sbatch 0 example_1_jobs
example_2_jobs: example_2.R
- grid_sweep.py --command "Rscript example_2.R" --arg_dict '{"N":${Ns},"m":${ms}, "seed":${seeds}, "outfile":["example_2.feather"]}' --outfile example_2_jobs
+ grid_sweep.py --command "Rscript 02_indep_differential.R" --arg_dict '{"N":${Ns},"m":${ms}, "seed":${seeds}, "outfile":["example_2.feather"]}' --outfile example_2_jobs
example_2.feather: example_2_jobs
rm -f example_2.feather
sbatch --wait --verbose --array=1-3000 run_simulation.sbatch 0 example_2_jobs
-# sbatch --wait --verbose --array=3001-6001 run_simulation.sbatch 0 example_2_jobs
+ sbatch --wait --verbose --array=3001-6001 run_simulation.sbatch 0 example_2_jobs
example_2_B_jobs: example_2_B.R
grid_sweep.py --command "Rscript example_2_B.R" --arg_dict '{"N":${Ns},"m":${ms}, "seed":${seeds}, "outfile":["example_2_B.feather"]}' --outfile example_2_B_jobs
amelia.ncpus=1)
library(Amelia)
library(Zelig)
+library(stats4)
+
+
+## This uses the pseudolikelihood approach from Carroll page 349.
+## assumes MAR
+## assumes differential error, but that only depends on Y
+## inefficient, because pseudolikelihood
+logistic.correction.pseudo <- function(df){
+ p1.est <- mean(df[w_pred==1]$y.obs==1,na.rm=T)
+ p0.est <- mean(df[w_pred==0]$y.obs==0,na.rm=T)
+
+ nll <- function(B0, Bxy, Bgy){
+ probs <- (1 - p0.est) + (p1.est + p0.est - 1)*plogis(B0 + Bxy * df$x + Bgy * df$g)
+
+ part1 = sum(log(probs[df$w_pred == 1]))
+ part2 = sum(log(1-probs[df$w_pred == 0]))
+
+ return(-1*(part1 + part2))
+ }
+
+ mlefit <- stats4::mle(minuslogl = nll, start = list(B0=0, Bxy=0.0, Bgy=0.0))
+ return(mlefit)
+
+}
+
+## This uses the likelihood approach from Carroll page 353.
+## assumes that we have a good measurement error model
+logistic.correction.liklihood <- function(df){
+
+ ## liklihood for observed responses
+ nll <- function(B0, Bxy, Bgy, gamma0, gamma_y, gamma_g){
+ df.obs <- df[!is.na(y.obs)]
+ p.y.obs <- plogis(B0 + Bxy * df.obs$x + Bgy*df.obs$g)
+ p.y.obs[df.obs$y==0] <- 1-p.y.obs[df.obs$y==0]
+ p.s.obs <- plogis(gamma0 + gamma_y * df.obs$y + gamma_g*df.obs$g)
+ p.s.obs[df.obs$w_pred==0] <- 1 - p.s.obs[df.obs$w_pred==0]
+
+ p.obs <- p.s.obs * p.y.obs
+
+ df.unobs <- df[is.na(y.obs)]
+
+ p.unobs.1 <- plogis(B0 + Bxy * df.unobs$x + Bgy*df.unobs$g)*plogis(gamma0 + gamma_y + gamma_g*df.unobs$g)
+ p.unobs.0 <- (1-plogis(B0 + Bxy * df.unobs$x + Bgy*df.unobs$g))*plogis(gamma0 + gamma_g*df.unobs$g)
+ p.unobs <- p.unobs.1 + p.unobs.0
+ p.unobs[df.unobs$w_pred==0] <- 1 - p.unobs[df.unobs$w_pred==0]
+
+ p <- c(p.obs, p.unobs)
+
+ return(-1*(sum(log(p))))
+ }
+
+ mlefit <- stats4::mle(minuslogl = nll, start = list(B0=1, Bxy=0,Bgy=0, gamma0=5, gamma_y=0, gamma_g=0))
+
+ return(mlefit)
+}
+
logistic <- function(x) {1/(1+exp(-1*x))}
+run_simulation_depvar <- function(df, result){
+
+ accuracy <- df[,mean(w_pred==y)]
+ result <- append(result, list(accuracy=accuracy))
+
+ (model.true <- glm(y ~ x + g, data=df,family=binomial(link='logit')))
+ true.ci.Bxy <- confint(model.true)['x',]
+ true.ci.Bgy <- confint(model.true)['g',]
+
+ result <- append(result, list(Bxy.est.true=coef(model.true)['x'],
+ Bgy.est.true=coef(model.true)['g'],
+ Bxy.ci.upper.true = true.ci.Bxy[2],
+ Bxy.ci.lower.true = true.ci.Bxy[1],
+ Bgy.ci.upper.true = true.ci.Bgy[2],
+ Bgy.ci.lower.true = true.ci.Bgy[1]))
+
+ (model.feasible <- glm(y.obs~x+g,data=df,family=binomial(link='logit')))
+
+ feasible.ci.Bxy <- confint(model.feasible)['x',]
+ result <- append(result, list(Bxy.est.feasible=coef(model.feasible)['x'],
+ Bxy.ci.upper.feasible = feasible.ci.Bxy[2],
+ Bxy.ci.lower.feasible = feasible.ci.Bxy[1]))
+
+ feasible.ci.Bgy <- confint(model.feasible)['g',]
+ result <- append(result, list(Bgy.est.feasible=coef(model.feasible)['g'],
+ Bgy.ci.upper.feasible = feasible.ci.Bgy[2],
+ Bgy.ci.lower.feasible = feasible.ci.Bgy[1]))
+
+ (model.naive <- glm(w_pred~x+g, data=df, family=binomial(link='logit')))
+
+ naive.ci.Bxy <- confint(model.naive)['x',]
+ naive.ci.Bgy <- confint(model.naive)['g',]
+
+ result <- append(result, list(Bxy.est.naive=coef(model.naive)['x'],
+ Bgy.est.naive=coef(model.naive)['g'],
+ Bxy.ci.upper.naive = naive.ci.Bxy[2],
+ Bxy.ci.lower.naive = naive.ci.Bxy[1],
+ Bgy.ci.upper.naive = naive.ci.Bgy[2],
+ Bgy.ci.lower.naive = naive.ci.Bgy[1]))
+
+
+ (model.naive.cont <- lm(w~x+g, data=df))
+ naivecont.ci.Bxy <- confint(model.naive.cont)['x',]
+ naivecont.ci.Bgy <- confint(model.naive.cont)['g',]
+
+ ## my implementatoin of liklihood based correction
+ mod.caroll.lik <- logistic.correction.liklihood(df)
+ coef <- coef(mod.caroll.lik)
+ ci <- confint(mod.caroll.lik)
+
+ result <- append(result,
+ list(Bxy.est.mle = coef['Bxy'],
+ Bxy.ci.upper.mle = ci['Bxy','97.5 %'],
+ Bxy.ci.lower.mle = ci['Bxy','2.5 %'],
+ Bgy.est.mle = coef['Bgy'],
+ Bgy.ci.upper.mle = ci['Bgy','97.5 %'],
+ Bgy.ci.lower.mle = ci['Bgy','2.5 %']))
+
+
+ ## my implementatoin of liklihood based correction
+ mod.caroll.pseudo <- logistic.correction.pseudo(df)
+ coef <- coef(mod.caroll.pseudo)
+ ci <- confint(mod.caroll.pseudo)
+
+ result <- append(result,
+ list(Bxy.est.pseudo = coef['Bxy'],
+ Bxy.ci.upper.pseudo = ci['Bxy','97.5 %'],
+ Bxy.ci.lower.pseudo = ci['Bxy','2.5 %'],
+ Bgy.est.pseudo = coef['Bgy'],
+ Bgy.ci.upper.pseudo = ci['Bgy','97.5 %'],
+ Bgy.ci.lower.pseudo = ci['Bgy','2.5 %']))
+
+
+ # amelia says use normal distribution for binary variables.
+ amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('y','ystar','w_pred'))
+ mod.amelia.k <- zelig(y.obs~x+g, model='ls', data=amelia.out.k$imputations, cite=FALSE)
+ (coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))
+
+ est.x.mi <- coefse['x','Estimate']
+ est.x.se <- coefse['x','Std.Error']
+ result <- append(result,
+ list(Bxy.est.amelia.full = est.x.mi,
+ Bxy.ci.upper.amelia.full = est.x.mi + 1.96 * est.x.se,
+ Bxy.ci.lower.amelia.full = est.x.mi - 1.96 * est.x.se
+ ))
+
+ est.g.mi <- coefse['g','Estimate']
+ est.g.se <- coefse['g','Std.Error']
+
+ result <- append(result,
+ list(Bgy.est.amelia.full = est.g.mi,
+ Bgy.ci.upper.amelia.full = est.g.mi + 1.96 * est.g.se,
+ Bgy.ci.lower.amelia.full = est.g.mi - 1.96 * est.g.se
+ ))
+
+ return(result)
+
+}
+
run_simulation <- function(df, result){
accuracy <- df[,mean(w_pred==x)]
Bgy.ci.lower.naive = naive.ci.Bgy[1]))
- ## multiple imputation when k is observed
- ## amelia does great at this one.
- noms <- c()
- if(length(unique(df$x.obs)) <=2){
- noms <- c(noms, 'x.obs')
- }
-
- if(length(unique(df$g)) <=2){
- noms <- c(noms, 'g')
- }
-
-
- amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('x','w_pred'),noms=noms)
+ amelia.out.k <- amelia(df, m=200, p2s=0, idvars=c('x','w_pred'))
mod.amelia.k <- zelig(y~x.obs+g, model='ls', data=amelia.out.k$imputations, cite=FALSE)
(coefse <- combine_coef_se(mod.amelia.k, messages=FALSE))