{"word_count": 885, "character_count": 7307}
This afternoon, an interesting point was raised, and I wanted to get back on it (since I did publish a post on that same topic a long time ago). How can we adapt a logistic regression when all the observations do not have the same exposure. Here the model is the following: ,the occurence of an event  on the period  is unobservedthe occurence of an event  on  is observed (as well as )If we assume that the 'occurence of an event' is the first occurence of a Poisson processus, we can prove thati.e. no event occur on  if no event occur on  and no event occur on . Assuming independence between the two, we can prove that we haveWith words, it means that the probability of not having a claim in the first six months of the year is the square root of not have a claim over a year. Which makes sense.Let us generate some sample to play with it, and see if we can use some regression model here.&#62; n=1e5&#62; set.seed(1)&#62; X = runif(n)&#62; N = rexp(n,.2)&#62; E = runif(n,X)&#62; Y = (N&#60;E)*1&#62; df=data.frame(Y,E=ceiling(E*12)/12,X)&#62; tail(df)       Y         E          X99995  0 0.8333333 0.3931627599996  0 0.9166667 0.0309145999997  0 1.0000000 0.2247494499998  0 1.0000000 0.9847557599999  0 0.5000000 0.09235741100000 0 0.2500000 0.12311414Here, the average exposure if almost 80% of a year,&#62; mean(df$E)[1] 0.7883208and 15% of the observation experienced an event&#62; mean(df$Y)[1] 0.14029Assume that the probability of not observing an event can be explained by some covariates, denoted  through some link function (using the GLM terminology),Now, since we do observe  – and not  – we haveSo if use a log link function, we can have the same property as in the Poisson model, and the logarithm of the exposure should be taken as an offset variable.&#62; reg0=glm((Y==0)~X+offset(log(X)),data=df,family=binomial(link="log"))But we get an error here, since no starting values for the algorithm could be found. If we try to set them, we get the same error, e.g.&#62; reg_init=glm((Y==0)~X+offset(log(X)),data=df,family=poisson(link="log"))&#62; reg0=glm((Y==0)~X+offset(log(X)),data=df,family=binomial(link="log"),start=reg_init$coef)So, let us try another model. An alternative could be to usewhich is the so-called complementary log-log link, cloglog. We can also write the inverse of that link function, which remins us Gompertz distribution,Observe thatwhich can also be writtenand therefore, one can prove thatSo here we can, as in the Poisson case, add the logarithm of the exposure as an offset variable,&#62; reg1=glm((Y==0)~X+offset(log(E)),  data=df,family=binomial(link="cloglog"))and the prediction of the probability to observe an event (over a full year) is&#62; vx=seq(0,1,by=.01)&#62; v1=1-predict(reg1,newdata=data.frame(X=vx,E=1),  type="response")That is nice, but what if we want to use a probit transformation for the annual probability? Something like&#160;I've seen people trying either&#62; reg2=glm((Y==0)~X+offset(log(E)),data=df,  family=binomial)or&#62; reg3=glm((Y==0)~X,weight=E,data=df,  family=binomial)But it does not really makes sense. Actually, if we plot those three predictions, we get&#62; plot(vx,v1)&#62; v2=1-predict(reg2,newdata=data.frame(X=vx,E=1),  type="response")&#62; lines(vx,v2,col="purple")&#62; v3=1-predict(reg3,newdata=data.frame(X=vx,E=1),  type="response")&#62; lines(vx,v3,col="green",lty=2)How can we get something better? A first idea could to actually compute the log-likelihood, and to optimize it. Manually,&#62; Y=(df$Y==1)*1&#62;  X=cbind(1,df$X)&#62;  E=df$E&#62;  logL = function(beta){+    pi=(exp(X%*%beta)/(1+exp(X%*%beta)))^E+   -sum(log(dbinom(Y,size=1,prob=pi)))+   }&#62;  P=optim(fn=logL,par=c(-0.0001,-.001),+      method="BFGS")From that optimization, we can also compute a prediction&#62;  beta=P$par&#62;  v4 = exp(beta[1]+beta[2]*vx)/  (1+exp(beta[1]+beta[2]*vx))Another strategy can actually to work not on a yearly basis, but on a monthly basis. If for someone observed one month, there were no event, we should have one line, and a 0. If for someone observed three month, there was one event, we should have three lines (one per month) and two 0's, and one 1. So first, we have to generate the monthly dataset,&#62; rep_each=function(x,n){+   y=NULL+   for(i in 1:length(n)) y=c(y,rep(x[i],n[i]))+   return(y)+ }&#62; split_freq=function(Y,E){+   y=NULL+   for(i in 1:length(Y)){+     if(12*E[i]&#62;1) v=c(Y[i],rep(0,12*E[i]-1))+     if(12*E[i]==1) v=Y[i]+     y=c(y,v)+   }+   return(y)  + }&#62; index=rep_each(1:n,df$E*12)&#62; large_df=df[index,]&#62; large_df$Y=split_freq(df$Y,df$E)In the initial dataset, we observed 14,000 events,&#62; sum(df$Y)[1] 14029and here also&#62; sum(large_df$Y)[1] 14029But this time, there are much more raws: one per month of observation. We can now run a 'standard' logistic regression to predict the monthly probability to observe an event&#62; reg5=glm(Y~X,family=binomial,data=large_df)and then get a yearly prediction&#62; v5=predict(reg5,newdata=data.frame(X=vx),  type="response")&#62; v5_year=1-(1-v5)^12But it is not really working here&#62; lines(vx,v4,col="red")&#62; lines(vx,v5_year,col="blue")(there was already a post on this idea of replicating data, in the context of contingency table, trying to make connections between weights and frequency).As mentioned on rstudio-pubs-static, and discussed in journal.frontiersin.org, one can also actually use an R package dedicated to this problem,&#62; library(bbmle)&#62; reg6 &#60;- mle2(Y~dbinom(plogis(mu)^E,size=1),+   parameters=list(mu~X),+   start=list(mu=2),data=df)Our prediction is here&#62; v6=predict(reg6,newdata=data.frame(X=vx,E=1),  type="response")Last, but not least, it is also possible to use Shaffer's method (see raw.githubusercontent.com/zhenglei-gao/ for some code),&#62; library(MASS)&#62; logexp &#60;- function(exposure = 1)+ {+ linkfun &#60;- function(mu) qlogis(mu^(1/exposure))+ linkinv &#60;- function(eta)  plogis(eta)^exposure+ logit_mu_eta &#60;- function(eta) {+     ifelse(abs(eta)&#62;30,.Machine$double.eps,+            exp(eta)/(1+exp(eta))^2)+   }+   mu.eta &#60;- function(eta) {       +     exposure * plogis(eta)^(exposure-1) *+     logit_mu_eta(eta)+   }+   valideta &#60;- function(eta) TRUE+   link &#60;- paste("logexp(", deparse(substitute(exposure)), ")", sep="")+   structure(list(linkfun = linkfun, linkinv = linkinv, mu.eta = mu.eta, valideta = valideta, name = link), class = "link-glm")+ }&#62; reg7 &#60;- glm(Y~X,+ family=binomial(link=logexp(df$E)),+ data=df,start=c(1,0))The main problem with this method is that the exposure is not a variable name, but a vector, and we can only get a prediction for observation in the dataset. But it is possible here to get a lot of predictions, and to plot them,&#62; v7=predict(reg7,type="response")&#62; d=data.frame(x=df$X,y=v7,e=df$E)&#62; d=d[d$e==1,]&#62; d=d[order(d$x),]&#62; lines(vx,v7,col="orange",lty=2)&#62; lines(d$x,d$y,col="blue",lty=3)Here, we have various techniques that can be used to take into account the exposure in a logistic regression. Three of them are them are identical (numerical optimization, bbmle and Shaffer), one is close (the complementary log-log) and the other three are very far away (including weights and using in a standard logistic regression the offset component).