secret
Created

  • Download Gist
library.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
##
## MissForest - nonparametric missing value imputation for mixed-type data
##
## This R script contains the necessary functions for performing imputation
## using the missForest algorithm in the statistical software R.
##
## Author: D.Stekhoven, stekhoven@stat.math.ethz.ch
##
## Modified by Steve Weston to support parallel execution
##############################################################################
 
 
missForest <- function(xmis, maxiter = 10, ntree = 100, variablewise = FALSE,
decreasing = FALSE, verbose = FALSE,
mtry = floor(sqrt(ncol(xmis))), replace = TRUE,
classwt = NULL, cutoff = NULL, strata = NULL,
sampsize = NULL, nodesize = NULL, maxnodes = NULL,
xtrue = NA, enableparallel=c('no', 'columns', 'rf'))
{ ## ----------------------------------------------------------------------
## Arguments:
## xmis = data matrix with missing values
## maxiter = stop after how many iterations (default = 10)
## ntree = how many trees are grown in the forest
## variablewise = return OOB errors for each variable separately
## decreasing = (boolean) if TRUE the columns are sorted with decreasing
## amount of missing values
## verbose = (boolean) if TRUE then missForest returns error estimates,
## runtime and if available true error during iterations
## mtry = how many variables should be tried randomly at each node
## replace = (boolean) if TRUE bootstrap sampling (with replacements)
## is performed, else subsampling (without replacements)
## classwt = list of priors of the classes in the categorical variables
## cutoff = list of class cutoffs for each categorical variable
## strata = list of (factor) variables used for stratified sampling
## sampsize = list of size(s) of sample to draw
## nodesize = minimum size of terminal nodes, vector of length 2, with
## number for continuous variables in the first entry and
## number for categorical variables in the second entry
## maxnodes = maximum number of terminal nodes for individual trees
## xtrue = complete data matrix
##
## ----------------------------------------------------------------------
## Author: Daniel Stekhoven, stekhoven@stat.math.ethz.ch
 
## prevent "R CMD check" warning resulting from foreach iteration variables
varInd <- 0
xntree <- 0
 
## stop in case of wrong inputs passed to randomForest
n <- nrow(xmis)
p <- ncol(xmis)
if (!is.null(classwt))
stopifnot(length(classwt) == p, typeof(classwt) == 'list')
if (!is.null(cutoff))
stopifnot(length(cutoff) == p, typeof(cutoff) == 'list')
if (!is.null(strata))
stopifnot(length(strata) == p, typeof(strata) == 'list')
if (!is.null(nodesize))
stopifnot(length(nodesize) == 2)
 
enableparallel <- match.arg(enableparallel)
if (enableparallel %in% c('columns', 'rf')) {
if (getDoParWorkers() == 1) {
warning('must register a foreach parallel backend to run in parallel')
enableparallel <- 'no'
} else if (verbose) {
if (enableparallel == 'columns') {
cat('parallelizing over the columns of the matrix xmis\n')
} else {
cat('parallelizing computation of the random forest model objects\n')
}
}
}
 
## remove completely missing variables
if (any(apply(is.na(xmis), 2, sum) == n)){
indCmis <- which(apply(is.na(xmis), 2, sum) == n)
xmis <- xmis[,-indCmis]
p <- ncol(xmis)
cat(' removed variable(s)', indCmis,
'due to the missingness of all entries\n')
}
## perform initial guess on xmis (mean imputation)
ximp <- xmis
xAttrib <- lapply(xmis, attributes)
varType <- character(p)
for (t.co in 1:p){
if (is.null(xAttrib[[t.co]])){
varType[t.co] <- 'numeric'
ximp[is.na(xmis[,t.co]),t.co] <- mean(xmis[,t.co], na.rm = TRUE)
} else {
varType[t.co] <- 'factor'
## take the level which is more 'likely' (majority vote)
max.level <- max(table(ximp[,t.co]))
## if there are several classes which are major, sample one at random
class.assign <- sample(names(which(max.level == summary(ximp[,t.co]))), 1)
## it shouldn't be the NA class
if (class.assign != "NA's"){
ximp[is.na(xmis[,t.co]),t.co] <- class.assign
} else {
while (class.assign == "NA's"){
class.assign <- sample(names(which(max.level ==
summary(ximp[,t.co]))), 1)
}
ximp[is.na(xmis[,t.co]),t.co] <- class.assign
}
}
}
## extract missingness pattern
NAloc <- is.na(xmis) # where are missings
noNAvar <- apply(NAloc, 2, sum) # how many are missing in the vars
sort.j <- order(noNAvar) # indices of increasing amount of NA in vars
if (decreasing)
sort.j <- rev(sort.j)
sort.noNAvar <- noNAvar[sort.j]
## compute a list of column indices for each task
nzsort.j <- sort.j[sort.noNAvar > 0]
if (enableparallel == 'columns') {
'%cols%' <- get('%dopar%')
idxList <- as.list(isplitVector(nzsort.j, chunkSize=getDoParWorkers()))
} else {
## force column loop to be sequential
'%cols%' <- get('%do%')
idxList <- nzsort.j
}
 
## output
Ximp <- vector('list', maxiter)
## initialize parameters of interest
iter <- 0
k <- length(unique(varType))
convNew <- rep(0, k)
convOld <- rep(Inf, k)
OOBerror <- numeric(p)
names(OOBerror) <- varType
 
## setup convergence variables w.r.t. variable types
if (k == 1){
if (unique(varType) == 'numeric'){
names(convNew) <- c('numeric')
} else {
names(convNew) <- c('factor')
}
convergence <- c()
OOBerr <- numeric(1)
} else {
names(convNew) <- c('numeric', 'factor')
convergence <- matrix(NA, ncol = 2)
OOBerr <- numeric(2)
}
 
## function to yield the stopping criterion in the following 'while' loop
stopCriterion <- function(varType, convNew, convOld, iter, maxiter){
k <- length(unique(varType))
if (k == 1){
(convNew < convOld) & (iter < maxiter)
} else {
((convNew[1] < convOld[1]) | (convNew[2] < convOld[2])) & (iter < maxiter)
}
}
 
## iterate missForest
while (stopCriterion(varType, convNew, convOld, iter, maxiter)){
if (iter != 0){
convOld <- convNew
OOBerrOld <- OOBerr
}
cat(" missForest iteration", iter+1, "in progress...")
t.start <- proc.time()
ximp.old <- ximp
 
for (idx in idxList) {
results <- foreach(varInd=idx, .packages='randomForest') %cols% {
obsi <- !NAloc[,varInd] # which i's are observed
misi <- NAloc[,varInd] # which i's are missing
obsY <- ximp[obsi, varInd] # training response
obsX <- ximp[obsi, seq(1, p)[-varInd]] # training variables
misX <- ximp[misi, seq(1, p)[-varInd]] # prediction variables
typeY <- varType[varInd]
if (typeY == 'numeric'){
## train random forest on observed data
if (enableparallel == 'rf') {
RF <- foreach(xntree=idiv(ntree, chunks=getDoParWorkers()),
.combine='combine', .multicombine=TRUE,
.packages='randomForest') %dopar% {
randomForest(
x = obsX,
y = obsY,
ntree = xntree,
mtry = mtry,
replace = replace,
sampsize = if (!is.null(sampsize)) sampsize[[varInd]] else
if (replace) nrow(obsX) else ceiling(0.632*nrow(obsX)),
nodesize = if (!is.null(nodesize)) nodesize[1] else 1,
maxnodes = if (!is.null(maxnodes)) maxnodes else NULL)
}
## record out-of-bag error
oerr <- mean((predict(RF) - RF$y) ^ 2, na.rm=TRUE)
} else {
RF <- randomForest(
x = obsX,
y = obsY,
ntree = ntree,
mtry = mtry,
replace = replace,
sampsize = if (!is.null(sampsize)) sampsize[[varInd]] else
if (replace) nrow(obsX) else ceiling(0.632*nrow(obsX)),
nodesize = if (!is.null(nodesize)) nodesize[1] else 1,
maxnodes = if (!is.null(maxnodes)) maxnodes else NULL)
## record out-of-bag error
oerr <- RF$mse[ntree]
}
## predict missing values in column varInd
misY <- predict(RF, misX)
} else { # if Y is categorical
obsY <- factor(obsY) ## remove empty classes
summarY <- summary(obsY)
if (length(summarY) == 1){ ## if there is only one level left
oerr <- 0
misY <- factor(rep(names(summarY), length(misi)))
} else {
## train random forest on observed data
if (enableparallel == 'rf') {
RF <- foreach(xntree=idiv(ntree, chunks=getDoParWorkers()),
.combine='combine', .multicombine=TRUE,
.packages='randomForest') %dopar% {
randomForest(
x = obsX,
y = obsY,
ntree = xntree,
mtry = mtry,
replace = replace,
classwt = if (!is.null(classwt)) classwt[[varInd]] else
rep(1, nlevels(obsY)),
cutoff = if (!is.null(cutoff)) cutoff[[varInd]] else
rep(1/nlevels(obsY), nlevels(obsY)),
strata = if (!is.null(strata)) strata[[varInd]] else obsY,
sampsize = if (!is.null(sampsize)) sampsize[[varInd]] else
if (replace) nrow(obsX) else ceiling(0.632*nrow(obsX)),
nodesize = if (!is.null(nodesize)) nodesize[2] else 5,
maxnodes = if (!is.null(maxnodes)) maxnodes else NULL)
}
## record out-of-bag error
ne <- as.integer(predict(RF)) != as.integer(RF$y)
ne <- ne[! is.na(ne)]
oerr <- sum(ne) / length(ne)
} else {
RF <- randomForest(
x = obsX,
y = obsY,
ntree = ntree,
mtry = mtry,
replace = replace,
classwt = if (!is.null(classwt)) classwt[[varInd]] else
rep(1, nlevels(obsY)),
cutoff = if (!is.null(cutoff)) cutoff[[varInd]] else
rep(1/nlevels(obsY), nlevels(obsY)),
strata = if (!is.null(strata)) strata[[varInd]] else obsY,
sampsize = if (!is.null(sampsize)) sampsize[[varInd]] else
if (replace) nrow(obsX) else ceiling(0.632*nrow(obsX)),
nodesize = if (!is.null(nodesize)) nodesize[2] else 5,
maxnodes = if (!is.null(maxnodes)) maxnodes else NULL)
## record out-of-bag error
oerr <- RF$err.rate[[ntree,1]]
}
## predict missing values in column varInd
misY <- predict(RF, misX)
}
}
list(varInd=varInd, misY=misY, oerr=oerr)
}
 
## update the master's copy of the data
for (res in results) {
misi <- NAloc[,res$varInd]
ximp[misi, res$varInd] <- res$misY
OOBerror[res$varInd] <- res$oerr
}
}
cat('done!\n')
 
iter <- iter+1
Ximp[[iter]] <- ximp
t.co2 <- 1
## check the difference between iteration steps
for (t.type in names(convNew)){
t.ind <- which(varType == t.type)
if (t.type == "numeric"){
convNew[t.co2] <- sum((ximp[,t.ind]-ximp.old[,t.ind])^2)/sum(ximp[,t.ind]^2)
} else {
dist <- sum(as.character(as.matrix(ximp[,t.ind])) != as.character(as.matrix(ximp.old[,t.ind])))
convNew[t.co2] <- dist / (n * sum(varType == 'factor'))
}
t.co2 <- t.co2 + 1
}
 
## compute estimated imputation error
if (!variablewise){
NRMSE <- sqrt(mean(OOBerror[varType=='numeric'])/
var(as.vector(as.matrix(xmis[,varType=='numeric'])),
na.rm = TRUE))
PFC <- mean(OOBerror[varType=='factor'])
if (k==1){
if (unique(varType)=='numeric'){
OOBerr <- NRMSE
names(OOBerr) <- 'NRMSE'
} else {
OOBerr <- PFC
names(OOBerr) <- 'PFC'
}
} else {
OOBerr <- c(NRMSE, PFC)
names(OOBerr) <- c('NRMSE', 'PFC')
}
} else {
OOBerr <- OOBerror
names(OOBerr)[varType=='numeric'] <- 'MSE'
names(OOBerr)[varType=='factor'] <- 'PFC'
}
 
if (any(!is.na(xtrue))){
err <- suppressWarnings(mixError(ximp, xmis, xtrue))
}
## return status output, if desired
if (verbose){
delta.start <- proc.time() - t.start
if (any(!is.na(xtrue))){
cat(" error(s):", err, "\n")
}
cat(" estimated error(s):", OOBerr, "\n")
cat(" difference(s):", convNew, "\n")
cat(" time:", delta.start[3], "seconds\n\n")
}
}#end while((convNew<convOld)&(iter<maxiter)){
 
## produce output w.r.t. stopping rule
if (iter == maxiter){
if (any(is.na(xtrue))){
out <- list(ximp = Ximp[[iter]], OOBerror = OOBerr)
} else {
out <- list(ximp = Ximp[[iter]], OOBerror = OOBerr, error = err)
}
} else {
if (any(is.na(xtrue))){
out <- list(ximp = Ximp[[iter-1]], OOBerror = OOBerrOld)
} else {
out <- list(ximp = Ximp[[iter-1]], OOBerror = OOBerrOld,
error = suppressWarnings(mixError(Ximp[[iter-1]], xmis, xtrue)))
}
}
class(out) <- 'missForest'
return(out)
}
 
 
varClass <- function(x){
xAttrib <- lapply(x, attributes)
p <- ncol(x)
x.types <- character(p)
for (t.co in 1:p){
if (is.null(xAttrib[[t.co]])){
x.types[t.co] <- 'numeric'
} else {
x.types[t.co] <- 'factor'
}
}
return(x.types)
}
 
 
mixError <- function(ximp, xmis, xtrue)
{
## Purpose:
## Calculates the difference between to matrices. For all numeric
## variables the NRMSE is used and for all categorical variables
## the relative number of false entries is returned.
## ----------------------------------------------------------------------
## Arguments:
## ximp = (imputed) matrix
## xmis = matrix with missing values
## xtrue = true matrix (or any matrix to be compared with ximp)
## ----------------------------------------------------------------------
## Author: Daniel Stekhoven, Date: 26 Jul 2010, 10:10
 
if (class(ximp)=='missForest')
stop("'xmis' is not of class 'missForest' - maybe you forgot to point at the\n list element $ximp from the missForest output object.")
x.types <- varClass(ximp)
n <- nrow(ximp)
k <- length(unique(x.types))
err <- rep(Inf, k)
t.co <- 1
if (k == 1){
if (unique(x.types) == 'numeric'){
names(err) <- c('NRMSE')
} else {
names(err) <- c('PFC')
t.co <- 1
}
} else {
names(err) <- c('NRMSE', 'PFC')
t.co <- 2
}
## for (t.type in names(err)){
for (t.type in x.types){
t.ind <- which(x.types == t.type)
if (t.type == "numeric"){
err[1] <- nrmse(ximp[,t.ind], xmis[,t.ind], xtrue[,t.ind])
} else {
dist <- sum(as.character(as.matrix(ximp[,t.ind])) != as.character(as.matrix(xtrue[,t.ind])))
no.na <- sum(is.na(xmis[,x.types == 'factor']))
if (no.na == 0){
err[t.co] <- 0
} else {
err[t.co] <- dist / no.na
}
}
}
return(err)
}
 
 
nrmse <- function(ximp, xmis, xtrue){
mis <- is.na(xmis)
sqrt(mean((ximp[mis]-xtrue[mis])^{2})/var(xtrue[mis]))
}
 
 
prodNA <- function(x, noNA = 0.1){
n <- nrow(x)
p <- ncol(x)
NAloc <- rep(FALSE, n*p)
NAloc[sample(n*p, floor(n*p*noNA))] <- TRUE
x[matrix(NAloc, nrow = n, ncol = p)] <- NA
return(x)
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.