#------------------------------------------------------------------------# # created on : JULY 18, 2012 # AFFILIATION : DEPARTMENT OF STATISTICS, NORTH CAROLINA STATE UNIVERSITY # EMAIL : WANG@STAT.NCSU.EDU # Computer code for "VARIABLE SELECTION FOR CENSORED QUANTILE REGRESION" # by Wang, H., Zhou, J. and Li, Y. (2012) #------------------------------------------------------------------------# rm(list=ls()) library(dr) library(survival) library(splines) library(mvtnorm) library(quantreg) Univ.Kernel.func = function(x0, x, h, kernel.type="4th") { # the kernel weight function Bnk(x0, x), where x0 is a scalar, and x is a vector # returns a vector # h is the bandwidth xx<-(x-x0)/h if(kernel.type=="normal") { w=dnorm(xx) } if(kernel.type=="4th") { xx[abs(xx)>=1]<-1 w<-105*(1-5*xx^2+7*xx^4-3*xx^6)/64 #biquadratic kernel } w<-w/sum(w) return(w) } Kernel.func <- function(U, U0, h, kernel.type="4th") { # U: n*k matrix # U0: k-vector # return: K((U-U0)/h) n = nrow(U) if(kernel.type=="4th") { tt = rbind(U, U0) tmp = apply(tt, 2, function(x) { Univ.Kernel.func(x[1:n],x[n+1],h) }) tmp = apply(tmp, 1, prod) tmp = tmp/sum(tmp) } if(kernel.type=="normal") # use multivariate normal density as the kernel function { k = length(U0) tt = t(t(U)-U0)/h tmp = dmvnorm(tt, mean=rep(0,k), sigma=diag(k), log=FALSE) tmp = tmp/sum(tmp) } return(tmp) } BT.weight.func = function(y,delta) { # the weight of Bang-Tsiatis (2003) estimator # y: observed survival times # delta: censoring indicator #weight is an internal function to calculate delta/G(yi) ind=order(y) y=y[ind] delta=delta[ind] n=length(y) s = numeric(length(y)) l = survfit(Surv(y,1-delta)~1) s[duplicated(y)==F] = l$surv index=seq(1,length(y),1) s[duplicated(y)==T]=s[index[duplicated(y)==T]-1] if (s[length(y)]==0) { s[length(y)]=1 } #assign any nonzero value to s[n] to avoid NaN for (j in 1:(n-1)) { if (s[j+1]==0) { s[j+1]=s[j] } } weight=delta/s ### avoid zero denominator weight2 = rep(0,n) weight2[ind] = weight return(weight2) } BT.est.func = function(y, x, delta, tau) { # Bang-Tsiatis estimator for censored quantile regression without any penalization # y: observed survival times # delta: censoring indicator # x: design matrix, does not include the intercept n=length(y) W=BT.weight.func(y,delta) #weight vector rq0 = rq(y~x, weights=W, tau=tau) return(list(coef=rq0$coef, W=W)) } PIPW.func = function(y, x, delta, tau, lams, eps=0.000001) { # Penalized inverse probability weighted method of Shows, Lu and Zhang (2010) # i.e. BT estimator with adaptive lasso penalty # tuning parameter is selected by BIC # y: observed survival times # delta: censoring indicator # x: design matrix, does not include the intercept # lams: a grid of lambdas # inital value and adaptive weights n<-length(y) tmp = BT.est.func(y, x, delta, tau) b0 = tmp$coef wt = tmp$W # delta/\hat G(y) awt = 1/abs(b0) #adaptive weights X = cbind(1, x) # weighted y vector and design matrix (weighted by delta/\hat G(y)) y.w = y*wt X.w = X*wt # calculate \tilde \sigma #ehat = y - X%*%b0 #sigma = mean(wt * ehat *(tau - 1*(ehat<0))) ehat = y.w - X.w%*%b0 sigma = mean(ehat *(tau - 1*(ehat<0))) BIC = COEF = NULL for(lambda in lams) { # penalized estimator lam = lambda * awt pcoef = rq.fit.lasso(x=X.w, y=y.w, tau=tau, lambda=lam, beta = 0.9995, eps = 1e-06)$coef res = y.w - X.w%*%pcoef edf = sum(abs(res)<=eps) fid = 2/sigma*sum(res*(tau-1*(res< 0))) BIC = c(BIC, fid + log(n)*edf) COEF = rbind(COEF, pcoef) } idx = order(BIC)[1] coeff = COEF[idx,] lam = lams[idx] plot(BIC~lams); abline(v=lam,col=2) out = list(BT=b0, PIPW=coeff, lam=lam) return(out) } tauhat.func<- function(y0, x0, y, x, delta, h, kernel.type="4th") { # estimate the cond. censoring probability P(T1) Bn = Kernel.func(x, x0, h, kernel.type) if(p==1) Bn = Univ.Kernel.func(x, x0, h, kernel.type) if (y0tau.star) w[ind[i]] = (tau-tau.star)/(1-tau.star) else w[ind[i]]=0 } # pseudo observations ind2 = which(w!=1) y.pse = rep(max(y)+100, length(ind2)) yy = c(y, y.pse) xx = rbind(x, x[ind2,]) ww = c(w, 1-w[ind2]) out = cbind(yy, ww, xx) # xx does not include the intercept return(out) } LCRQ.func <- function(y, x, DIR, delta, tau, h, kernel.type="4th") { # Locally weighted censored quantile regression method (without any penalization) # DIR: indices # local weights are obtained by the cond. distribution of T given DIR # x: does not include the first column of 1's corresponding to the intercept tmp = Pseudo.func(y, x, DIR, delta, tau, h, kernel.type) yy = tmp[,1] ww = tmp[,2] xx = tmp[,-(1:2)] rq1 = rq(yy~xx, weights=ww, tau=tau) result<-rq1$coeff result } cv.function<-function(y,x,delta, DIR, nfold=5, h, tau, kernel.type="4th") { # cross validation for selecting the bandwidth n = length(y) m<-n/nfold pp<-1:n pp1<-sample(pp) ##a random permutation of 1:n fpred.5cv = NULL for (i in 1:nfold) { #validation data ind<-pp1[seq((i-1)*m+1,i*m,1)] xv<-x[ind,] yv<-y[ind] deltav = delta[ind] #training data xt<-x[-ind,] yt<-y[-ind] deltat<-delta[-ind] DIRt<-as.matrix(DIR[-ind,]) beta<-LCRQ.func(yt, xt, DIRt, deltat,tau=tau, h, kernel.type) pred<-beta[1]+xv%*%beta[-1] ind2 = which(deltav==1) tmp.error = sum(abs(yv[ind2]-pred[ind2])) #absolute prediction error based on the ith validation sample fpred.5cv = c(fpred.5cv, tmp.error) } result<- mean(fpred.5cv) result } PROM.func = function(y, x, DIR, delta, tau, h, kernel.type, lams, awt=NA) { if(is.na(awt[1])) { ROM = LCRQ.func(y, x, DIR, delta, tau, h, kernel.type) awt = 1/pmax(ROM^2,0.00001)[-1] } X = cbind(1, x) tmp = Pseudo.func(y, x, DIR, delta, tau, h, kernel.type) ww = tmp[,2] yy = tmp[,1]*ww xx = cbind(1,tmp[,-(1:2)])*ww if(length(lams)>1) #then select lambda based on SBIC { SBIC = COEF = NULL for(i in 1:length(lams)) { lambda = c(0, lams[i]*awt) coef = rq.fit.lasso(xx, yy, tau = tau, lambda=lambda, beta = .9995, eps = 1e-06)$coef COEF = rbind(COEF, coef) #track the estimates #estimated residuals res = y - X%*%coef Mn = 1/n*t(X)%*%matrix(tau- ww[1:n]*(res<0), ncol=1) Dn = 1/n * t(X)%*% diag(tau*ww[1:n]^2 + tau^2*(1-2*ww[1:n]))%*%X tmp.Rao = n*t(Mn)%*%solve(Dn)%*%Mn p = sum(abs(coef)>0.00001) tmp.SBIC = tmp.Rao + p*log(n) SBIC = c(SBIC, tmp.SBIC) } lam.star = lams[which.min(SBIC)] PROM = COEF[which.min(SBIC),] } else{ lam.star = lams lambda = c(0, lam.star*awt) PROM = rq.fit.lasso(xx, yy, tau = tau, lambda=lambda, beta = .9995, eps = 1e-06)$coef } return(list(lam=lam.star, PROM=PROM)) } #### The following R code are for Slice Inverse Regression in censored data. ##### Program was developed by Dr. Wei Sun ##### and can be downloaded from http://www.bios.unc.edu/~weisun/software.htm "cen.sir" <- function(y, delta, x, n.slice, joint.edrs, h, c=0.05){ "cov1" <- function(x, use="pair"){ n = nrow(x); c = cov(x, use=use)*(n-1)/n; c } "kernel.est" <- function(Bx,h){ n = nrow(Bx); r = ncol(Bx); b = rep(h, r); kernel.x = matrix(rep(0,n*n), nrow=n); for (i in 1:n){ Bx.temp = t(matrix(rep(Bx[i,],n), nrow=r, ncol=n)); d2 = ((Bx - Bx.temp)/b)^2; ds = apply(d2, 1, sum); fh = exp(-0.5*(ds)); kernel.x[i,] = fh; } kernel.x } "cond.sur.est" <- function(kernel.mtr, y, c){ n = length(y); s.hat = rep(0, n) for (i in 1:n){ yi = (1:n)[y>y[i]]; fh = kernel.mtr[i,]; if(length(yi)>0){ s.hat[i] = sum(fh[yi], na.rm=TRUE)/sum(fh, na.rm=TRUE); s.hat[i] = max(s.hat[i], c, na.rm=TRUE); }else{ s.hat[i] = c; } } s.hat } "weight.est" <- function(t1, t2, index.x, y, delta, kernel.mtr, s.hat){ if (t1 >= t2){ cat(paste(t1, "\t", t2, "\n")); stop("t1 >= t2!"); } # equation (5.2) fhatx0 = mean(kernel.mtr[index.x,], na.rm=TRUE) lambdahat.ttx.temp = kernel.mtr[index.x,] * (t1 n2){ h1 = lt%%h; h2 = h - h1; index = rep(c(n1, n2), c(h1, h2)); } t.slice=numeric(h+1); # (h+1) time points t.slice[1]=min(t) - 0.000001; end = 0; for(i in 1:h){ bgn = end + 1; end = end + index[i]; t.slice[i+1] = t[end]; } t.slice } # order the data by survival time first ordr = order(y, -delta); y = y[ordr]; x = x[ordr,]; delta = delta[ordr]; # first, estimate the kernel matrix and conditional survial function Bx = x %*% joint.edrs; kernel.mtr = kernel.est(Bx, h); s.hat = cond.sur.est(kernel.mtr, y, c); # sencondly, calculate the slice mean m_h t.slice = slice.time(y, n.slice); m = matrix(0, nrow=n.slice, ncol=ncol(x)); p.hat = rep(1,(n.slice+1)); p = rep(1,n.slice); e.hat.x = matrix(0, nrow=(n.slice+1), ncol=ncol(x)); x.bar = apply(x, 2, mean, na.rm=TRUE); e.hat.x[1,] = x.bar; nobs = length(y); for(j in 1:(n.slice-1)){ weight.vect = rep(1,nobs); idx = (1:nobs); idx.case1 = idx[yc]; idx.case2 = idx[y>=t.slice[(j+1)]]; for(i in idx.case1){ weight.vect[i] = weight.est(y[i], t.slice[(j+1)], i, y, delta, kernel.mtr, s.hat); } p.hat[(j+1)] = sum(weight.vect[idx.case1], na.rm=TRUE)/nobs; p.hat[(j+1)] = p.hat[(j+1)]+sum(weight.vect[idx.case2],na.rm=TRUE)/nobs; if(length(idx.case1)>1){ x.case1 = x[idx.case1,]*weight.vect[idx.case1] ave.case1 = apply(x.case1, 2, sum, na.rm=TRUE)/nobs; }else if(length(idx.case1)==1){ ave.case1 = x[idx.case1,]*weight.vect[idx.case1]/nobs; }else if(length(idx.case1)==0){ ave.case1 = 0; } if(length(idx.case2)>1){ ave.case2 = apply(x[idx.case2,], 2, sum, na.rm=TRUE)/nobs; }else if(length(idx.case2)==1){ ave.case2 = x[idx.case2,]/nobs; }else if(length(idx.case2)==0){ ave.case2 = 0; } e.hat.x[(j+1),] = ave.case1 + ave.case2; m[j,] = (e.hat.x[j,]-e.hat.x[(j+1),])/(p.hat[j]-p.hat[(j+1)]) - x.bar; p[j] = p.hat[j] - p.hat[(j+1)]; } m[n.slice,] = e.hat.x[n.slice,]/p.hat[n.slice] - x.bar; p[n.slice] = p.hat[n.slice]; # at last, compute the SIR direction mp = m*sqrt(p); sigma.eta = t(mp) %*% mp; sigma.x = cov1(x, use="pair"); eign = eigen.decomp(sigma.eta, sigma.x); ordr = order(eign$values, decreasing=TRUE); e.val = eign$values[ordr]; e.vec = eign$vectors[,ordr]; if(is.null(colnames(x))){ x.names = paste("X", 1:ncol(x), sep=""); }else{ x.names = colnames(x); } dimnames(e.vec) = list(x.names, paste("Dir", 1:ncol(e.vec), sep="")); csir = list(y=y, x=x, delta=delta, eval=e.val, evec=e.vec, nslice=n.slice); csir$c = c; csir$h = h; class(csir) = "csir"; csir } "double.slice" <- function(y, delta, x, n.slice1, n.slice0){ "cov1" <- function(x, use="pair"){ n = nrow(x); c = cov(x, use=use)*(n-1)/n; c } "slice.idx" <- function(y, h, m){ ly = length(y); if(m < max(y) ) {stop("y is not a valid index vector");} n1 = ceiling(ly/h); n2 = floor(ly/h); split = numeric(m); if(n1==n2){ n = ly/h; index = rep(n, h); }else if(n1 > n2){ h1 = ly%%h; h2 = h - h1; index = rep(c(n1, n2), c(h1, h2)); } end = 0; for(i in 1:h){ bgn = end + 1; end = end + index[i]; split[y[bgn:end]] = i; } split } # order the data by survival time first ordr = order(y, -delta); y = y[ordr]; x = x[ordr,]; delta = delta[ordr]; ds.idx = numeric(nrow(x)); y.idx0 = (1:nrow(x))[delta==0]; y.idx0 = y.idx0[order(y[delta==0])]; ds.idx0 = slice.idx(y.idx0, n.slice0, nrow(x)); y.idx1 = (1:nrow(x))[delta==1]; y.idx1 = y.idx1[order(y[delta==1])]; ds.idx1 = slice.idx(y.idx1, n.slice1, nrow(x)); ds.idx[ds.idx0 > 0] = ds.idx0[ds.idx0 > 0]; ds.idx[ds.idx1 > 0] = ds.idx1[ds.idx1 > 0] + n.slice0; n.per.slice = as.vector(table(ds.idx)); probs = n.per.slice/nrow(x); for(i in 1:length(n.per.slice)){ x.slice = x[(1:nrow(x))[ds.idx==i],]; cov.slice = cov1(x.slice, use="pair"); if(i==1){ ave.covx = probs[i]*cov.slice; }else{ ave.covx = ave.covx + probs[i]*cov.slice; } } sigma.x = cov1(x, use="pair"); sigma.eta = sigma.x - ave.covx; eign = eigen.decomp(sigma.eta, sigma.x); ordr = order(eign$values, decreasing=TRUE); e.val = eign$values[ordr]; e.vec = eign$vectors[,ordr]; if(is.null(colnames(x))){ x.names = paste("X", 1:ncol(x), sep=""); }else{ x.names = colnames(x); } dimnames(e.vec) = list(x.names, paste("Dir", 1:ncol(e.vec), sep="")); n.s = n.slice1 + n.slice0; ds = list(y=y, x=x, delta=delta, eval=e.val, evec=e.vec, nslice=n.s); ds$nslice0 = n.slice0; ds$nslice1 = n.slice1; class(ds) = "ds"; ds } "edr.n" <- function(object, n){ object$evec[,1:n] } "edr.percent" <- function(object, percent){ if(percent > 1 || percent < 0){ stop("percent should be between 0 and 1\n"); } values = object$eval; vectors = object$evec; j=1; while(sum(values[1:j])/sum(values) < percent){ j=j+1; # take the first j eigenvalues } pct = round(sum(values[1:j])/sum(values), 2); cat(paste("eigen.value =", "\n")); cat(signif(values,3)); cat("\n"); cat(paste("First", j, "eigen values explain", pct, "variance", "\n")); cat("\n"); vectors.mtr = vectors[,1:j]; vectors.mtr } "eigen.decomp" <- function(m1, m2, tol=1e-5){ # cholesky decomposition of m2 = t(cm2) %*% cm2 # and inverse(t(cm2)) = t(inverse(cm2)) cm2 = chol(m2); inv.cm2 = cm2; idx.cm2 = diag(cm2)>tol; inv.cm2[idx.cm2, idx.cm2] = solve(cm2[idx.cm2, idx.cm2]); m3 = t(inv.cm2) %*% m1 %*% (inv.cm2); svd.m3 = svd(m3); eigen.value = svd.m3$d; eigen.vect = inv.cm2 %*% svd.m3$v; result = list(values=eigen.value, vectors=eigen.vect); result } "plot.3d.sir" <- function(object, which=1:2, angles=c(60, 120), z.plane=NULL,logY=FALSE) { library(scatterplot3d) if(length(which)!=2){ stop("Please indicate 2 and only 2 directions for plot.3d\n"); } if(length(angles)>6){ stop("no more than 6 directions can be plot at one time"); } dirs = object$x %*% object$evec[,which]; if(logY){ surv = log(object$y); labZ = "log(survival time)"; }else{ surv = object$y; labZ = "survival time"; } labX = colnames(object$evec[,which]); if(length(angles)==2){ par(mfrow=c(1,2)); } if(length(angles)==3 || length(which)==4){ par(mfrow=c(2,2)); } if(length(angles)==5 || length(which)==6){ par(mfrow=c(2,3)); } d = object$delta; for(i in 1:length(angles)){ s3d = scatterplot3d(dirs[,1], dirs[,2], xlab=labX[1], grid=TRUE, ylab=labX[2], zlab=labZ, surv, angle=angles[i], type="n"); s3d$points3d(dirs[d==1,1], dirs[d==1,2], surv[d==1], col="blue", type="p", pch=16); s3d$points3d(dirs[d==0,1], dirs[d==0,2], surv[d==0], col="red", type="p", pch=10); if(!is.null(z.plane)){ s3d$plane3d(z.plane, 0 ,0); } } } "plot.sir" <- function(object, which=1:ncol(object$evec), logY=FALSE) { if(length(which)>6){ stop("no more than 6 directions can be plot at one time"); } dirs = object$x %*% object$evec[,which]; if(logY){ surv = log(object$y); labY = "log(survival time)"; }else{ surv = object$y; labY = "survival time"; } labX = colnames(object$evec)[which]; if(length(which)==2){ par(mfrow=c(1,2)); } if(length(which)==3 || length(which)==4){ par(mfrow=c(2,2)); } if(length(which)==5 || length(which)==6){ par(mfrow=c(2,3)); } for(i in 1:length(which)){ plot(dirs[,i][object$delta==1], surv[object$delta==1], col="blue", type="p", pch=16, xlab=labX[i], ylab=labY, main="", xlim=range(dirs[,i]), ylim=range(surv)) points(dirs[,i][object$delta==0], surv[object$delta==0], col="red", type="p", pch=10); legend(min(dirs[,i]) + 0.05*(max(dirs[,i]) - min(dirs[,i])), min(surv) + 0.95*(max(surv) - min(surv)), legend=c("censored", "uncensored"), col=c("red", "blue"), pch=c(10, 16)) } } "plot.csir" <- function(object, which=1:ncol(object$evec), logY=FALSE) { plot.sir(object, which=which, logY=logY) } "plot.ds" <- function(object, which=1:ncol(object$evec), logY=FALSE) { plot.sir(object, which=which, logY=logY) } "print.csir" <- function(object, digits = max(3, getOption("digits") - 3), ...) { cat("Censored Sliced Inverse Regression Model\n\n") cat(paste("Number of observation: ", length(object$y), "\n")) n.censor = length(object$y[object$delta==0]); cat(paste("Number of censored observation: ", n.censor, "\n")) cat(paste("Number of predictors: ", ncol(object$x), "\n")) cat(paste("Number of slices: ", (object$nslice), "\n")) cat(paste("Kernel width: ", (object$h), "\n\n")) cum.e = cumsum(object$eval/sum(object$eval)) evals = rbind(object$eval, cum.e) rownames(evals) = c("Eigenvalues", "Cum.Sum.R^2"); colnames(evals) = colnames(object$evec); cat("Eigenvalues:\n") print(evals, digits=digits) cat("\nAsym Chi-square test of SIR directions:\n") print(sir.test(object), digits=digits) cat("\nEigenvectors:\n") print(object$evec, digits=digits) invisible(object) } "print.ds" <- function(object, digits = max(3, getOption("digits") - 3), ...) { cat("Double Slicing of Survival time\n\n") cat(paste("Number of observation: ", length(object$y), "\n")) n.censor = length(object$y[object$delta==0]); cat(paste("Number of censored observation: ", n.censor, "\n")) cat(paste("Number of predictors: ", ncol(object$x), "\n")) cat(paste("Number of slices (uncensored): ", object$nslice1, "\n")) cat(paste("Number of slices (censored): ", object$nslice0, "\n\n")) cat("Eigenvalues:\n") cum.e = cumsum(object$eval/sum(object$eval)) evals = rbind(object$eval, cum.e) rownames(evals) = c("Eigenvalues", "Cum.Sum.R^2"); colnames(evals) = colnames(object$evec); print(evals, digits=digits) cat("\nAsym Chi-square test of SIR directions:\n") print(sir.test(object), digits=digits) cat("\nEigenvectors:\n") print(object$evec, digits=digits) invisible(object) } "sir.test" <- function(object, nd=length(object$eval)) { if(class(object) != "csir" && class(object) != "ds") { stop("wrong class of object in sir.test\n"); } e = sort(object$eval); p = length(object$eval); n = length(object$y); l = min(p, nd) chisq = numeric(l); df = numeric(l); p.val = numeric(l); for (i in 0:(l-1)){ j = i+1; chisq[j] = n*sum(e[1:(p-i)]) df[j] = (p-i)*(object$nslice-i-1) p.val[j] = 1-pchisq(chisq[j], df[j]) } test = data.frame(Chisq=chisq, df=df, p.value=p.val); rnames = character(l); for(i in 1:l){ rnames[i] = paste("D=", i-1, " vs. ", "D>=", i, sep=""); } rownames(test) = rnames; test }