View source: R/impute.learn.rfsrc.R
| impute.learn.rfsrc | R Documentation |
Learns a predictive imputer from training data for later use on new data.
If the training data contain missing values, the function first
imputes them using impute. It then fits one saved full-sweep
learner per selected target on the completed training data and reuses
those learners later to update missing values in new data without
refitting on the test set.
The same saved learner bank can also be used to score new data for out-of-distribution (OOD) behavior. Note that OOD scores are available even when new data have missing values. Each selected target is reconstructed from its saved conditional learner and compared with the observed value. Target-wise discrepancies are calibrated against a training reference calculated from out-of-bag predictions computed during training.
If the training data are complete and target.mode = "all",
the initial training-data imputation step is skipped and the
full-sweep learners are fit directly from the complete training data.
If supervised.formula is supplied, the function also fits an
internal supervised forest from the training data. The supervised
forest is fit after training imputation and provides auxiliary
predictors for test-time imputation and OOD scoring. The auxiliary
predictors use supervised information learned from the training
outcomes. Supervised outcomes supplied with new data are dropped and
are not used at deployment time. Leave supervised.formula
unspecified to use the learned imputer without these auxiliary
predictors.
impute.learn.rfsrc(formula, data,
ntree = 100, nodesize = 1, nsplit = 10,
nimpute = 2, fast = FALSE, blocks,
mf.q, max.iter = 10, eps = 0.01,
ytry = NULL, always.use = NULL, verbose = TRUE,
...,
supervised.formula = NULL,
supervised.args = list(),
full.sweep.options = list(ntree = 100, nsplit = 10),
target.mode = c("missing.only", "all"),
deployment.xvars = NULL,
anonymous = TRUE,
learner.prefix = "impute.learner.",
learner.root = "learners",
out.dir = NULL,
wipe = TRUE,
keep.models = is.null(out.dir),
keep.ximp = FALSE,
save.on.fit = !is.null(out.dir),
save.ood = TRUE,
weight = NULL,
compress = 50,
share.xvar = FALSE)
save.impute.learn.rfsrc(object, path, wipe = TRUE, verbose = TRUE,
compress = 50, share.xvar = NULL)
load.impute.learn.rfsrc(path, targets = NULL, lazy = TRUE, verbose = TRUE)
## S3 method for class 'impute.learn.rfsrc'
predict(object, newdata,
max.predict.iter = 3L,
eps = 1e-3,
targets = NULL,
restore.integer = TRUE,
cache.learners = c("session", "none", "all"),
verbose = TRUE,
...)
impute.ood.rfsrc(object, newdata,
targets = NULL,
max.predict.iter = 3L,
eps = 1e-3,
cache.learners = c("all", "session", "none"),
weight = NULL,
aggregate = c("bounded.product", "weighted.mean",
"weighted.lp", "weighted.lp.log", "top.k"),
aggregate.args = list(),
return.details = FALSE,
return.reconstruction = FALSE,
verbose = TRUE,
...)
formula |
An optional symbolic model description passed to
|
data |
Training data, converted to a plain data frame before
processing. Matrices, tibbles, and |
ntree, nodesize, nsplit, nimpute, fast, blocks, max.iter, ytry, always.use, verbose |
Arguments passed to
|
mf.q |
Controls the imputation engine used by |
eps |
Finite nonnegative convergence threshold. In |
... |
For |
supervised.formula |
Optional supervised learning formula used to
augment the learned imputer for improved OOD detection in supervised
settings. The left-hand side defines the supervised response and
the right-hand side defines the raw predictor block to be learned by
|
supervised.args |
Optional named list of arguments passed to the
internal supervised |
full.sweep.options |
A named |
target.mode |
Determines which raw variables receive a saved
full-sweep learner. The default |
deployment.xvars |
Controls which raw predictors are assumed to
be available later when the saved imputer is used on new data. If
|
anonymous |
If |
learner.prefix, learner.root |
Names used when writing saved
full-sweep learners to disk. If |
out.dir |
Optional output directory. If supplied and
|
wipe |
If |
keep.models |
If |
keep.ximp |
If |
save.on.fit |
If |
compress |
A single number from 0 to 100 controlling lossless
FST compression of saved learners. The default, 50, balances file
size and saving speed. Use 100 for stronger compression at the cost
of slower saving. Applies to the target learners and the optional
supervised forest. In |
save.ood |
If |
share.xvar |
Share the completed training predictor table across
non-anonymous target learners instead of writing a separate
‘xvar.rda’ for each learner. The fitting default is |
object |
An object returned by |
path |
For |
targets |
Optional subset of target variables to load, update,
or score. Unknown names are ignored with a warning. For
|
lazy |
If |
newdata |
New data to be imputed or scored, converted to a
plain data frame before processing. The column-name and vector-column
requirements for |
max.predict.iter |
Maximum number of full-sweep passes applied to
|
restore.integer |
If |
cache.learners |
How saved learners are reused during
prediction or OOD scoring. For |
weight |
Optional nonnegative target weights used for row-level OOD
aggregation. In |
aggregate |
Row-level aggregation metric used by
|
aggregate.args |
Optional named list of tuning arguments for
|
return.details |
If |
return.reconstruction |
If |
Training begins by converting variables that are not real-valued to factors when possible; otherwise fitting stops with an error. Rows and columns that are entirely missing are removed before the training schema is stored. The imputer is then fitted in two stages:
Complete the training data. Missing values are
imputed using impute, with the same options as that
function. With mf.q = 1 and always.use = NULL,
targets are updated one at a time. Other positive settings use
the multivariate missForest generalization.
If mf.q is omitted, on-the-fly imputation is used. It is
supervised when an initial-imputation formula is used, and
unsupervised otherwise. Complete training data with
target.mode = "all" skip this stage.
Fit the saved learners. A full forest sweep is
fitted on the completed training data. For each target selected
by target.mode, a forest is fitted using rows where that
target was originally observed and predictors selected by
deployment.xvars. All saved learners use the same
completed training table; fitting them does not further update
that table.
Training stops if every requested target learner fails. If some
succeed, a partial bank is returned with one summary warning.
manifest$learners records each target's status and error,
and printing the imputer reports successful and unavailable learners.
By default, deployment.xvars = NULL uses every non-target
column as a predictor. Restrict deployment.xvars when the
training data include outcomes, future-only variables, identifiers,
or other fields that could introduce leakage or will be unavailable
in new data.
Supplying supervised.formula fits an internal supervised
forest. Its out-of-bag predicted values for training data
and predicted values for new data provide auxiliary
predictors for the saved learners. These variables can influence
both imputation and OOD scoring, but are not imputation targets.
Leave supervised.formula unspecified to use the basic
unsupervised learned imputer.
The auxiliary variables are created automatically and added to each
saved target's predictor set. deployment.xvars restricts
only the raw predictors; users do not need to supply auxiliary
columns in new data.
Ordinary forest predictions fill unavailable auxiliary predictions,
including when the supervised forest has no OOB predictions, as
with supervised.args = list(bootstrap = "none").
This fallback applies only to auxiliary predictors. OOD reference
discrepancies always use the final target learners' OOB predictions.
A saved imputer consists of a manifest and a directory of learners,
with an optional shared predictor table. Learner components use the
same serializers as fast.save and fast.load, so saving
and loading require the fst package. The supervised forest, when used, is saved
alongside the target learners. The explicit save method can save
learners from memory or from the directory where the imputer is
already saved.
Each imputer has its own directory, which can be inside a project
directory; for example, file.path(getwd(), "imputer").
Saving accepts a new directory, an empty directory, or a directory
recognized as a saved imputer by its manifest. Other nonempty
directories are rejected with either setting of wipe.
Saving cannot replace the current working directory, home directory, filesystem root, or their ancestors. A complete imputer can be saved back to the same directory. A different destination must neither contain nor be inside the existing imputer directory. An object loaded with a target subset must be saved to a different directory. Loading has none of these location restrictions.
Set compress = 100 for stronger FST compression when saving
a deployment bundle. Supply this directly to impute.learn
or save.impute.learn, rather than in
full.sweep.options. The manifest and remaining RDS metadata
use their existing compression settings. Loading requires no
compression argument.
Both training-time and explicit saving write and verify the new learners before replacing an existing destination. A failed staging operation leaves the previous saved imputer unchanged. If replacement fails, restoration of the previous directory is attempted; an unrecovered backup path is reported.
With share.xvar = TRUE, the completed training table used by
the final target learners is saved once in
‘_shared_xvar/xvar.fst’. In supervised mode this table also
includes the auxiliary training predictors actually used in those
fits. Each target stores its exact training-row indices, predictor
names and column encodings. These reconstruct the learner's
training predictors before prediction. Reconstruction is checked
against the fitted forest before its separate ‘xvar.rda’ is
omitted. Trees, responses, terminal information and OOD references
keep their existing representations. The single supervised forest
remains self-contained.
Shared storage requires anonymous = FALSE. It is independent
of compress, terminal.qualts and
terminal.quants; their existing settings still apply.
keep.ximp continues to control the returned raw completed
table. An in-memory shared-capable fit separately holds the common
predictor table needed for deferred saving. Saved shared banks
and eagerly loaded shared objects can be saved again without
reconstructing row identities from predictor values.
Load the whole imputer with load.impute.learn. Shared learner
subdirectories are not independently portable, and direct
fast.load calls on them stop with an explanatory message.
Keep the manifest, shared table and learners together when moving
or archiving the bank. A compatible shared-aware package version
is required. The updated loader also accepts the existing
independent-learner format. Saving a shared object with
share.xvar = FALSE writes that independent format.
Lazy loading leaves the common table on disk until first use. Each
prediction or OOD operation loads it at most once and reuses it
across learner accesses, including when
cache.learners = "none". Reconstructed learners remain normal
forest objects: caching or eagerly loading many learners can still
use memory for their individual predictor tables. Shared storage
primarily reduces repeated serialization and on-disk duplication.
Missing shared files, checksum mismatches and invalid mappings
cause errors rather than silently substituting initialization fills.
Prediction applies the saved learners in three steps:
Match the training schema. Columns and types in
newdata are matched to the training schema. Supervised
response columns outside the learned raw predictor block are
dropped and are not used for prediction or OOD scoring.
Initialize missing values. Missing raw values are filled with training means or modes. In supervised mode, the saved supervised forest then computes auxiliary predictors from this initialized table. The auxiliary predictors stay fixed throughout the subsequent passes.
Update with saved learners. Full-sweep passes
update missing values in the selected targets. Each target
update requires one valid prediction per requested row. Failed
or unavailable predictions leave the previous imputed values
unchanged and are recorded in target.issues. A pass
with no valid model updates is reported separately from
convergence.
With target.mode = "missing.only", a variable that was
complete in training but is missing in new data receives only an
initialization value. Use target.mode = "all" when missing
values may appear later in any raw variable. Complete training data
also require this setting because there are no missing variables
from which to select the saved targets.
Integer restoration applies only to generated values, including initialization values in columns without a target update. Observed numeric entries are unchanged.
With save.ood = TRUE, each saved learner's out-of-bag
predictions are compared with observed training values to form
target-wise reconstruction discrepancies:
Continuous and integer targets use absolute reconstruction error.
Factor targets use the negative log probability of the observed class when OOB class probabilities are available. If only OOB class labels are available, unordered factors use misclassification error and ordered factors use scaled distance between ordered levels.
Each target's discrepancy rule is saved with its reference and used
unchanged for new data. For probability-based discrepancies, the
saved probability floor is 1e-12; finite zero probabilities
use this floor. Unavailable or invalid predictions give missing
discrepancies, without switching to another rule. Each learner entry
records n.oob.finite and n.oob.nonfinite.
OOB predictions come from the final target forests after training-data imputation and auxiliary predictor construction. Those earlier steps are not repeated for each OOB sample. Missing OOB predictions are never replaced by ordinary training predictions when constructing these references.
The training-time row reference combines calibrated target scores
using a weighted mean. If weight is omitted, all saved OOD
targets receive weight 1. Named weights are matched to targets, and
omitted targets receive weight 0. These weights are also the defaults
for later OOD scoring.
impute.ood first completes the predictors in newdata
using the same schema matching, initialization, and full-sweep passes
as predict.impute.learn. It then reconstructs each requested
raw target from its saved learner and compares the reconstruction
with the observed value in newdata. A target that is missing
in a row does not contribute to that row's OOD score.
Discrepancies are converted to target-wise OOD scores using the saved target-specific training references. Values strictly above a nonempty reference's maximum, including positive infinity, receive its largest stored probability. Ties, including equality at the largest quantile, follow the reference's quantile-grid convention. Missing discrepancies and empty references are unscored.
In supervised mode, the auxiliary variables are predictors for reconstruction; the supervised response is not used in new data.
Older saved imputers that do not record the factor discrepancy rule must be refitted before OOD scoring those targets. They remain usable for imputation and numeric-only OOD scoring.
impute.ood returns two row-level summaries:
scoreCombines calibrated target scores over the
targets that are observed and scoreable in each row. The default
is a bounded product rule. Alternatives are a weighted mean,
weighted L_p, log-tail weighted L_p, and
top-k rules. These options allow greater sensitivity to
sparse but severe coordinate shifts. Unless overridden, scoring
uses the weights saved by impute.learn.
score.percentileCalibrates the row score against a training reference rebuilt from the saved target-wise training OOD scores. The reference uses the requested target subset, weights, and row aggregate, so percentile calibration remains available when any of these settings change. It is not conditioned on each new row's pattern of observed targets.
Unseen factor levels are tracked by row when matching new data to the
training schema. impute.ood flags these rows and assigns them
the maximum row-level score. If an unseen level occurs in a scored
target, its target-level discrepancy is also maximal.
impute.learn returns an object of class
c("impute.learn.rfsrc", "impute.learn"). The object
contains a manifest, optionally the fitted full-sweep learners,
optionally the internal supervised forest when
supervised.formula is used, optionally the completed raw
training predictor table, and optionally a path to the saved imputer
on disk. If save.ood = TRUE, the manifest also contains an
ood component storing compact target-wise OOD references, the
saved row-by-target training OOD score matrix used for later
percentile recalibration, and the default OOD aggregation weights.
When supervised mode is active, the manifest also records the
supervised family, response names, and the internally created
auxiliary predicted.* variable names.
Shared-capable fits also contain manifest$shared.xvar,
the common-table specification, and per-learner xvar.ref
reconstruction mappings. shared.xvar.data holds the common
table for in-memory fits with keep.models = TRUE and eagerly
loaded shared objects. It is NULL for disk-backed lazy objects.
This component is separate from ximp.
load.impute.learn returns an object of the same class.
predict.impute.learn returns a data frame with imputed values
overlaid on the raw predictor table, retaining its row names. An attribute named
"impute.learn.info" contains prediction-time diagnostics such
as the number of sweep passes, pass-difference history, caching mode,
disk-load counts, schema harmonization details, dropped supervised
response columns when present, row-wise unseen-factor flags,
supervised-auxiliary diagnostics when present, and any targets
skipped because a learner was unavailable or a prediction failed.
pass.updated.cells and pass.failed.cells count accepted
updates and failed updates in each pass; converged and
stopping.reason distinguish convergence from initialization-only,
empty-input, iteration-limit, and failed-update stopping.
conversion.issues records the row indices of nonmissing values
that became missing during numeric conversion. In both prediction and
OOD diagnostics, n.disk.loads counts successful target-learner
load operations, including repeated loads with cache.learners = "none".
disk.load.targets lists the distinct targets loaded. Supervised
forest loading is reported separately in info$supervised and is
not included in the target-learner count.
impute.ood returns an object of class
c("impute.ood.rfsrc", "impute.ood"). It is a list with the
following components:
score: the row-level aggregate of calibrated
target-wise OOD scores under the requested aggregate and
weight. Larger values indicate greater
out-of-distribution behavior. For aggregate = "weighted.lp.log",
the probability floor bounds the mathematical aggregate by
-\log(\varepsilon) for 0 < \varepsilon < 1. With
the default eps = 1e-12, the upper bound is approximately
27.63.
score.percentile: the percentile of score
relative to a row-level training reference rebuilt from the saved
target-wise training OOD scores for the requested targets,
weights, and row aggregate. For legacy fitted objects that do not
contain those saved training scores, the original saved row-level
reference is used when possible; otherwise NA.
targets.used: the number of weighted targets that
contributed to each row-level score.
target.score: optional matrix of target-wise calibrated
OOD scores, returned when return.details = TRUE.
target.delta: optional matrix of raw target-wise
reconstruction discrepancies, returned when
return.details = TRUE.
target.reconstruction: when
return.reconstruction = TRUE, a data frame containing
the saved learners' predictions for the scored targets.
reconstructed.data: when
return.reconstruction = TRUE, the harmonized raw table
with scored targets replaced by their reconstructions. Other
columns retain their harmonized values. Integer restoration applies
to generated reconstructions, preserving observed numeric values in
the other columns.
completed.data: when both return.details
and return.reconstruction are TRUE, the raw
predictor table after prediction-time imputation. This is distinct
from the target reconstruction table.
info: a list of diagnostics including harmonization
details, dropped supervised response columns when present,
row-wise unseen-factor flags, learner-loading information,
supervised-auxiliary diagnostics when present, the active row
aggregate and its arguments, whether the saved row-level
calibration was used, and any target-specific issues.
Hemant Ishwaran and Udaya B. Kogalur
Stekhoven D.J. and Buhlmann P. (2012). MissForest–non-parametric missing value imputation for mixed-type data. Bioinformatics, 28(1):112–118.
Tang F. and Ishwaran H. (2017). Random forest missing data algorithms. Statistical Analysis and Data Mining, 10:363–377.
impute.rfsrc,
rfsrc,
predict.rfsrc.
## ------------------------------------------------------------
## small data example: uses missForest for impute engine
## ------------------------------------------------------------
set.seed(101)
aq <- airquality[, c("Ozone", "Solar.R", "Wind", "Temp", "Month")]
aq$Month <- factor(aq$Month)
id <- sample(1:nrow(aq), 100)
train <- aq[id, ]
test <- aq[-id, ]
## training the imputer
fit <- impute.learn(
data = train,
ntree = 25,
mf.q = 1,
max.iter = 5,
full.sweep.options = list(ntree = 25, nsplit = 5)
)
## test time imputation
test.imp <- predict(fit, test, max.predict.iter = 2, verbose = FALSE)
print(head(test.imp))
## ------------------------------------------------------------
## Shared training predictors for a deployment bank
## ------------------------------------------------------------
## Keep these objects separate from the airquality examples below.
local({
if (requireNamespace("fst", quietly = TRUE) &&
requireNamespace("data.table", quietly = TRUE)) {
set.seed(17)
train <- data.frame(x1 = rnorm(100), x2 = runif(100),
group = factor(rep(c("a", "b"), 50)))
bank.dir <- tempfile("shared-imputer-")
fit <- impute.learn(
data = train, target.mode = "all", anonymous = FALSE,
share.xvar = TRUE, compress = 100, out.dir = bank.dir,
full.sweep.options = list(ntree = 50, nsplit = 5,
terminal.qualts = FALSE, terminal.quants = FALSE),
verbose = FALSE
)
imp <- load.impute.learn(bank.dir, verbose = FALSE)
test <- train[1:5, ]
test$x1[c(1, 3)] <- NA_real_
print(predict(imp, test, verbose = FALSE))
unlink(bank.dir, recursive = TRUE)
}
})
## OOD scoring is most informative when every deployment-time
## variable can be reconstructed, so target.mode = "all" is recommended.
## Optional named OOD weights can also be supplied here. Any omitted
## targets receive weight 0, and the saved weights are reused
## automatically later by impute.ood().
ood.fit <- impute.learn(
data = train,
ntree = 25,
mf.q = 1,
max.iter = 5,
target.mode = "all",
save.ood = TRUE,
full.sweep.options = list(ntree = 25, nsplit = 5),
verbose = FALSE
)
ood <- impute.ood(ood.fit, test, return.details = TRUE, verbose = FALSE)
print(head(ood$score))
print(head(ood$score.percentile))
## try a more spike-sensitive row aggregate
ood.lp <- impute.ood(ood.fit, test,
aggregate = "weighted.lp",
aggregate.args = list(p = 4),
verbose = FALSE)
print(head(ood.lp$score.percentile))
## ------------------------------------------------------------
## supervised OOD example: regression benchmark
## the user supplies only the raw x-columns at test time
## ------------------------------------------------------------
friedman1_sim <- function(n = 150, p = 10, sigma = 1) {
X <- matrix(runif(n * p), nrow = n)
y <- 10 * sin(pi * X[, 1] * X[, 2]) +
20 * (X[, 3] - 0.5)^2 +
10 * X[, 4] + 5 * X[, 5] +
rnorm(n, sd = sigma)
list(X = X, y = y)
}
trn <- data.frame(friedman1_sim())
tst <- data.frame(friedman1_sim())
xvars <- setdiff(names(trn), "y")
## impute data using missForest, construct a supervised forest
## - supervised forests are used to create auxiliary variables
## - improves test time OOD in supervised problems
sup.fit <- impute.learn(
data = trn,
mf.q = 1,
supervised.formula = y ~ .,
supervised.args = list(ntree = 50, nsplit = 5),
full.sweep.options = list(ntree = 25, nsplit = 5),
save.ood = TRUE,
verbose = FALSE
)
## add some missing values to the test data
xnew <- tst[, xvars, drop = FALSE]
xnew[sample(seq_len(nrow(xnew)), 5), xvars[1]] <- NA
xnew[sample(seq_len(nrow(xnew)), 5), xvars[2]] <- NA
## imputation
xnew.imp <- predict(sup.fit, xnew, max.predict.iter = 2, verbose = FALSE)
print(head(xnew.imp))
## OOD score
ood.sup <- impute.ood(sup.fit, xnew, verbose = FALSE)
print(head(ood.sup$score.percentile))
## ------------------------------------------------------------
## Save the learned imputer to disk and load it later.
## This explicit save example writes learners kept in memory.
## Uses missForest for the impute engine.
## ------------------------------------------------------------
bundle.dir <- file.path(tempdir(), "aq.imputer")
fit <- impute.learn(
data = train,
ntree = 25,
mf.q = 1,
max.iter = 5,
full.sweep.options = list(ntree = 25, nsplit = 5),
keep.models = TRUE,
verbose = FALSE
)
## Stronger compression for a deployment bundle.
save.impute.learn(fit, bundle.dir, compress = 100, verbose = FALSE)
imp <- load.impute.learn(bundle.dir, lazy = TRUE, verbose = FALSE)
test.imp <- predict(imp, test, max.predict.iter = 2, verbose = FALSE)
unlink(bundle.dir, recursive = TRUE)
## ------------------------------------------------------------
## Challenging example with factors, uses save/reload
## ------------------------------------------------------------
## load pbc, convert everything to factors
data(pbc, package = "randomForestSRC")
dta <- data.frame(lapply(pbc, factor))
dta$days <- pbc$days
dta$status <- dta$status
## split the data into unbalanced train/test data (25/75)
## the train/test data have the same levels, but different labels
idx <- sample(1:nrow(dta), round(nrow(dta) * .25))
train <- dta[idx,]
test <- dta[-idx,]
## even harder ... factor level not previously encountered in training
levels(test$stage) <- c(levels(test$stage), "fake")
test$stage[sample(seq_len(nrow(test)), 10)] <- "fake"
## train forest
fit <- suppressWarnings(
impute.learn(Surv(days, status) ~ ., train,
target.mode = "all",
save.ood = TRUE,
keep.models = TRUE)
)
## save/reload
bundle.dir <- file.path(tempdir(), "pbc.imputer")
save.impute.learn(fit, bundle.dir, verbose = FALSE)
imp <- load.impute.learn(bundle.dir, lazy = TRUE, verbose = FALSE)
test.imp <- predict(imp, test, max.predict.iter = 2, verbose = FALSE)
ood <- impute.ood(imp, test, return.details = TRUE, verbose = FALSE)
print(which(ood$info$unseen.rows))
print(summary(test.imp))
unlink(bundle.dir, recursive = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.