| Title: | Schema-Driven Machine Learning and Visualization |
|---|---|
| Description: | Machine learning and visualization package with an 'S7' backend featuring comprehensive type checking and validation, observable runs, and auditable outputs. The functional API provides one-call access to supervised and unsupervised learning through train(), cluster(), and decomp(). All configuration steps are performed using setup functions and validated. A single call to train() can handle preprocessing, decomposition, hyperparameter tuning, model stacking, and testing with nested resampling. Supports 'data.frame', 'data.table', and 'tibble' inputs and parallel execution. Plot methods for trained and resampled supervised models draw interactive figures through 'rtemis.draw'. Includes native implementations of SuperLearner, RuleFit, and Linear Additive Trees, and supports conformal prediction. The package first appeared in E.D. Gennatas (2017) <https://repository.upenn.edu/entities/publication/d81892ea-3087-4b71-a6f5-739c58626d64>. |
| Authors: | E.D. Gennatas [aut, cre, cph] (ORCID: <https://orcid.org/0000-0001-9280-3609>) |
| Maintainer: | E.D. Gennatas <[email protected]> |
| License: | BSD_3_clause + file LICENSE |
| Version: | 1.4.2 |
| Built: | 2026-10-17 04:46:54 UTC |
| Source: | https://github.com/rtemis-org/rtemis |
Schema-driven machine learning for validated, observable, auditable, and reproducible machine learning workflows.
Model plots (plot_true_pred(), plot_roc(), plot_varimp(), plot_metric(),
plot_learning(), plot_session(), plot_manhattan()) and present() render
interactive charts through 'rtemis.draw', which also provides the draw_*() functions for
data. draw_linad() draws a LINAD tree.
By convention, the last column of the data is the outcome variable, and all other columns are
predictors. Convenience function set_outcome can be used to move a specified column to the
end of the data.
Regression and Classification is performed using train().
This function allows you to preprocess, train, tune, and test models on multiple resamples.
Use available_supervised to get a list of available algorithms
For training of binary classification models, the outcome should be provided as a factor, with the second level of the factor being the 'positive' class.
Clustering is performed using cluster().
Use available_clustering to get a list of available algorithms.
Decomposition is performed using decomp().
Use available_decomposition to get a list of available algorithms.
Function documentation includes input type (e.g. "Character", "Integer", "Float"/"Numeric", etc). When applicable, value ranges are provided in interval notation. For example, Float: [0, 1) means floats between 0 and 1 including 0, but excluding 1. Categorical variables may include set of allowed values using curly braces. For example, Character: {"future", "mirai", "none"}.
rtemis internally uses methods for efficient handling of tabular data, with support for
data.frame, data.table, and tibble. If a function is documented as accepting
"tabular data", it should work with any of these data structures. If a function is documented
as accepting only one of these, then it should only be used with that structure.
For example, some optimized data.table operations that perform in-place modifications only
work with data.table objects.
Errors are signalled as classed conditions that can be handled with
tryCatch(). See rtemis_conditions for the class hierarchy.
Maintainer: E.D. Gennatas [email protected] (ORCID) [copyright holder]
Authors:
E.D. Gennatas [email protected] (ORCID) [copyright holder]
Useful links:
Report bugs at https://github.com/rtemis-org/rtemis/issues
Collapse a binary indicator matrix into a character vector of labels. For each
row, the labels of all columns equal to 1 are pasted together, comma-separated.
This is the inverse of multi-hot encoding: unlike one_hot2factor, which assumes
a single 1 per row, %BC% supports rows with multiple 1s (multi-label data, e.g.
multiple-choice survey responses, tags, or set membership). Rows of all zeros
return NA.
x %BC% labelsx %BC% labels
x |
A binary matrix or data.frame |
labels |
Character vector length equal to |
a character vector
EDG
# Multi-hot matrix: each row can belong to multiple categories x <- rbind( c(1, 0, 1), c(0, 1, 0), c(1, 1, 1), c(0, 0, 0) ) labels <- c("apple", "banana", "cherry") x %BC% labels # -> "apple,cherry", "banana", "apple,banana,cherry", NA# Multi-hot matrix: each row can belong to multiple categories x <- rbind( c(1, 0, 1), c(0, 1, 0), c(1, 1, 1), c(0, 0, 0) ) labels <- c("apple", "banana", "cherry") x %BC% labels # -> "apple,cherry", "banana", "apple,banana,cherry", NA
Ask a language model to write a summary, an evaluation, next steps and caveats from a review of a trained supervised model. Every statement cites the codes of the review findings it rests on, and the result keeps the review and a record of how the text was produced.
ai_review(x, llm, context = NULL, temperature = NULL, verbosity = 1L, ...)ai_review(x, llm, context = NULL, temperature = NULL, verbosity = 1L, ...)
x |
|
llm |
|
context |
Optional Character: Domain context for the assessment. |
temperature |
Optional Numeric [0, Inf): Sampling temperature for this call. NULL uses the model's own setting. |
verbosity |
Integer: Verbosity level. |
... |
Not used. |
The model receives the review as JSON and, if given, context: the
question the model addresses, the costs of different errors, how its
predictions will be used. It never receives the data. Without context, the
assessment states that usefulness cannot be judged.
The model answers in a declared structure whose codes are restricted to the review's findings, and the answer is checked: an answer that does not match the structure, or cites a code that is not a finding of the review, is an error. The returned object records the model, the provider, the temperature, the full prompt, a SHA-256 hash of the review sent and the time, so the assessment can be audited and, as far as the model allows, reproduced.
The written assessment is an interpretation of the review, which remains the evidence; read them together. write_text writes both as Markdown.
Requires the rtemis.llm package and access to a model.
AISupervisedReview object.
EDG
## Not run: # Requires a running Ollama server with the model pulled. mod <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(5L), verbosity = 0L ) llm <- rtemis.llm::create_Ollama(model_name = "gemma4:e4b") ai_review( mod, llm = llm, context = "Teaching example; no decisions depend on the predictions." ) ## End(Not run)## Not run: # Requires a running Ollama server with the model pulled. mod <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(5L), verbosity = 0L ) llm <- rtemis.llm::create_Ollama(model_name = "gemma4:e4b") ai_review( mod, llm = llm, context = "Teaching example; no decisions depend on the predictions." ) ## End(Not run)
Derived from decomposition_traits and the metric registry: a metric applies to an algorithm when every trait it requires is TRUE for that algorithm.
applicable_metrics(algorithm = NULL)applicable_metrics(algorithm = NULL)
algorithm |
Optional Character: Name of a decomposition algorithm,
matched case-insensitively. |
Nothing here is maintained per algorithm. reconstruction_rmse requires
invertible, so it is defined for PCA, ICA and NMF and undefined for tSNE,
UMAP and Isomap; max_abs_component_correlation requires nothing, so it is
defined everywhere. An algorithm added to decom_algorithms with a correct
traits row inherits the right metric set without any edit to the metrics
code.
data.frame. With algorithm, the registry rows that apply to it:
one row per metric, with its group, requirements, whether it needs new data,
direction and range. With NULL, one row per metric and one logical column
per algorithm.
EDG
# Every metric, and which algorithms support it applicable_metrics() # What can be computed for a UMAP embedding, which does not invert applicable_metrics("UMAP")# Every metric, and which algorithms support it applicable_metrics() # What can be computed for a UMAP embedding, which does not invert applicable_metrics("UMAP")
Apply a fitted decomposition to new data for algorithms that support this.
apply_decomp(decom, new_data, execution_config = NULL, verbosity = 1L)apply_decomp(decom, new_data, execution_config = NULL, verbosity = 1L)
decom |
Decomposition object. |
new_data |
Tabular data (data.frame, data.table, or tibble): New data to which the decomposition will be applied. |
execution_config |
Optional |
verbosity |
Integer: Verbosity level |
A fit is learned on the columns decom@config@features names, so only those
columns of new_data are transformed; the remaining columns are returned
unchanged, alongside the learned components, in the layout
[kept features, components]. decomp() resolves an unset features to
the numeric columns and records them, so a fit it produced always names
them. A Decomposition assembled by hand with no features transforms
every column of new_data and returns only the components.
A data.frame of the learned components for new_data, preceded by any
feature columns that were not decomposed.
EDG
iris_pca <- decomp(exc(iris, "Species"), algorithm = "PCA") apply_decomp(iris_pca, exc(iris, "Species"))iris_pca <- decomp(exc(iris, "Species"), algorithm = "PCA") apply_decomp(iris_pca, exc(iris, "Species"))
Apply a trained Preprocessor to new data, reusing the values learned from the training
data. For example, the same mean and mode imputation values, scale centers and
coefficients, one-hot levels, and removed features will be applied to the new data.
apply_preprocessor(preprocessor, new_data, verbosity = 1L)apply_preprocessor(preprocessor, new_data, verbosity = 1L)
preprocessor |
|
new_data |
Tabular data, i.e. data.frame, data.table, or tbl_df (tibble): New data to preprocess. |
verbosity |
Integer: Verbosity level. |
Imputation follows the preprocessor's impute_type. "meanMode" imputes the
stored training values. "missRanger" applies the forests fitted on the
training data with predict(), and imputes a feature that had no missing
training values with its stored mean or mode; predict() stops on a factor
level of an imputed feature that is absent from the training data. A
preprocessor using "micePMM" cannot be applied to new data and is refused.
Preprocessed data, in the same structure as new_data.
EDG
preprocess, setup_Preprocessor
res <- resample(iris, setup_KFold(seed = 2026)) iris_train <- iris[res[[1]], ] iris_test <- iris[-res[[1]], ] # Preprocess training data iris_pre <- preprocess(iris_train, setup_Preprocessor(scale = TRUE, center = TRUE)) # Apply the same preprocessing to test data iris_test_pre <- apply_preprocessor(iris_pre, iris_test)res <- resample(iris, setup_KFold(seed = 2026)) iris_train <- iris[res[[1]], ] iris_test <- iris[-res[[1]], ] # Preprocess training data iris_pre <- preprocess(iris_train, setup_Preprocessor(scale = TRUE, center = TRUE)) # Apply the same preprocessing to test data iris_test_pre <- apply_preprocessor(iris_pre, iris_test)
Print available algorithms for supervised learning, clustering, and decomposition.
available_supervised(verbosity = 1L) available_clustering(verbosity = 1L) available_calibration(verbosity = 1L) available_decomposition(verbosity = 1L, traits = FALSE)available_supervised(verbosity = 1L) available_clustering(verbosity = 1L) available_calibration(verbosity = 1L) available_decomposition(verbosity = 1L, traits = FALSE)
verbosity |
Integer: Verbosity level. |
traits |
Logical: If TRUE, |
Each algorithm is set up with setup_{Algorithm}(), using the name printed
here: setup_LightGBM(), setup_KMeans(), setup_PCA(). Pass the result to
train, cluster, or decomp.
Named list of algorithm descriptions, invisibly.
EDG
available_supervised() # Train with one of them, at its default hyperparameters: # train(iris, hyperparameters = setup_LightGBM()) available_clustering() available_calibration() # Calibrate with one of them: # calibrate(mod, hyperparameters = setup_Isotonic()) available_decomposition() available_decomposition(traits = TRUE)available_supervised() # Train with one of them, at its default hyperparameters: # train(iris, hyperparameters = setup_LightGBM()) available_clustering() available_calibration() # Calibrate with one of them: # calibrate(mod, hyperparameters = setup_Isotonic()) available_decomposition() available_decomposition(traits = TRUE)
Decompose a learner's error into the part that comes from being systematically wrong and the part that comes from being unstable, by refitting it over many resamples of the training set and watching what its predictions do at a fixed test set.
bias_variance( x, hyperparameters, dat_test = NULL, true_values = NULL, resampler_config = NULL, test_p = 0.3, execution_config = setup_FutureExecution(), verbosity = 1L )bias_variance( x, hyperparameters, dat_test = NULL, true_values = NULL, resampler_config = NULL, test_p = 0.3, execution_config = setup_FutureExecution(), verbosity = 1L )
x |
tabular data: Full dataset, outcome in the last column. Resamples are drawn from it after the test set is held out. |
hyperparameters |
|
dat_test |
Optional tabular data: Test set. NULL holds one out of |
true_values |
Optional Numeric vector: The true function at the test
cases, in their order. Regression: |
resampler_config |
Optional |
test_p |
Numeric (0, 1): Fraction of |
execution_config |
|
verbosity |
Integer: If > 0, print messages. |
For squared-error loss, the expected error at a point decomposes as
– irreducible noise, squared bias, and variance. This function estimates the
second and third per test case, by fitting the model on n_resamples
resamples of the training set and reading the spread and the average of the
predictions each makes at the same test cases.
The test set is held out once and every resample is drawn from what is left, which is what makes the predictions comparable across resamples: a test set that moved would confound the model's variability with the sample's.
BiasVariance object.
Squared bias is measured against true_values when you have them, and
against the observed outcome when you do not. The difference is not
cosmetic:
true_values
bias_squared is the bias, exactly. Only
simulated data has this, which is what makes a simulation study the place
to ask how a learner divides its error.
The observed outcome carries the irreducible noise, so what
is reported is and no amount of resampling
separates them. It stays comparable between learners on the same data
– they share the same – so a ranking is still meaningful
even though the level is inflated.
variance is the sample variance across resamples (dividing by
n_resamples - 1), which is unbiased for the variance of the fitted
function. bias_squared is the plug-in estimate, and is inflated by roughly
variance / n_resamples because the mean prediction is itself estimated –
so prefer many resamples over few, and treat a bias_squared of the same
order as variance / n_resamples as indistinguishable from zero.
The decomposition above is for squared error, and 0-1 loss does not
decompose additively into bias and variance. For a binary outcome this
function therefore decomposes the squared error of the predicted
probability of the positive class, which does. true_values is then the
true probability, not the class. Multiclass is not supported.
EDG
Geman S, Bienenstock E, Doursat R (1992). Neural Networks and the Bias/Variance Dilemma. Neural Computation, 4(1), 1-58. doi:10.1162/neco.1992.4.1.1
set.seed(2026) n <- 200L features <- data.frame(a = rnorm(n), b = rnorm(n)) dat <- data.frame(features, y = 2 * features[["a"]] + rnorm(n)) bv <- bias_variance( dat, hyperparameters = setup_CART(), resampler_config = setup_StratBoot(n_resamples = 10L), verbosity = 0L ) bvset.seed(2026) n <- 200L features <- data.frame(a = rnorm(n), b = rnorm(n)) dat <- data.frame(features, y = 2 * features[["a"]] + rnorm(n)) bv <- bias_variance( dat, hyperparameters = setup_CART(), resampler_config = setup_StratBoot(n_resamples = 10L), verbosity = 0L ) bv
Classification & ClassificationRes ModelsGeneric function to calibrate binary classification models.
calibrate( x, hyperparameters = NULL, execution_config = NULL, verbosity = 1L, ... )calibrate( x, hyperparameters = NULL, execution_config = NULL, verbosity = 1L, ... )
x |
|
hyperparameters |
Optional |
execution_config |
Optional |
verbosity |
Integer: Verbosity level. |
... |
Additional arguments passed to specific methods. |
The goal of calibration is to adjust the predicted probabilities of a binary classification model so that they better reflect the true probabilities (i.e. empirical risk) of the positive class.
Calibrated model object.
For Classification objects:
predicted_probabilities: Numeric vector of the positive class's
predicted probabilities, one per case
true_labels: Factor of true class labels
For ClassificationRes objects:
resampler_config: ResamplerConfig object for calibration training
train_verbosity: Integer controlling calibration model training output
A calibration map must be monotonic non-decreasing. A map that reorders
scores changes the ranking of the predictions, and so changes AUC; a
non-decreasing one cannot. available_calibration lists the algorithms
that carry that guarantee. Any other Hyperparameters object is accepted
and trained like any other model, but nothing then constrains the map.
setup_Isotonic (the default) fits isotonic regression. The map is a step
function, so it merges nearby scores into ties, which moves AUC slightly
in either direction. Fitted probabilities are held at least 1 / (2 * n)
away from 0 and 1, n being the number of calibration cases, so a block
of uniformly labelled cases does not assert certainty.
setup_MonotonicHAL fits a monotonic Highly Adaptive Lasso on the logit
scale. At its default smoothness_orders = 1 the map is continuous and
strictly increasing, so it preserves AUC exactly – but the constraint
that achieves this also makes the map convex on the logit scale, which
costs accuracy whenever the correction needed is concave.
smoothness_orders = 0 with penalized = FALSE lifts that restriction,
at the cost of ties and a markedly slower fit.
Isotonic is the default because no monotonic lasso configuration is
uniformly better and every one of them is several times slower.
data-raw/benchmark_calibrators.R reproduces the comparison.
The calibrator that ran is recorded on the returned object's @calibrator
property, is shown by print(), and is serialized by to_json().
EDG
# --- Calibrate Classification --- dat <- iris[51:150, ] res <- resample(dat) dat[["Species"]] <- factor(dat[["Species"]]) dat_train <- dat[res[[1]], ] dat_test <- dat[-res[[1]], ] # Train GLM on a training/test split mod_c_glm <- train( x = dat_train, dat_test = dat_test, hyperparameters = setup_GLM() ) # Calibrate the `Classification` by defining `predicted_probabilities` and `true_labels`, # in this case using the training data, but it could be a separate calibration dataset. mod_c_glm_cal <- calibrate( mod_c_glm, predicted_probabilities = mod_c_glm[["predicted_prob_training"]][, 1L], true_labels = mod_c_glm[["y_training"]] ) mod_c_glm_cal # --- Calibrate ClassificationRes --- # Train GLM with cross-validation resmod_c_glm <- train( x = dat, hyperparameters = setup_GLM(), outer_resampling_config = setup_KFold(n_resamples = 3L) ) # Calibrate the `ClassificationRes` using the same resampling configuration as used for training. resmod_c_glm_cal <- calibrate(resmod_c_glm) resmod_c_glm_cal# --- Calibrate Classification --- dat <- iris[51:150, ] res <- resample(dat) dat[["Species"]] <- factor(dat[["Species"]]) dat_train <- dat[res[[1]], ] dat_test <- dat[-res[[1]], ] # Train GLM on a training/test split mod_c_glm <- train( x = dat_train, dat_test = dat_test, hyperparameters = setup_GLM() ) # Calibrate the `Classification` by defining `predicted_probabilities` and `true_labels`, # in this case using the training data, but it could be a separate calibration dataset. mod_c_glm_cal <- calibrate( mod_c_glm, predicted_probabilities = mod_c_glm[["predicted_prob_training"]][, 1L], true_labels = mod_c_glm[["y_training"]] ) mod_c_glm_cal # --- Calibrate ClassificationRes --- # Train GLM with cross-validation resmod_c_glm <- train( x = dat, hyperparameters = setup_GLM(), outer_resampling_config = setup_KFold(n_resamples = 3L) ) # Calibrate the `ClassificationRes` using the same resampling configuration as used for training. resmod_c_glm_cal <- calibrate(resmod_c_glm) resmod_c_glm_cal
Check Data
check_data( x, name = NULL, get_duplicates = TRUE, get_na_case_pct = FALSE, get_na_feature_pct = FALSE )check_data( x, name = NULL, get_duplicates = TRUE, get_na_case_pct = FALSE, get_na_feature_pct = FALSE )
x |
tabular data: Input to be checked. |
name |
Character: Name of dataset. |
get_duplicates |
Logical: If TRUE, count duplicate cases. If FALSE,
|
get_na_case_pct |
Logical: If TRUE, calculate percent of NA values per case. |
get_na_feature_pct |
Logical: If TRUE, calculate percent of NA values per feature. |
CheckData object.
EDG
n <- 1000 x <- rnormmat(n, 50, return_df = TRUE) x[["char1"]] <- sample(letters, n, TRUE) x[["char2"]] <- sample(letters, n, TRUE) x[["fct"]] <- factor(sample(letters, n, TRUE)) x <- rbind(x, x[1, ]) x[["const"]] <- 99L x[sample(nrow(x), 20), 3] <- NA x[sample(nrow(x), 20), 10] <- NA x[["fct"]][30:35] <- NA check_data(x)n <- 1000 x <- rnormmat(n, 50, return_df = TRUE) x[["char1"]] <- sample(letters, n, TRUE) x[["char2"]] <- sample(letters, n, TRUE) x[["fct"]] <- factor(sample(letters, n, TRUE)) x <- rbind(x, x[1, ]) x[["const"]] <- 99L x[sample(nrow(x), 20), 3] <- NA x[sample(nrow(x), 20), 10] <- NA x[["fct"]][30:35] <- NA check_data(x)
Calculate class imbalance as given by:
where is the number of classes, and is the number of
instances of class
class_imbalance(x)class_imbalance(x)
x |
Vector, factor: Outcome. |
Numeric.
EDG
# iris is perfectly balanced class_imbalance(iris[["Species"]]) # Simulate imbalanced outcome x <- factor(sample(c("A", "B"), size = 500L, replace = TRUE, prob = c(0.9, 0.1))) class_imbalance(x)# iris is perfectly balanced class_imbalance(iris[["Species"]]) # Simulate imbalanced outcome x <- factor(sample(c("A", "B"), size = 500L, replace = TRUE, prob = c(0.9, 0.1))) class_imbalance(x)
Classification Metrics
classification_metrics( true_labels, predicted_labels, predicted_prob = NULL, binclasspos = 2L, calc_auc = TRUE, calc_brier = TRUE, auc_method = "lightAUC", sample = NULL, verbosity = 0L )classification_metrics( true_labels, predicted_labels, predicted_prob = NULL, binclasspos = 2L, calc_auc = TRUE, calc_brier = TRUE, auc_method = "lightAUC", sample = NULL, verbosity = 0L )
true_labels |
Factor: True labels. |
predicted_labels |
Factor: predicted values. |
predicted_prob |
Optional Numeric vector or matrix [0, 1]: Predicted probabilities, one column per class. A single column is the positive class's probability and enables the probability-based metrics (AUC, Brier score); a multiclass matrix has no single score per case, so those are not computed. |
binclasspos |
Integer: Factor level position of the positive class in binary classification. |
calc_auc |
Logical: If TRUE, calculate AUC. May be slow in very large datasets. |
calc_brier |
Logical: If TRUE, calculate Brier score. |
auc_method |
Character: "lightAUC", "pROC", "ROCR". |
sample |
Optional Character {"Training", "Validation", "Test", "Calibrated Training", "Calibrated Validation", "Calibrated Test"}: Sample the metrics describe. |
verbosity |
Integer: Verbosity level. |
Note that auc_method = "pROC" is the only one that will output an AUC even if one or more predicted probabilities are NA.
ClassificationMetrics object.
EDG
# Assume positive class is "b" true_labels <- factor(c("a", "a", "a", "b", "b", "b", "b", "b", "b", "b")) predicted_labels <- factor(c("a", "b", "a", "b", "b", "a", "b", "b", "b", "a")) predicted_prob <- c(0.3, 0.55, 0.45, 0.75, 0.57, 0.3, 0.8, 0.63, 0.62, 0.39) classification_metrics(true_labels, predicted_labels, predicted_prob) classification_metrics(true_labels, predicted_labels, 1 - predicted_prob, binclasspos = 1L)# Assume positive class is "b" true_labels <- factor(c("a", "a", "a", "b", "b", "b", "b", "b", "b", "b")) predicted_labels <- factor(c("a", "b", "a", "b", "b", "a", "b", "b", "b", "a")) predicted_prob <- c(0.3, 0.55, 0.45, 0.75, 0.57, 0.3, 0.8, 0.63, 0.62, 0.39) classification_metrics(true_labels, predicted_labels, predicted_prob) classification_metrics(true_labels, predicted_labels, 1 - predicted_prob, binclasspos = 1L)
Perform clustering on the rows (usually cases) of a dataset.
cluster( x, algorithm = "KMeans", config = NULL, execution_config = setup_FutureExecution(), outdir = NULL, verbosity = 1L )cluster( x, algorithm = "KMeans", config = NULL, execution_config = setup_FutureExecution(), outdir = NULL, verbosity = 1L )
x |
Matrix, data.frame, or |
algorithm |
Character: Clustering algorithm. Not needed when |
config |
|
execution_config |
|
outdir |
Character, optional: Output directory. If not NULL, the returned
|
verbosity |
Integer: Verbosity level. |
See docs.rtemis.org/r for detailed documentation.
Clustering object.
EDG
iris_km <- cluster(exc(iris, "Species"), algorithm = "KMeans")iris_km <- cluster(exc(iris, "Species"), algorithm = "KMeans")
A prediction interval for a regression or a set of labels for a
classification, covering the truth with probability at least 1 - alpha
under exchangeability alone – in finite samples, for any model, including a
misspecified one.
conformal(x, newdata, calibration = NULL, config = NULL, verbosity = 1L, ...)conformal(x, newdata, calibration = NULL, config = NULL, verbosity = 1L, ...)
x |
|
newdata |
tabular data: Cases to bound. Predictors only, in training
order, as |
calibration |
Optional tabular data: Calibration cases, predictors and
outcome, in the shape |
config |
Optional |
verbosity |
Integer: Verbosity level. |
... |
Additional arguments passed to methods. |
The guarantee is marginal. P(Y in C(X)) >= 1 - alpha averages over the
draw of both the calibration set and the test case. It is not conditional:
90% marginal coverage is compatible with 99% coverage on easy cases and 60%
on a hard subgroup, and averaged over everyone is not the same as guaranteed
for anyone. It is also void, silently, under distribution shift –
exchangeability is the whole assumption.
Width is the quality measure; coverage is the correctness check. A
useless model attains valid coverage by returning intervals wide enough to be
uninformative, so read the two together. The region reports its widths (or
set sizes); conformal_metrics() scores coverage against outcomes the region
did not see.
Which data calibrates. calibration is a tabular dataset holding the
predictors and the outcome, in training shape. Left NULL, a model trained
with dat_test calibrates on that split, whose residuals it already stores:
train() never fits, tunes or early-stops on dat_test. Nothing else is
assumed clean – a validation split may have driven early stopping, and a
model chosen by its test metric has used that split for selection, which
nothing in the object records.
Conformal calibration is unrelated to the probability calibration calibrate performs, and the two must not share rows. Where rtemis can see that they do, it refuses.
Which method. config NULL takes the method the object supports: split
conformal for a Supervised, CV+ for a SupervisedRes. See
setup_SplitConformal, setup_CVPlus and setup_CQR.
PredictionInterval object for a regression, PredictionSet for a
classification.
EDG
x <- data.frame(age = rnorm(300), bmi = rnorm(300)) x[["y"]] <- x[["age"]] * 2 + rnorm(300, sd = 0.3) # Three splits: one fits, one calibrates, one scores what the other two did. mod <- train( x[1:200, ], dat_test = x[201:250, ], hyperparameters = setup_GLM(), verbosity = 0L ) # The stored test split calibrates; 90% intervals for five fresh cases. region <- conformal(mod, x[1:5, c("age", "bmi")], verbosity = 0L) region region@lower region@upper # Coverage, against outcomes nothing in the pipeline has seen. held_out <- x[251:300, ] conformal_metrics( conformal(mod, held_out[, c("age", "bmi")], verbosity = 0L), held_out[["y"]] )x <- data.frame(age = rnorm(300), bmi = rnorm(300)) x[["y"]] <- x[["age"]] * 2 + rnorm(300, sd = 0.3) # Three splits: one fits, one calibrates, one scores what the other two did. mod <- train( x[1:200, ], dat_test = x[201:250, ], hyperparameters = setup_GLM(), verbosity = 0L ) # The stored test split calibrates; 90% intervals for five fresh cases. region <- conformal(mod, x[1:5, c("age", "bmi")], verbosity = 0L) region region@lower region@upper # Coverage, against outcomes nothing in the pipeline has seen. held_out <- x[251:300, ] conformal_metrics( conformal(mod, held_out[, c("age", "bmi")], verbosity = 0L), held_out[["y"]] )
Empirical coverage and region size for a PredictionRegion, against the
outcomes of the cases it bounds.
conformal_metrics(region, true_outcome)conformal_metrics(region, true_outcome)
region |
|
true_outcome |
Numeric or Factor: The outcomes of the cases |
Coverage on the calibration data is not a check. The threshold is chosen
as the 1 - alpha empirical quantile of the calibration scores, so coverage
measured back on those same cases is 1 - alpha by construction. Score
against outcomes nothing in the pipeline has seen, or the number means
nothing.
Read coverage and size together. A model with no signal attains valid coverage by returning intervals wide enough to be useless, so coverage alone cannot separate a good model from a wide one. Width – or set size, and the rate of singleton and empty sets – is the part that carries information about the model.
Coverage is a proportion over the cases supplied, so it carries the Monte Carlo error of that sample: 100 cases at a nominal 90% have a standard error near 3 points, and a single run landing at 87% is not evidence of a broken guarantee.
One-row data.frame. coverage and n for either shape, plus
mean_width and median_width for an interval, or mean_set_size,
singleton_rate and empty_rate for a set.
EDG
x <- data.frame(age = rnorm(300), bmi = rnorm(300)) x[["y"]] <- x[["age"]] * 2 + rnorm(300, sd = 0.3) mod <- train( x[1:200, ], dat_test = x[201:250, ], hyperparameters = setup_GLM(), verbosity = 0L ) held_out <- x[251:300, ] region <- conformal(mod, held_out[, c("age", "bmi")], verbosity = 0L) conformal_metrics(region, held_out[["y"]])x <- data.frame(age = rnorm(300), bmi = rnorm(300)) x[["y"]] <- x[["age"]] * 2 + rnorm(300, sd = 0.3) mod <- train( x[1:200, ], dat_test = x[201:250, ], hyperparameters = setup_GLM(), verbosity = 0L ) held_out <- x[251:300, ] region <- conformal(mod, held_out[, c("age", "bmi")], verbosity = 0L) conformal_metrics(region, held_out[["y"]])
Computes a DataFingerprint: a content hash of x plus the structural facts
(dimensions, column names) that make a mismatch between two runs diagnosable.
Used to record which data a run actually used, so undocumented drift between
experiments is visible.
data_fingerprint(x, method = "object", algorithm = "sha256", source = NULL)data_fingerprint(x, method = "object", algorithm = "sha256", source = NULL)
x |
tabular data: The dataset. Required for every method, so that dimensions and column names are always recorded, even when hashing file bytes. |
method |
Character {"file", "object", "table"}: What to hash. "object"
hashes the serialized R object (cheap, R-only). "file" hashes the raw bytes
of |
algorithm |
Character {"sha256", "sha512", "sha384", "sha224", "sha3-256", "sha3-512", "blake2b", "blake2s", "sha1", "md5"}: Hash algorithm. "blake2b" and "blake2s" are the fast options; "sha1" and "md5" are for interoperability with systems that record those. |
source |
Optional Character: Path |
DataFingerprint object.
EDG
fp <- data_fingerprint(iris) fp # A logically identical table in a different R container hashes differently # under "object", which is what `@data_structure` records. FALSE: data_fingerprint(iris)@hash == data_fingerprint(data.table::as.data.table(iris))@hashfp <- data_fingerprint(iris) fp # A logically identical table in a different R container hashes differently # under "object", which is what `@data_structure` records. FALSE: data_fingerprint(iris)@hash == data_fingerprint(data.table::as.data.table(iris))@hash
Measures the facts validate_config checks a config against: dimensions, column types, distinct and missing counts per column, level counts for low-cardinality categorical columns, and the number of complete cases.
data_profile(x, n_duplicates = TRUE, fingerprint = FALSE)data_profile(x, n_duplicates = TRUE, fingerprint = FALSE)
x |
tabular data: The dataset. |
n_duplicates |
Logical: If TRUE, count rows that repeat an earlier row. The one whole-table operation here; FALSE leaves the field NULL. |
fingerprint |
Logical: If TRUE, record a data_fingerprint of |
One pass per column and no copy of the data, so profiling is cheap enough to do per validation.
DataProfile object.
EDG
p <- data_profile(iris) p@columns p@level_countsp <- data_profile(iris) p@columns p@level_counts
Collect a table read with ddb_data(x, collect = FALSE)
ddb_collect(sql, progress = TRUE, returnobj = c("data.frame", "data.table"))ddb_collect(sql, progress = TRUE, returnobj = c("data.frame", "data.table"))
sql |
Character: DuckDB SQL query, usually output of
ddb_data with |
progress |
Logical: If TRUE, show progress bar |
returnobj |
Character: data.frame or data.table: class of object to return |
data.frame or data.table.
EDG
## Not run: # Requires local CSV file; replace with your own path sql <- ddb_data("/Data/iris.csv", collect = FALSE) ir <- ddb_collect(sql) ## End(Not run)## Not run: # Requires local CSV file; replace with your own path sql <- ddb_data("/Data/iris.csv", collect = FALSE) ir <- ddb_collect(sql) ## End(Not run)
Lazy-read a CSV file, optionally: filter rows, remove duplicates, clean column names, convert character to factor, collect.
ddb_data( filename, datadir = NULL, sep = ",", header = TRUE, quotechar = "", ignore_errors = TRUE, make_unique = TRUE, select_columns = NULL, filter_column = NULL, filter_vals = NULL, character2factor = FALSE, collect = TRUE, progress = TRUE, returnobj = c("data.table", "data.frame"), data.table.key = NULL, clean_colnames = TRUE, verbosity = 1L )ddb_data( filename, datadir = NULL, sep = ",", header = TRUE, quotechar = "", ignore_errors = TRUE, make_unique = TRUE, select_columns = NULL, filter_column = NULL, filter_vals = NULL, character2factor = FALSE, collect = TRUE, progress = TRUE, returnobj = c("data.table", "data.frame"), data.table.key = NULL, clean_colnames = TRUE, verbosity = 1L )
filename |
Character: file name; either full path or just the file name,
if |
datadir |
Character: Optional path if |
sep |
Character: Field delimiter/separator. |
header |
Logical: If TRUE, first line will be read as column names. |
quotechar |
Character: Quote character. |
ignore_errors |
Logical: If TRUE, ignore parsing errors (sometimes it's either this or no data, so). |
make_unique |
Logical: If TRUE, keep only unique rows. |
select_columns |
Character vector: Column names to select. |
filter_column |
Character: Name of column to filter on, e.g. "ID". |
filter_vals |
Numeric or Character vector: Values in |
character2factor |
Logical: If TRUE, convert character columns to factors. |
collect |
Logical: If TRUE, collect data and return structure class
as defined by |
progress |
Logical: If TRUE, print progress (no indication this works). |
returnobj |
Character: "data.frame" or "data.table" object class to
return. If "data.table", data.frame object returned from
|
data.table.key |
Character: If set, this corresponds to a column name in the dataset. This column will be set as key in the data.table output. |
clean_colnames |
Logical: If TRUE, clean colnames with clean_colnames. |
verbosity |
Integer: Verbosity level. |
data.frame or data.table if collect is TRUE, otherwise a character with the SQL query
EDG
## Not run: # Requires local CSV file; replace with your own path ir <- ddb_data("/Data/massive_dataset.csv", filter_column = "ID", filter_vals = 8001:9999 ) ## End(Not run)## Not run: # Requires local CSV file; replace with your own path ir <- ddb_data("/Data/massive_dataset.csv", filter_column = "ID", filter_vals = 8001:9999 ) ## End(Not run)
Perform linear or non-linear decomposition of numeric data.
decomp( x, algorithm = "ICA", config = NULL, execution_config = setup_FutureExecution(), outdir = NULL, verbosity = 1L )decomp( x, algorithm = "ICA", config = NULL, execution_config = setup_FutureExecution(), outdir = NULL, verbosity = 1L )
x |
Matrix, data frame, or |
algorithm |
Character: Decomposition algorithm. Not needed when |
config |
DecompositionConfig: Algorithm-specific config. Its |
execution_config |
|
outdir |
Character, optional: Output directory. If not NULL, the returned
|
verbosity |
Integer: Verbosity level. |
See docs.rtemis.org/r for detailed documentation.
Decomposition object.
EDG
iris_pca <- decomp(exc(iris, "Species"), algorithm = "PCA")iris_pca <- decomp(exc(iris, "Species"), algorithm = "PCA")
Quantify a fitted decomposition: how much of the data its components reconstruct, how redundant they are, and – given data the fit never saw – whether it generalizes.
decomp_metrics( decom, x, new_data = NULL, execution_config = NULL, verbosity = 1L )decomp_metrics( decom, x, new_data = NULL, execution_config = NULL, verbosity = 1L )
decom |
|
x |
Tabular data (data.frame, data.table, or tibble): The data |
new_data |
Optional tabular data: Data the fit never saw. Its columns
must match those |
execution_config |
Optional |
verbosity |
Integer: Verbosity level. |
Which metrics are computed follows from the algorithm's traits; see
applicable_metrics. A metric its algorithm cannot support is NA.
The unprefixed metrics describe the fitted data, so x must be that data:
they are computed against the components decom already holds. A different
number of cases is an error, and x failing to match
decom@data_fingerprint is reported without raising, since scoring a fit
against an altered copy of its training data is a legitimate thing to do.
decomp() already stores this on its result for the data it was fitted on,
so calling this without new_data recomputes what decom@metrics holds. The
reason to call it is new_data: reconstruction_gap is the difference
between out-of-sample and in-sample relative reconstruction error, and it is
the signal that a decomposition has fitted its training cases rather than
their structure.
Reconstruction is measured in the units of the data as it was passed to
decomp(), so the numbers are comparable across algorithms and across
configurations of one algorithm. One caveat: ICA with row_norm = TRUE
standardizes each case across features, and inverting that needs each case's
own mean and standard deviation, taken from the data being reconstructed.
Its reconstruction therefore draws on information the components do not
carry, and its error is not comparable with an algorithm that reconstructs
from components alone.
DecompositionMetrics object.
EDG
x <- exc(iris, "Species") iris_pca <- decomp(x, algorithm = "PCA", verbosity = 0L) decomp_metrics(iris_pca, x, verbosity = 0L)x <- exc(iris, "Species") iris_pca <- decomp(x, algorithm = "PCA", verbosity = 0L) decomp_metrics(iris_pca, x, verbosity = 0L)
Machine-readable properties of each decomposition algorithm available to decomp: whether the map is linear, whether it can be applied to new data, whether it inverts, and what its objective preserves.
decomposition_traits(algorithm = NULL)decomposition_traits(algorithm = NULL)
algorithm |
Optional Character: Name of a decomposition algorithm,
matched case-insensitively. |
The columns:
nameThe name used by setup_<name>() and decomp(algorithm =).
descriptionFull name of the algorithm.
linearThe map from input space to component space is linear.
can_applyA fitted result can be applied to new data with apply_decomp.
invertibleThere is an inverse map from component space back to input space, so reconstruction error is defined.
orthogonalComponents are mutually orthogonal.
orderedComponents come in a meaningful order, so "the first j" is well-defined.
deterministicThe same input and configuration give the same result without setting a seed.
preservesWhat the objective preserves: "variance",
"global", "local", or "reconstruction".
nonnegRequires non-negative input and produces non-negative factors.
threadedThe fit runs on as many threads as the execution
config gives the algorithm (n_workers_algorithm, or the worker count).
Like can_apply, it states what rtemis implements.
packagePackage supplying the backend implementation.
can_apply states what rtemis implements, not what is mathematically
possible. Parametric tSNE exists and Isomap admits a Nystrom-style
out-of-sample extension; neither is implemented here, so both are FALSE.
The column's contract is that apply_decomp on a fitted result of this
algorithm returns components.
data.frame: One row per algorithm, one column per trait.
EDG
decomposition_traits() decomposition_traits("PCA") # Which algorithms support out-of-sample projection? decomposition_traits()[["name"]][decomposition_traits()[["can_apply"]]]decomposition_traits() decomposition_traits("PCA") # Which algorithms support out-of-sample projection? decomposition_traits()[["name"]][decomposition_traits()[["can_apply"]]]
Describe object
describe(x, verbosity = 1L, ...)describe(x, verbosity = 1L, ...)
x |
R object to describe. See method documentation for supported classes. |
verbosity |
Integer: Verbosity level. |
... |
Additional arguments passed to methods. |
Extra arguments for factor method:
max_n: Integer: Return counts for up to this many levels.
return_ordered: Logical: If TRUE, return levels ordered by count, otherwise return in level order.
verbosity: Integer: Verbosity level.
Character, invisibly.
EDG
# --- For `Supervised` objects --- species_cart <- train(iris, hyperparameters = setup_CART()) describe(species_cart) # --- For `SupervisedRes` objects --- mod <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(n_resamples = 3L) ) describe(mod) # --- For factors --- # Small number of levels describe(iris[["Species"]]) # Large number of levels: show top n by count x <- factor(sample(letters, 1000, TRUE)) describe(x) describe(x, 3) describe(x, 3, return_ordered = FALSE)# --- For `Supervised` objects --- species_cart <- train(iris, hyperparameters = setup_CART()) describe(species_cart) # --- For `SupervisedRes` objects --- mod <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(n_resamples = 3L) ) describe(mod) # --- For factors --- # Small number of levels describe(iris[["Species"]]) # Large number of levels: show top n by count x <- factor(sample(letters, 1000, TRUE)) describe(x) describe(x, 3) describe(x, 3, return_ordered = FALSE)
Move data frame column
df_movecolumn(x, colname, to = ncol(x))df_movecolumn(x, colname, to = ncol(x))
x |
data.frame. |
colname |
Character: Name of column you want to move. |
to |
Integer: Which column position to move the vector to. |
data.frame
EDG
ir <- df_movecolumn(iris, colname = "Species", to = 1L)ir <- df_movecolumn(iris, colname = "Species", to = 1L)
Get number of unique values per features
df_nunique_perfeat(x, excludeNA = FALSE)df_nunique_perfeat(x, excludeNA = FALSE)
x |
matrix or data frame input |
excludeNA |
Logical: If TRUE, exclude NA values from unique count. |
Vector, integer of length NCOL(x) with number of unique
values per column/feature
EDG
df_nunique_perfeat(iris)df_nunique_perfeat(iris)
Draw a fitted LINAD model as an interactive tree: the partition as a hierarchy, each node's value on its label, and each node's linear coefficients in a table on hover.
draw_linad( x, n_leaves = NULL, top = 15L, sort_coefs = TRUE, direction = "UD", node_width = 180L, node_gap = 16L, level_separation = NULL, font_size = 14L, node_labels = TRUE, show_ncases = TRUE, show_node_value = TRUE, show_changes = TRUE, lo_col = sign_colors()[["negative"]], mid_col = NULL, hi_col = sign_colors()[["positive"]], root_col = NULL, node_col = NULL, leaf_col = NULL, hover_col = NULL, height = "600px", theme = NULL, verbosity = 1L )draw_linad( x, n_leaves = NULL, top = 15L, sort_coefs = TRUE, direction = "UD", node_width = 180L, node_gap = 16L, level_separation = NULL, font_size = 14L, node_labels = TRUE, show_ncases = TRUE, show_node_value = TRUE, show_changes = TRUE, lo_col = sign_colors()[["negative"]], mid_col = NULL, hi_col = sign_colors()[["positive"]], root_col = NULL, node_col = NULL, leaf_col = NULL, hover_col = NULL, height = "600px", theme = NULL, verbosity = 1L )
x |
|
n_leaves |
Optional Integer: Draw the tree at this size. NULL draws the size selected at training. |
top |
Optional Integer: Show this many coefficients per node, largest in absolute value first. NULL shows every one, which on a wide model is neither readable nor quick to render. |
sort_coefs |
Logical: If TRUE, order each table by absolute coefficient. |
direction |
Character {"UD", "DU", "LR", "RL"}: Tree direction. |
node_width |
Integer: Largest node width in pixels. Labels wrap to stay within it, which is what keeps a long feature name from widening a node past the space the layout reserves for it. |
node_gap |
Integer: Clear pixels to leave between two boxes on the same level. Separation is computed per pair from the two nodes' own widths, so a narrow node sits close to its neighbor. |
level_separation |
Optional Integer: Pixels between levels. |
font_size |
Integer: Label font size in pixels. |
node_labels |
Logical: If TRUE, label nodes with their rule. |
show_ncases |
Logical: If TRUE, include the case count in node labels. |
show_node_value |
Logical: If TRUE, include the node's own value in its label. |
show_changes |
Logical: If TRUE, mark each coefficient in the node's table with where it came from: a global effect, shared by every leaf, is marked with an identity sign, and one this node changed with a delta. A term with neither was inherited from the parent unchanged. The root carries no marks: it has no parent to differ from. |
lo_col |
Character: Color for the most negative coefficient. Defaults
to the package-wide negative color, the same one |
mid_col |
Optional Character: Color at zero. NULL uses the coefficient table's own background, so a coefficient of no consequence shows as no cell at all. |
hi_col |
Character: Color for the most positive coefficient. Defaults to the package-wide positive color. |
root_col |
Optional Character: Root node color. NULL follows the theme. |
node_col |
Optional Character: Internal node color. NULL follows the theme. |
leaf_col |
Optional Character: Terminal node color. NULL follows the theme. Kept off the two ends of the coefficient scale, so a hue in this plot means a coefficient's sign and nothing else. |
hover_col |
Optional Character: Border color marking the node the coefficient table belongs to. NULL uses the theme foreground. |
height |
Character: CSS height, as a length: a percentage of a container with no height of its own collapses. |
theme |
Optional rtemis.draw::Theme: Its background and text colors
set the canvas and the foreground. Node fills, the coefficient table and the
hover marker all follow them, chosen by the background's luminance so that a
custom theme is handled too. NULL uses |
verbosity |
Integer: If > 0, print messages. |
The coefficient tables are the point. A LINAD leaf's coefficients are the accumulated sum along its path, so the same feature can carry a different slope in each region of the data – and sometimes a different sign. That is the model's central interpretive claim, and it is only visible by comparing the table at one node against the table at another. The color scale is therefore diverging and centered on zero, and computed once across every table, so a sign change reads as a color flip.
Each node's label carries node_value, what the tree alone predicts
there, while the table on hover carries what the linear model adds. The
two are separate quantities in a fitted LINAD, so the plot shows them
separately: with node_model = "constant" the tables are empty of slopes and
the node values are the entire model, which is what a plain decision tree
looks like.
The intercept is excluded from the color range. It is typically far larger than any slope and would compress every other coefficient into the middle of the scale.
This is the reference implementation for the LINAD tree plot, built on
visNetwork because a tooltip carrying a real HTML table needs a backend
whose tooltip is an HTML element. Plotly, which every other draw_* uses,
renders hover labels as SVG and cannot express a table at all.
visNetwork htmlwidget.
EDG
x <- data.frame(a = rnorm(300), b = rnorm(300)) x[["y"]] <- 2 * x[["a"]] + ifelse(x[["b"]] < 0, -3, 3) + rnorm(300) mod <- train(x, hyperparameters = setup_LINAD(max_leaves = 5L)) draw_linad(mod)x <- data.frame(a = rnorm(300), b = rnorm(300)) x[["y"]] <- 2 * x[["a"]] + ifelse(x[["b"]] < 0, -3, 3) + rnorm(300) mod <- train(x, hyperparameters = setup_LINAD(max_leaves = 5L)) draw_linad(mod)
Describe data.table
dt_describe(x, verbosity = 1L)dt_describe(x, verbosity = 1L)
x |
data.table: Input data.table. |
verbosity |
Integer: If > 0, print output to console. |
List with three data.tables: Numeric, Categorical, and Date.
EDG
library(data.table) origin <- as.POSIXct("2022-01-01 00:00:00", tz = "America/Los_Angeles") x <- data.table( ID = paste0("ID", 1:10), V1 = rnorm(10), V2 = rnorm(10, 20, 3), V1_datetime = as.POSIXct( seq( 1, 1e7, length.out = 10 ), origin = origin ), V2_datetime = as.POSIXct( seq( 1, 1e7, length.out = 10 ), origin = origin ), C1 = sample(c("alpha", "beta", "gamma"), 10, TRUE), F1 = factor(sample(c("delta", "epsilon", "zeta"), 10, TRUE)) )library(data.table) origin <- as.POSIXct("2022-01-01 00:00:00", tz = "America/Los_Angeles") x <- data.table( ID = paste0("ID", 1:10), V1 = rnorm(10), V2 = rnorm(10, 20, 3), V1_datetime = as.POSIXct( seq( 1, 1e7, length.out = 10 ), origin = origin ), V2_datetime = as.POSIXct( seq( 1, 1e7, length.out = 10 ), origin = origin ), C1 = sample(c("alpha", "beta", "gamma"), 10, TRUE), F1 = factor(sample(c("delta", "epsilon", "zeta"), 10, TRUE)) )
Will attempt to identify columns that should be numeric but are either character or factor by running inspect_type on each column.
dt_inspect_types(x, cols = NULL, verbosity = 1L)dt_inspect_types(x, cols = NULL, verbosity = 1L)
x |
data.table: Input data.table. |
cols |
Character vector: columns to inspect. |
verbosity |
Integer: Verbosity level. |
Character vector.
EDG
library(data.table) x <- data.table( id = 8001:8006, a = c("3", "5", "undefined", "21", "4", NA), b = c("mango", "banana", "tangerine", NA, "apple", "kiwi"), c = c(1, 2, 3, 4, 5, 6) ) dt_inspect_types(x)library(data.table) x <- data.table( id = 8001:8006, a = c("3", "5", "undefined", "21", "4", NA), b = c("mango", "banana", "tangerine", NA, "apple", "kiwi"), c = c(1, 2, 3, 4, 5, 6) ) dt_inspect_types(x)
Reshape a long format data.table using key-value pairs with
data.table::dcast
dt_keybin_reshape( x, id_name, key_name, positive = 1, negative = 0, xname = NULL, verbosity = 1L )dt_keybin_reshape( x, id_name, key_name, positive = 1, negative = 0, xname = NULL, verbosity = 1L )
x |
|
id_name |
Character: Name of column in |
key_name |
Character: Name of column in |
positive |
Numeric or Character: Used to fill id ~ key combination
present in the long format input |
negative |
Numeric or Character: Used to fill id ~ key combination
NOT present in the long format input |
xname |
Character: Name of |
verbosity |
Integer: Verbosity level. |
data.table in wide format.
EDG
library(data.table) x <- data.table( ID = rep(1:3, each = 2), Dx = c("A", "C", "B", "C", "D", "A") ) dt_keybin_reshape(x, id_name = "ID", key_name = "Dx")library(data.table) x <- data.table( ID = rep(1:3, each = 2), Dx = c("A", "C", "B", "C", "D", "A") ) dt_keybin_reshape(x, id_name = "ID", key_name = "Dx")
Merge data.tables
dt_merge( left, right, on = NULL, left_on = NULL, right_on = NULL, how = "left", left_name = NULL, right_name = NULL, left_suffix = NULL, right_suffix = NULL, verbosity = 1L, ... )dt_merge( left, right, on = NULL, left_on = NULL, right_on = NULL, how = "left", left_name = NULL, right_name = NULL, left_suffix = NULL, right_suffix = NULL, verbosity = 1L, ... )
left |
data.table |
right |
data.table |
on |
Character: Name of column to join on. |
left_on |
Character: Name of column on left table. |
right_on |
Character: Name of column on right table. |
how |
Character: Type of join: "inner", "left", "right", "outer". |
left_name |
Character: Name of left table. |
right_name |
Character: Name of right table. |
left_suffix |
Character: If provided, add this suffix to all left column names, excluding on/left_on. |
right_suffix |
Character: If provided, add this suffix to all right column names, excluding on/right_on. |
verbosity |
Integer: Verbosity level. |
... |
Additional arguments to be passed to |
Merged data.table.
EDG
library(data.table) xleft <- data.table(ID = 1:5, Alpha = letters[1:5]) xright <- data.table(ID = c(3, 4, 5, 6), Beta = LETTERS[3:6]) xlr_inner <- dt_merge(xleft, xright, on = "ID", how = "inner")library(data.table) xleft <- data.table(ID = 1:5, Alpha = letters[1:5]) xright <- data.table(ID = c(3, 4, 5, 6), Beta = LETTERS[3:6]) xlr_inner <- dt_merge(xleft, xright, on = "ID", how = "inner")
List column names by attribute
dt_names_by_attr(x, attribute, exact = TRUE, sorted = TRUE)dt_names_by_attr(x, attribute, exact = TRUE, sorted = TRUE)
x |
data.table: Input data.table. |
attribute |
Character: name of attribute. |
exact |
Logical: If TRUE, use exact matching. |
sorted |
Logical: If TRUE, sort the output. |
Character vector.
EDG
library(data.table) x <- data.table( id = 1:5, sbp = rnorm(5, 120, 15), dbp = rnorm(5, 80, 10), paO2 = rnorm(5, 90, 10), paCO2 = rnorm(5, 40, 5) ) setattr(x[["id"]], "source", "demographics") setattr(x[["sbp"]], "source", "outpatient") setattr(x[["dbp"]], "source", "outpatient") setattr(x[["paO2"]], "source", "icu") setattr(x[["paCO2"]], "source", "icu") dt_names_by_attr(x, "source", "outpatient")library(data.table) x <- data.table( id = 1:5, sbp = rnorm(5, 120, 15), dbp = rnorm(5, 80, 10), paO2 = rnorm(5, 90, 10), paCO2 = rnorm(5, 40, 5) ) setattr(x[["id"]], "source", "demographics") setattr(x[["sbp"]], "source", "outpatient") setattr(x[["dbp"]], "source", "outpatient") setattr(x[["paO2"]], "source", "icu") setattr(x[["paCO2"]], "source", "icu") dt_names_by_attr(x, "source", "outpatient")
Number of unique values per feature
dt_nunique_perfeat(x, excludeNA = FALSE, limit = 20L, verbosity = 1L)dt_nunique_perfeat(x, excludeNA = FALSE, limit = 20L, verbosity = 1L)
x |
data.table: Input data.table. |
excludeNA |
Logical: If TRUE, exclude NA values. |
limit |
Integer: Print up to this many features. Set to -1L to print all. |
verbosity |
Integer: If > 0, print output to console. |
Named integer vector of length NCOL(x) with number of unique values per column/feature, invisibly.
EDG
library(data.table) ir <- as.data.table(iris) dt_nunique_perfeat(ir)library(data.table) ir <- as.data.table(iris) dt_nunique_perfeat(ir)
Get N and percent match of values between two columns of two data.tables
dt_pctmatch(x, y, on = NULL, left_on = NULL, right_on = NULL, verbosity = 1L)dt_pctmatch(x, y, on = NULL, left_on = NULL, right_on = NULL, verbosity = 1L)
x |
data.table: First input data.table. |
y |
data.table: Second input data.table. |
on |
Integer or character: column to read in |
left_on |
Integer or character: column to read in |
right_on |
Integer or character: column to read in |
verbosity |
Integer: Verbosity level. |
list.
EDG
library(data.table) x <- data.table(ID = 1:5, Alpha = letters[1:5]) y <- data.table(ID = c(3, 4, 5, 6), Beta = LETTERS[3:6]) dt_pctmatch(x, y, on = "ID")library(data.table) x <- data.table(ID = 1:5, Alpha = letters[1:5]) y <- data.table(ID = c(3, 4, 5, 6), Beta = LETTERS[3:6]) dt_pctmatch(x, y, on = "ID")
Get percent of missing values from every column
dt_pctmissing(x, verbosity = 1L)dt_pctmissing(x, verbosity = 1L)
x |
data.frame or data.table |
verbosity |
Integer: Verbosity level. |
list
EDG
library(data.table) x <- data.table(a = c(1, 2, NA, 4), b = c(NA, NA, 3, 4), c = c("A", "B", "C", NA)) dt_pctmissing(x)library(data.table) x <- data.table(a = c(1, 2, NA, 4), b = c(NA, NA, 3, 4), c = c("A", "B", "C", NA)) dt_pctmissing(x)
This function inspects a data.table and attempts to identify columns that should be numeric but have been read in as character, and fixes their type in-place. This can happen when one or more fields contain non-numeric characters, for example.
dt_set_autotypes(x, cols = NULL, verbosity = 1L)dt_set_autotypes(x, cols = NULL, verbosity = 1L)
x |
data.table: Input data.table. Will be modified in-place, if needed. |
cols |
Character vector: columns to work on. If not defined, will work on all columns |
verbosity |
Integer: Verbosity level. |
data.table, invisibly.
EDG
library(data.table) x <- data.table( id = 8001:8006, a = c("3", "5", "undefined", "21", "4", NA), b = c("mango", "banana", "tangerine", NA, "apple", "kiwi"), c = c(1, 2, 3, 4, 5, 6) ) str(x) # ***in-place*** operation means no assignment is needed dt_set_autotypes(x) str(x) # Try excluding column 'a' from autotyping x <- data.table( id = 8001:8006, a = c("3", "5", "undefined", "21", "4", NA), b = c("mango", "banana", "tangerine", NA, "apple", "kiwi"), c = c(1, 2, 3, 4, 5, 6) ) str(x) # exclude column 'a' from autotyping dt_set_autotypes(x, cols = setdiff(names(x), "a")) str(x)library(data.table) x <- data.table( id = 8001:8006, a = c("3", "5", "undefined", "21", "4", NA), b = c("mango", "banana", "tangerine", NA, "apple", "kiwi"), c = c(1, 2, 3, 4, 5, 6) ) str(x) # ***in-place*** operation means no assignment is needed dt_set_autotypes(x) str(x) # Try excluding column 'a' from autotyping x <- data.table( id = 8001:8006, a = c("3", "5", "undefined", "21", "4", NA), b = c("mango", "banana", "tangerine", NA, "apple", "kiwi"), c = c(1, 2, 3, 4, 5, 6) ) str(x) # exclude column 'a' from autotyping dt_set_autotypes(x, cols = setdiff(names(x), "a")) str(x)
Clean column names and factor levels in-place
dt_set_clean_all(x, prefix_digits = NA)dt_set_clean_all(x, prefix_digits = NA)
x |
data.table: Input data.table. Will be modified in-place, if needed. |
prefix_digits |
Character: prefix to add to names beginning with a digit. Set to NA to skip |
Nothing, modifies x in-place.
EDG
library(data.table) x <- as.data.table(iris) levels(x[["Species"]]) <- c("setosa:iris", "versicolor$iris", "virginica iris") names(x) levels(x[["Species"]]) # ***in-place*** operation means no assignment is needed dt_set_clean_all(x) names(x) levels(x[["Species"]])library(data.table) x <- as.data.table(iris) levels(x[["Species"]]) <- c("setosa:iris", "versicolor$iris", "virginica iris") names(x) levels(x[["Species"]]) # ***in-place*** operation means no assignment is needed dt_set_clean_all(x) names(x) levels(x[["Species"]])
Finds all factors in a data.table and cleans factor levels to include only underscore symbols
dt_set_cleanfactorlevels(x, prefix_digits = NA)dt_set_cleanfactorlevels(x, prefix_digits = NA)
x |
data.table: Input data.table. Will be modified in-place. |
prefix_digits |
Character: If not NA, add this prefix to all factor levels that are numbers |
Nothing, modifies x in-place.
EDG
library(data.table) x <- as.data.table(iris) levels(x[["Species"]]) <- c("setosa:iris", "versicolor$iris", "virginica iris") levels(x[["Species"]]) dt_set_cleanfactorlevels(x) levels(x[["Species"]])library(data.table) x <- as.data.table(iris) levels(x[["Species"]]) <- c("setosa:iris", "versicolor$iris", "virginica iris") levels(x[["Species"]]) dt_set_cleanfactorlevels(x) levels(x[["Species"]])
Convert data.table logical columns to factors with custom labels in-place
dt_set_logical2factor( x, cols = NULL, labels = c("False", "True"), maintain_attributes = TRUE, fillNA = NULL )dt_set_logical2factor( x, cols = NULL, labels = c("False", "True"), maintain_attributes = TRUE, fillNA = NULL )
x |
data.table: Input data.table. Will be modified in-place. |
cols |
Optional Integer or character: columns to convert. If NULL, operates on all logical columns. |
labels |
Character: labels for factor levels. |
maintain_attributes |
Logical: If TRUE, maintain column attributes. |
fillNA |
Optional Character: If not NULL, fill NA values with this constant. |
data.table, invisibly.
EDG
library(data.table) x <- data.table(a = 1:5, b = c(TRUE, FALSE, FALSE, FALSE, TRUE)) x dt_set_logical2factor(x) x z <- data.table( alpha = 1:5, beta = c(TRUE, FALSE, TRUE, NA, TRUE), gamma = c(FALSE, FALSE, TRUE, FALSE, NA) ) # You can usee fillNA to fill NA values with a constant dt_set_logical2factor(z, cols = "beta", labels = c("No", "Yes"), fillNA = "No") z w <- data.table(mango = 1:5, banana = c(FALSE, FALSE, TRUE, TRUE, FALSE)) w dt_set_logical2factor(w, cols = 2, labels = c("Ugh", "Huh")) w # Column attributes are maintained by default: z <- data.table( alpha = 1:5, beta = c(TRUE, FALSE, TRUE, NA, TRUE), gamma = c(FALSE, FALSE, TRUE, FALSE, NA) ) for (i in seq_along(z)) setattr(z[[i]], "source", "Guava") str(z) dt_set_logical2factor(z, cols = "beta", labels = c("No", "Yes")) str(z)library(data.table) x <- data.table(a = 1:5, b = c(TRUE, FALSE, FALSE, FALSE, TRUE)) x dt_set_logical2factor(x) x z <- data.table( alpha = 1:5, beta = c(TRUE, FALSE, TRUE, NA, TRUE), gamma = c(FALSE, FALSE, TRUE, FALSE, NA) ) # You can usee fillNA to fill NA values with a constant dt_set_logical2factor(z, cols = "beta", labels = c("No", "Yes"), fillNA = "No") z w <- data.table(mango = 1:5, banana = c(FALSE, FALSE, TRUE, TRUE, FALSE)) w dt_set_logical2factor(w, cols = 2, labels = c("Ugh", "Huh")) w # Column attributes are maintained by default: z <- data.table( alpha = 1:5, beta = c(TRUE, FALSE, TRUE, NA, TRUE), gamma = c(FALSE, FALSE, TRUE, FALSE, NA) ) for (i in seq_along(z)) setattr(z[[i]], "source", "Guava") str(z) dt_set_logical2factor(z, cols = "beta", labels = c("No", "Yes")) str(z)
Convert data.table's factor to one-hot encoding in-place
dt_set_one_hot(x, xname = NULL, verbosity = 1L)dt_set_one_hot(x, xname = NULL, verbosity = 1L)
x |
data.table: Input data.table. Will be modified in-place. |
xname |
Character, optional: Dataset name. |
verbosity |
Integer: Verbosity level. |
The input, invisibly, after it has been modified in-place.
EDG
ir <- data.table::as.data.table(iris) # dt_set_one_hot operates ***in-place***; therefore no assignment is used: dt_set_one_hot(ir) irir <- data.table::as.data.table(iris) # dt_set_one_hot operates ***in-place***; therefore no assignment is used: dt_set_one_hot(ir) ir
Exclude columns by character or numeric vector.
exc(x, idx)exc(x, idx)
x |
tabular data. |
idx |
Character or numeric vector: Column names or indices to exclude. |
data.frame, tibble, or data.table.
EDG
exc(iris, "Species") |> head() exc(iris, c(1, 3)) |> head()exc(iris, "Species") |> head() exc(iris, c(1, 3)) |> head()
Per-case explanation of a fitted model: why it predicted what it did, for
each case in newdata. Where get_varimp() ranks features across a whole
model, this attributes one prediction – a feature can rank third overall and
be the entire reason for one case.
explain(x, newdata, background = NULL, config = NULL, verbosity = 1L, ...)explain(x, newdata, background = NULL, config = NULL, verbosity = 1L, ...)
x |
|
newdata |
tabular data: Cases to explain. Predictors only, in training
order, as |
background |
Optional tabular data: Cases the contributions are measured
against, in the same shape as |
config |
Optional |
verbosity |
Integer: Verbosity level. |
... |
Additional arguments passed to methods, such as |
background is what the contributions are measured against, and most
estimators cannot work without one. A contribution says how far a feature
moved this case's prediction away from E[f(x)], and that expectation is a
property of the background data, and the model does not store the data it
was trained on. Pass the training features, or a
representative sample of them. The exceptions are the estimators that take
their baseline from the model itself, such as the LightGBM family's; those
ignore it, and everything else aborts without it.
Two explanations of one model against different backgrounds are not comparable, and nothing in the returned numbers says so – which is why the result carries a fingerprint of the background it used.
config chooses the method, built by setup_SHAP:
setup_SHAP(perturbation = "conditional") picks the value function,
setup_SHAP(estimator = "kernel") overrides the estimator the algorithm
would otherwise get. explanation_methods reports which estimator applies to
which algorithm, whether it is exact, and why.
A SupervisedRes additionally takes type: "avg" (the default) averages
the resamples' explanations, which decomposes the averaged prediction
exactly, and "all" returns one explanation per resample.
The contributions plus the baseline reconstruct the prediction exactly, on
the scale they were computed on. For classification that scale is the
model's margin, not the probability stats::predict() returns:
probability is a nonlinear transform of the margin, so contributions do not
sum to it.
Read the result with shap_case for one case, shap_long across cases,
shap_by_level for the levels of a categorical, and get_varimp() for
mean(|phi|) per feature.
A SHAP value is not a causal effect. It attributes a prediction under the model's own logic; intervening on a feature in the world does not move the outcome by its attribution. Correlated features split credit between themselves, and how they split it depends on the value function – so a small attribution does not show a feature to be unimportant, and this is not a feature-selection criterion.
SHAP object, or a named list of them for a SupervisedRes with
type = "all".
EDG
x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) features <- x[, c("age", "bmi")] mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) # `background` is what the contributions are measured against. contributions <- explain( mod, features[1:5, ], background = features, verbosity = 0L ) contributions # Contributions plus the baseline reconstruct the prediction, exactly: rowSums(contributions@phi[["outcome"]]) + contributions@baseline[, 1L] predict(mod, features[1:5, ], verbosity = 0L) # One case, ordered the way a waterfall reads: shap_case(contributions, features[1:5, ], case = 1L) # Which features mattered across these cases: get_varimp(contributions) # `config` chooses the method; here, a subsampled background. explain( mod, features[1:5, ], background = features, config = setup_SHAP(background_n = 50L), verbosity = 0L )x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) features <- x[, c("age", "bmi")] mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) # `background` is what the contributions are measured against. contributions <- explain( mod, features[1:5, ], background = features, verbosity = 0L ) contributions # Contributions plus the baseline reconstruct the prediction, exactly: rowSums(contributions@phi[["outcome"]]) + contributions@baseline[, 1L] predict(mod, features[1:5, ], verbosity = 0L) # One case, ordered the way a waterfall reads: shap_case(contributions, features[1:5, ], case = 1L) # Which features mattered across these cases: get_varimp(contributions) # `config` chooses the method; here, a subsampled background. explain( mod, features[1:5, ], background = features, config = setup_SHAP(background_n = 50L), verbosity = 0L )
What explain does to a model fitted by each supervised algorithm: which
estimator setup_SHAP(estimator = "auto") resolves to, whether that answer
is exact, which value function it computes, and why.
explanation_methods(algorithm = NULL)explanation_methods(algorithm = NULL)
algorithm |
Optional Character: Name of a supervised algorithm, matched case-insensitively. NULL returns every algorithm. |
The columns:
nameThe algorithm, as named by setup_<name>().
estimatorThe estimator "auto" resolves to. "KernelSHAP" is
the model-agnostic fallback and applies to every algorithm; the others
are exact and algorithm-specific.
exactTRUE if the estimator returns Shapley values rather than an estimate of them, NA where that depends on the fitted model rather than on the algorithm – an ensemble whose meta-learner turned out to be linear, or a model that has one linear map for a regression or binary outcome but not for a multiclass one. An NA row explains what it did when asked, and refuses with a message naming the reason when it cannot.
perturbationThe value function computed when
setup_SHAP(perturbation = ) is left NULL.
rationaleWhy this estimator, in one line.
estimator = "kernel" is always available, so a row whose exact is FALSE
is saying that estimator = "exact" has nothing to offer for it – not that
the algorithm cannot be explained.
data.frame: One row per algorithm.
EDG
explanation_methods() explanation_methods("Ranger") # Which algorithms have an exact estimator? em <- explanation_methods() em[["name"]][!is.na(em[["exact"]]) & em[["exact"]]]explanation_methods() explanation_methods("Ranger") # Which algorithms have an exact estimator? em <- explanation_methods() em[["name"]][!is.na(em[["exact"]]) & em[["exact"]]]
Convert a tabular dataset to a matrix, one-hot encoding factors, if present.
feature_matrix(x)feature_matrix(x)
x |
tabular data: Input data to convert to a feature matrix. |
This is a convenience function that uses features(), preprocess(), as.matrix().
Matrix with features. Factors are one-hot encoded, if present.
EDG
# reorder columns so that we have a categorical feature x <- set_outcome(iris, "Sepal.Length") feature_matrix(x) |> head()# reorder columns so that we have a categorical feature x <- set_outcome(iris, "Sepal.Length") feature_matrix(x) |> head()
Returns all column names except the last one
feature_names(x)feature_names(x)
x |
tabular data. |
This applied to tabular datasets used for supervised learning in rtemis, where, by convention, the last column is the outcome variable and all other columns are features.
Character vector of feature names.
EDG
feature_names(iris)feature_names(iris)
Returns all columns except the last one.
features(x)features(x)
x |
tabular data: Input data to get features from. |
This can be applied to tabular datasets used for supervised learning in rtemis, where, by convention, the last column is the outcome variable and all other columns are features.
Object of the same class as the input, after removing the last column.
EDG
features(iris) |> head()features(iris) |> head()
Train one regression model on x and y with an algorithm named as a string,
then return its predictions for newdata, their standard errors when the
algorithm provides them, and the training R-squared.
fit_predict( x, y, newdata, algorithm, params = NULL, se = FALSE, verbosity = 0L )fit_predict( x, y, newdata, algorithm, params = NULL, se = FALSE, verbosity = 0L )
x |
data.frame: Features, one column per predictor. |
y |
Numeric: Outcome, one value per row of |
newdata |
data.frame: Features to predict, with the columns of |
algorithm |
Character: Supervised learning algorithm name, matched
case-insensitively, e.g. |
params |
Optional Named list: Arguments to the algorithm's setup
function, e.g. |
se |
Logical: If TRUE, compute standard errors of the fit for |
verbosity |
Integer: Verbosity level. |
This is the bridge behind fit = "<algorithm>" in rtemis.draw::draw_scatter(),
rtemis.draw::draw_fit() and rtemis.draw::draw_scatter3d(), which need a
fitted curve or surface from a name alone. For full control over training,
use train().
Named list: fitted (Numeric predictions for newdata), se
(Numeric standard errors, or NULL when se = FALSE or the algorithm has
none), rsq (Numeric training R-squared), and algorithm (Character
canonical algorithm name).
EDG
fit <- fit_predict( mtcars["wt"], mtcars[["mpg"]], newdata = data.frame(wt = c(2, 3, 4)), algorithm = "GLM", se = TRUE ) fit[["fitted"]] fit_predict( mtcars["wt"], mtcars[["mpg"]], newdata = data.frame(wt = c(2, 3, 4)), algorithm = "LINAD", params = list(max_leaves = 2) )[["fitted"]]fit <- fit_predict( mtcars["wt"], mtcars[["mpg"]], newdata = data.frame(wt = c(2, 3, 4)), algorithm = "GLM", se = TRUE ) fit[["fitted"]] fit_predict( mtcars["wt"], mtcars[["mpg"]], newdata = data.frame(wt = c(2, 3, 4)), algorithm = "LINAD", params = list(max_leaves = 2) )[["fitted"]]
Preprocessor's config with its learned values filled in@config holds what the user asked for and @values what preprocessing
learned, which keeps the input intact – but re-applying to new data needs
the two merged, and so does a run record, which must report the values
actually used. One merge, so the two cannot disagree.
fitted_config(preprocessor)fitted_config(preprocessor)
preprocessor |
|
The merged fields are settable inputs: supplying scale_centers makes
preprocess() use it instead of computing one. That is why the merge is
@values over @config and not the reverse – a learned value only fills a
slot the user left empty.
PreprocessorConfig with the learned values applied.
EDG
apply_preprocessor, setup_Preprocessor
iris_pre <- preprocess(iris, setup_Preprocessor(scale = TRUE, center = TRUE)) # The config as supplied carries no centers; the fitted one carries the # centers `preprocess()` computed. fitted_config(iris_pre)@scale_centersiris_pre <- preprocess(iris, setup_Preprocessor(scale = TRUE, center = TRUE)) # The config as supplied carries no centers; the fitted one carries the # centers `preprocess()` computed. fitted_config(iris_pre)@scale_centers
Get factor names
get_factor_names(x)get_factor_names(x)
x |
tabular data. |
This applied to tabular datasets used for supervised learning in rtemis, where, by convention, the last column is the outcome variable and all other columns are features.
Character vector of factor names.
EDG
get_factor_names(iris)get_factor_names(iris)
The loss recorded at every step of training, as data: one row per step, with the training and validation loss where the algorithm records them.
Returns NULL for an algorithm that records no learning curve, so it is safe to call on any model.
get_learning_curve(x, ...)get_learning_curve(x, ...)
x |
|
... |
Additional arguments passed to methods. |
data.frame with columns iteration, loss_training and
loss_validation, carrying attributes unit and selected; or NULL.
EDG
plot_learning, which draws it
dat <- set_outcome(iris[, 1:4], "Sepal.Length") mod <- train( dat[1:100, ], dat_validation = dat[101:150, ], hyperparameters = setup_LINAD(max_leaves = 12L) ) get_learning_curve(mod)dat <- set_outcome(iris[, 1:4], "Sepal.Length") mod <- train( dat[1:100, ], dat_validation = dat[101:150, ], hyperparameters = setup_LINAD(max_leaves = 12L) ) get_learning_curve(mod)
The performance metrics stored on a fitted model, clustering, or decomposition, for one sample.
get_metrics(x, sample = NULL, calibrated = FALSE)get_metrics(x, sample = NULL, calibrated = FALSE)
x |
|
sample |
Optional Character {"training", "validation", "test"}: The
sample whose metrics to return. Required for |
calibrated |
Logical: If TRUE, return the metrics of the calibrated predictions of a calibrated classifier. |
A Supervised model stores metrics for the training sample, and for the
validation and test samples when train received dat_validation and
dat_test. A SupervisedRes model stores per-resample metrics for the
training and test samples of each outer resample, with their mean and
standard deviation. A calibrated classifier also stores the metrics of its
calibrated predictions, selected with calibrated = TRUE.
A Clustering or Decomposition stores metrics for the data it was fitted
on, which sample = NULL and sample = "training" both select. For a
decomposition, decomp_metrics computes the metrics of new data.
Requesting a sample the object does not store raises an error that names the samples it does store.
The returned object supports $ and [[: for example,
get_metrics(mod, "test")$rsq.
Metrics object for a Supervised model; MetricsRes object for a
SupervisedRes model; ClusteringMetrics or DecompositionMetrics
object, or NULL when the object holds no metrics, for a Clustering or
Decomposition.
EDG
x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train( x[1:80, ], dat_test = x[81:100, ], hyperparameters = setup_GLM(), verbosity = 0L ) get_metrics(mod, "training") get_metrics(mod, "test")$rsqx <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train( x[1:80, ], dat_test = x[81:100, ], hyperparameters = setup_GLM(), verbosity = 0L ) get_metrics(mod, "training") get_metrics(mod, "test")$rsq
Returns the mode of a factor or integer
get_mode(x, na.rm = TRUE, getlast = TRUE, retain_class = TRUE)get_mode(x, na.rm = TRUE, getlast = TRUE, retain_class = TRUE)
x |
Vector, factor or integer: Input data. |
na.rm |
Logical: If TRUE, exclude NAs (using |
getlast |
Logical: If TRUE, get the last value in case of ties. |
retain_class |
Logical: If TRUE, output is always same class as input. |
The mode of x
EDG
x <- c(9, 3, 4, 4, 0, 2, 2, NA) get_mode(x) x <- c(9, 3, 2, 2, 0, 4, 4, NA) get_mode(x) get_mode(x, getlast = FALSE)x <- c(9, 3, 4, 4, 0, 2, 2, NA) get_mode(x) x <- c(9, 3, 2, 2, 0, 4, 4, NA) get_mode(x) get_mode(x, getlast = FALSE)
The variable importance measures a fitted model reports, or the mean
absolute contribution of each predictor in a SHAP explanation.
get_varimp(x, ...)get_varimp(x, ...)
x |
|
... |
Additional arguments passed to methods. |
A VariableImportance object holds its measures by name in @measures.
Each measure states what it quantifies (@kind, for example split gain,
permutation, or coefficient), the cases it was computed on
(@computed_on), whether its values can be negative (@signed) or depend
on the units of the predictors (@scale_dependent), how it ranks
predictors (@direction), and what its values are for this model
(@description); @values holds the value for each predictor.
varimp_table combines the measures into one data.frame.
VariableImportance object, a list of them (one per resample) for
a SupervisedRes, or NULL when the algorithm reports no importance.
EDG
mod <- train(iris, hyperparameters = setup_LightRF()) get_varimp(mod)mod <- train(iris, hyperparameters = setup_LightRF()) get_varimp(mod)
Get names by string matching or class
getnames( x, pattern = NULL, starts_with = NULL, ends_with = NULL, ignore_case = TRUE ) getfactornames(x) getnumericnames(x) getlogicalnames(x) getcharacternames(x) getdatenames(x)getnames( x, pattern = NULL, starts_with = NULL, ends_with = NULL, ignore_case = TRUE ) getfactornames(x) getnumericnames(x) getlogicalnames(x) getcharacternames(x) getdatenames(x)
x |
object with |
pattern |
Character: pattern to match anywhere in names of x. |
starts_with |
Character: pattern to match in the beginning of names of x. |
ends_with |
Character: pattern to match at the end of names of x. |
ignore_case |
Logical: If TRUE, well, ignore case. |
For getnames() only:
pattern, starts_with, and ends_with are applied sequentially.
If more than one is provided, the result will be the intersection of all matches.
Character vector of matched names.
EDG
getnames(iris, starts_with = "Sepal") getnames(iris, ends_with = "Width") getfactornames(iris) getnumericnames(iris)getnames(iris, starts_with = "Sepal") getnames(iris, ends_with = "Width") getfactornames(iris) getnumericnames(iris)
Get data.frame names and types
getnamesandtypes(x)getnamesandtypes(x)
x |
data.frame / data.table or similar |
character vector of column names with attribute "type" holding the class of each column
EDG
getnamesandtypes(iris)getnamesandtypes(iris)
Built by tune_over() and stored in the hyperparameter it is assigned to, so
that a search space is a distinct type, never inferred from a vector's
length.
HyperparameterCandidates(candidates = list(), from_vector = FALSE)HyperparameterCandidates(candidates = list(), from_vector = FALSE)
candidates |
List: The values to search over, one per element. |
from_vector |
Logical: TRUE when the candidates were read out of a single bare vector. A vector is also how one value of a vector-valued hyperparameter is written, so that one combination cannot be inferred; this records it so the hyperparameter can reject it with a correction. |
HyperparameterCandidates object.
EDG
# Built by tune_over(), not directly. d <- tune_over(3L, 4L, 5L) d@candidates# Built by tune_over(), not directly. d <- tune_over(3L, 4L, 5L) d@candidates
Select (include) columns by character or numeric vector.
inc(x, idx)inc(x, idx)
x |
tabular data. |
idx |
Character or numeric vector: Column names or indices to include. |
data.frame, tibble, or data.table.
EDG
inc(iris, c(3, 4)) |> head() inc(iris, c("Sepal.Length", "Species")) |> head()inc(iris, c(3, 4)) |> head() inc(iris, c("Sepal.Length", "Species")) |> head()
Index columns by attribute name & value
index_col_by_attr(x, name, value, exact = TRUE)index_col_by_attr(x, name, value, exact = TRUE)
x |
tabular data. |
name |
Character: Name of attribute. |
value |
Character: Value of attribute. |
exact |
Logical: Passed to |
Integer vector.
EDG
library(data.table) x <- data.table( id = 1:5, sbp = rnorm(5, 120, 15), dbp = rnorm(5, 80, 10), paO2 = rnorm(5, 90, 10), paCO2 = rnorm(5, 40, 5) ) setattr(x[["sbp"]], "source", "outpatient") setattr(x[["dbp"]], "source", "outpatient") setattr(x[["paO2"]], "source", "icu") setattr(x[["paCO2"]], "source", "icu") index_col_by_attr(x, "source", "icu")library(data.table) x <- data.table( id = 1:5, sbp = rnorm(5, 120, 15), dbp = rnorm(5, 80, 10), paO2 = rnorm(5, 90, 10), paCO2 = rnorm(5, 40, 5) ) setattr(x[["sbp"]], "source", "outpatient") setattr(x[["dbp"]], "source", "outpatient") setattr(x[["paO2"]], "source", "icu") setattr(x[["paCO2"]], "source", "icu") index_col_by_attr(x, "source", "icu")
The first step of any pipeline. A delimited file or a spreadsheet carries no usable type information; Parquet does. Ingesting once means nothing downstream infers a type a second time, and the decisions that were made are in the config.
The config's format is checked against the file, and a mismatch is an
error: a config written for a delimited file sets options a Parquet reader
would ignore.
Returns a manifest describing what happened: the file in, the file out, a
DataFingerprint of the data, the config, and which engine ran it. The
engine is named from the start because it is unrecoverable later – once a
second implementation exists, nothing else could say which produced a given
Parquet.
ingest(path, outfile, config = NULL, overwrite = FALSE, verbosity = 1L)ingest(path, outfile, config = NULL, overwrite = FALSE, verbosity = 1L)
path |
Character: Path to the input file. |
outfile |
Character: Path to write the Parquet file to. |
config |
Optional |
overwrite |
Logical: If TRUE, overwrite |
verbosity |
Integer: Verbosity level. |
Named list: the ingest manifest.
EDG
## Not run: ingest("data.csv", "data.parquet") ingest("data.csv", "data.parquet", setup_DelimitedIngest(sep = ";")) ## End(Not run)## Not run: ingest("data.csv", "data.parquet") ingest("data.csv", "data.parquet", setup_DelimitedIngest(sep = ";")) ## End(Not run)
Initializes Directory Structure: "R", "Data", "Results"
init_project_dir(path, output_dir = "Out", verbosity = 1L)init_project_dir(path, output_dir = "Out", verbosity = 1L)
path |
Character: Path to initialize project directory in. |
output_dir |
Character: Name of output directory to create. |
verbosity |
Integer: Verbosity level. |
Character: the path where the project directory was initialized, invisibly.
EDG
## Not run: # Will create "my_project" directory with init_project_dir("my_project") ## End(Not run)## Not run: # Will create "my_project" directory with init_project_dir("my_project") ## End(Not run)
Inspect rtemis object
inspect(x)inspect(x)
x |
R object to inspect. |
Called for side effect of printing information to console; returns character string invisibly.
EDG
inspect(iris)inspect(iris)
Checks character or factor vector to determine whether it might be best to convert to numeric.
inspect_type(x, xname = NULL, verbosity = 1L, thresh = 0.5, na.omit = TRUE)inspect_type(x, xname = NULL, verbosity = 1L, thresh = 0.5, na.omit = TRUE)
x |
Character or factor vector. |
xname |
Character: Name of input vector |
verbosity |
Integer: Verbosity level. |
thresh |
Numeric: Threshold for determining whether to convert to numeric. |
na.omit |
Logical: If TRUE, remove NA values before checking. |
All data can be represented as a character string. A numeric variable may be read as a character variable if there are non-numeric characters in the data. It is important to be able to automatically detect such variables and convert them, which would mean introducing NA values.
Character.
EDG
x <- c("3", "5", "undefined", "21", "4", NA) inspect_type(x) z <- c("mango", "banana", "tangerine", NA) inspect_type(z)x <- c("3", "5", "undefined", "21", "4", NA) inspect_type(x) z <- c("mango", "banana", "tangerine", NA) inspect_type(z)
Check if vector is constant
is_constant(x, skip_missing = FALSE)is_constant(x, skip_missing = FALSE)
x |
Vector: Input |
skip_missing |
Logical: If TRUE, skip NA values before test |
Logical.
EDG
x <- rep(9, 1000000) is_constant(x) x[10] <- NA is_constant(x) is_constant(x, skip_missing = TRUE)x <- rep(9, 1000000) is_constant(x) x[10] <- NA is_constant(x) is_constant(x, skip_missing = TRUE)
The read direction of S7_to_JSONSchema: reads each property's
PropertySpec back out of the schema and assembles a live S7 class whose
properties carry the same types, bounds, enums, containers, and validators as
the class the schema was generated from.
JSONSchema_to_S7( schema, defaults = NULL, refs = NULL, name = NULL, package = NULL, authoring = NULL, declarations = NULL, schemas = NULL, decode_reference = NULL, parent = NULL, policies = NULL )JSONSchema_to_S7( schema, defaults = NULL, refs = NULL, name = NULL, package = NULL, authoring = NULL, declarations = NULL, schemas = NULL, decode_reference = NULL, parent = NULL, policies = NULL )
schema |
Named list: A JSON Schema, as produced by S7_to_JSONSchema
or parsed from the published tree with |
defaults |
Optional named list: Format version 1 defaults artifact, or explicit property declaration values for an independently supplied schema. |
refs |
Optional named list: Property name to S7 class, for properties
published as a |
name |
Optional Character: Class name. Defaults to the schema |
package |
Optional Character: Package name recorded on the class. |
authoring |
Optional named list: Property name to logical authorship
policy, from the separate authoring artifact under this schema's |
declarations |
Optional List: Declaration descriptors keyed by schema pointer. |
schemas |
Optional List: Complete parsed schema graph keyed by canonical ID. Used with a format version 1 artifact to reconstruct typed references without source classes. |
decode_reference |
Optional Function: Reference decoder for a custom artifact graph. |
parent |
Optional S7 class: Reconstructed parent type. |
policies |
Optional List: Serialized input policy descriptors. |
Defaults are supplied in a separate versioned artifact keyed by schema $id.
The published schemas carry no default keywords. Absent declaration defaults remain absent;
constructing a non-nullable property without a default requires a value.
Properties holding a nested config are published as a $ref to that config's
own schema. Supply the parsed graph through schemas and the format version 1
artifact through defaults to reconstruct these references. Independently
supplied S7 reference classes can be passed through refs.
Reconstructed constructors use declaration defaults; input resolution policies
remain separate metadata on the class.
S7 class.
EDG
# A schema as `S7_to_JSONSchema()` emits it: standard keywords carry the # bounds, `x-rtemis` carries the leaf type. schema <- list( title = "Demo", properties = list( k = list( type = "integer", minimum = 1L, maximum = 10L, description = "Number of components.", `x-rtemis` = list(type = "integer") ) ) ) Demo <- JSONSchema_to_S7(schema, defaults = list(k = 2L)) Demo()@k Demo(k = 5L)@k # The reconstructed class enforces the schema's bounds. tryCatch(Demo(k = 99L), error = conditionMessage)# A schema as `S7_to_JSONSchema()` emits it: standard keywords carry the # bounds, `x-rtemis` carries the leaf type. schema <- list( title = "Demo", properties = list( k = list( type = "integer", minimum = 1L, maximum = 10L, description = "Number of components.", `x-rtemis` = list(type = "integer") ) ) ) Demo <- JSONSchema_to_S7(schema, defaults = list(k = 2L)) Demo()@k Demo(k = 5L)@k # The reconstructed class enforces the schema's bounds. tryCatch(Demo(k = 99L), error = conditionMessage)
Mass-univariate GLM Analysis
massGLM(x, y, scale_y = NULL, center_y = NULL, verbosity = 1L)massGLM(x, y, scale_y = NULL, center_y = NULL, verbosity = 1L)
x |
tabular data: Predictor variables. Usually a small number of covariates. |
y |
data.frame or similar: Each column is a different outcome. The function will train one
GLM for each column of |
scale_y |
Logical: If TRUE, scale each column of |
center_y |
Logical: If TRUE, center each column of |
verbosity |
Integer: Verbosity level. |
MassGLM object.
EDG
set.seed(2022) y <- rnormmat(500, 40, return_df = TRUE) x <- data.frame( x1 = y[[3]] - y[[5]] + y[[14]] + rnorm(500), x2 = y[[21]] + rnorm(500), g = factor(sample(letters[1:3], 500, replace = TRUE)) ) massmod <- massGLM(x, y) # Print table of coefficients, p-values, etc. for all models summary(massmod)set.seed(2022) y <- rnormmat(500, 40, return_df = TRUE) x <- data.frame( x1 = y[[3]] - y[[5]] + y[[14]] + rnorm(500), x2 = y[[21]] + rnorm(500), g = factor(sample(letters[1:3], 500, replace = TRUE)) ) massmod <- massGLM(x, y) # Print table of coefficients, p-values, etc. for all models summary(massmod)
Find one or more cases from a pool data.frame that match cases in a target
data.frame. Match exactly and/or by distance (sum of squared distances).
matchcases( target, pool, n_matches = 1, target_id = NULL, pool_id = NULL, exactmatch_factors = TRUE, exactmatch_cols = NULL, distmatch_cols = NULL, norepeats = TRUE, ignore_na = FALSE, verbosity = 1L )matchcases( target, pool, n_matches = 1, target_id = NULL, pool_id = NULL, exactmatch_factors = TRUE, exactmatch_cols = NULL, distmatch_cols = NULL, norepeats = TRUE, ignore_na = FALSE, verbosity = 1L )
target |
data.frame you are matching against. |
pool |
data.frame you are looking for matches from. |
n_matches |
Integer: Number of matches to return. |
target_id |
Character: Column name in |
pool_id |
Character: Same as |
exactmatch_factors |
Logical: If TRUE, selected cases will have to
exactly match factors available in |
exactmatch_cols |
Character: Names of columns that should be matched exactly. |
distmatch_cols |
Character: Names of columns that should be distance-matched. |
norepeats |
Logical: If TRUE, cases in |
ignore_na |
Logical: If TRUE, ignore NA values during exact matching. |
verbosity |
Integer: Verbosity level. |
data.frame
EDG
set.seed(2021) cases <- data.frame( PID = paste0("PID", seq(4)), Sex = factor(c(1, 1, 0, 0)), Handedness = factor(c(1, 1, 0, 1)), Age = c(21, 27, 39, 24), Var = c(.7, .8, .9, .6), Varx = rnorm(4) ) controls <- data.frame( CID = paste0("CID", seq(50)), Sex = factor(sample(c(0, 1), 50, TRUE)), Handedness = factor(sample(c(0, 1), 50, TRUE, c(.1, .9))), Age = sample(16:42, 50, TRUE), Var = rnorm(50), Vary = rnorm(50) ) mc <- matchcases(cases, controls, 2, "PID", "CID")set.seed(2021) cases <- data.frame( PID = paste0("PID", seq(4)), Sex = factor(c(1, 1, 0, 0)), Handedness = factor(c(1, 1, 0, 1)), Age = c(21, 27, 39, 24), Var = c(.7, .8, .9, .6), Varx = rnorm(4) ) controls <- data.frame( CID = paste0("CID", seq(50)), Sex = factor(sample(c(0, 1), 50, TRUE)), Handedness = factor(sample(c(0, 1), 50, TRUE, c(.1, .9))), Age = sample(16:42, 50, TRUE), Var = rnorm(50), Vary = rnorm(50) ) mc <- matchcases(cases, controls, 2, "PID", "CID")
Get names by string matching multiple patterns
mgetnames( x, pattern = NULL, starts_with = NULL, ends_with = NULL, ignore_case = TRUE, return_index = FALSE )mgetnames( x, pattern = NULL, starts_with = NULL, ends_with = NULL, ignore_case = TRUE, return_index = FALSE )
x |
Character vector or object with |
pattern |
Character vector: pattern(s) to match anywhere in names of x. |
starts_with |
Character: pattern to match in the beginning of names of x. |
ends_with |
Character: pattern to match at the end of names of x. |
ignore_case |
Logical: If TRUE, well, ignore case. |
return_index |
Logical: If TRUE, return integer index of matches instead of names. |
pattern, starts_with, and ends_with are applied and the union of all matches is returned.
pattern can be a character vector of multiple patterns to match.
Character vector of matched names or integer index.
EDG
mgetnames(iris, pattern = c("Sepal", "Petal")) mgetnames(iris, starts_with = "Sepal") mgetnames(iris, ends_with = "Width")mgetnames(iris, pattern = c("Sepal", "Petal")) mgetnames(iris, starts_with = "Sepal") mgetnames(iris, ends_with = "Width")
List column names by class
names_by_class(x, sorted = TRUE, item_format = highlight, maxlength = 24)names_by_class(x, sorted = TRUE, item_format = highlight, maxlength = 24)
x |
tabular data. |
sorted |
Logical: If TRUE, sort the output |
item_format |
Function: Function to format each item |
maxlength |
Integer: Maximum number of items to print |
NULL, invisibly.
EDG
names_by_class(iris)names_by_class(iris)
Returns the numeric columns among the features (all columns except the last).
numeric_features(x)numeric_features(x)
x |
tabular data: Input data to get numeric features from. |
Mirrors features(): by rtemis convention the last column is the outcome
variable and all other columns are features. This drops the outcome, then keeps
the numeric features (both double and integer). Useful, for example, to feed only
the continuous features to a decomposition: decomp(numeric_features(iris), ...).
Object of the same class as the input, containing only the numeric feature columns.
EDG
numeric_features(iris) |> head()numeric_features(iris) |> head()
Convert one-hot encoded matrix to factor
one_hot2factor(x, labels = colnames(x))one_hot2factor(x, labels = colnames(x))
x |
one-hot encoded matrix or data.frame. |
labels |
Character vector of level names. |
If input has a single column, it will be converted to factor and returned
A factor.
EDG
x <- data.frame(matrix(FALSE, 10, 3)) colnames(x) <- c("Dx1", "Dx2", "Dx3") x[["Dx1"]][1:3] <- x[["Dx2"]][4:6] <- x[["Dx3"]][7:10] <- TRUE one_hot2factor(x)x <- data.frame(matrix(FALSE, 10, 3)) colnames(x) <- c("Dx1", "Dx2", "Dx3") x[["Dx1"]][1:3] <- x[["Dx2"]][4:6] <- x[["Dx3"]][7:10] <- TRUE one_hot2factor(x)
Returns the last column of x, which is by convention the outcome variable.
outcome(x)outcome(x)
x |
tabular data. |
This applied to tabular datasets used for supervised learning in rtemis, where, by convention, the last column is the outcome variable and all other columns are features.
Vector containing the last column of x.
EDG
outcome(iris)outcome(iris)
Get the name of the last column
outcome_name(x)outcome_name(x)
x |
tabular data. |
This applied to tabular datasets used for supervised learning in rtemis, where, by convention, the last column is the outcome variable and all other columns are features.
Name of the last column.
EDG
outcome_name(iris)outcome_name(iris)
A held-out split is a decision – which rows train, which are held out, and
by what rule – and a decision the record cannot report is one nothing
downstream can audit. partition() makes it a first-class, executed step,
the same way ingest() makes reading a file one: the config states the
rule, this function applies it and returns a manifest naming exactly what
happened, including a DataFingerprint of each side.
Not a SuperConfig property. SuperConfig's dat_training_path and
dat_test_path simply name whatever partition() (or any other step)
produced – the same relationship they already have with ingest()'s
output.
partition(dat, config, outdir = NULL, overwrite = FALSE, verbosity = 1L)partition(dat, config, outdir = NULL, overwrite = FALSE, verbosity = 1L)
dat |
data.frame or data.table: The dataset to split. |
config |
|
outdir |
Optional Character: Directory to write |
overwrite |
Logical: If TRUE, overwrite existing output files. |
verbosity |
Integer: Verbosity level. |
Named list: the partition manifest – config, source (a
DataFingerprint of dat), and outputs (a list with training and
test, each holding a fingerprint and, when outdir is given, the path
written to).
EDG
partition(iris, setup_RandomPartition(train_p = 0.8, seed = 2026L))partition(iris, setup_RandomPartition(train_p = 0.8, seed = 2026L))
Draw training and validation losses recorded by a rtemis Supervised
object using the ECharts renderer in rtemis.draw.
plot_learning(x, ...)plot_learning(x, ...)
x |
|
... |
Additional arguments to |
The method uses get_learning_curve() to extract algorithm-specific
progress, losses, and the selected step, then rtemis.draw::draw_learning_curve() to
render them. Forest curves are averaged at each step over available trees.
Models without recorded learning losses produce an informative error.
The default title names the algorithm; pass title = NULL to omit it or
title = "..." to supply another title.
htmlwidget: ECharts learning curve.
model <- train( mtcars[, c("wt", "mpg")], hyperparameters = setup_LINAD(max_leaves = 3L), verbosity = 0L ) plot_learning(model)model <- train( mtcars[, c("wt", "mpg")], hyperparameters = setup_LINAD(max_leaves = 3L), verbosity = 0L ) plot_learning(model)
plot(model) draws a volcano plot using rtemis.draw.
plot_manhattan(model) draws categorical significance bars,
preserving outcome order. Both select one coefficient and use the shared
rtemis.draw::SignificanceConfig statistical contract via rtemis.draw::draw_volcano() or
rtemis.draw::draw_manhattan().
plot_manhattan(x, coefname = NULL, ...) plot_manhattan.MassGLM(x, coefname = NULL, ...) ## S3 method for class 'MassGLM' plot(x, ...)plot_manhattan(x, coefname = NULL, ...) plot_manhattan.MassGLM(x, coefname = NULL, ...) ## S3 method for class 'MassGLM' plot(x, ...)
x |
|
coefname |
Optional Character scalar: Coefficient to plot. Unset selects
the first entry in the object's |
... |
Named settings for |
plot_manhattan.MassGLM() is deprecated; use plot_manhattan().
An ECharts htmlwidget.
model <- massGLM(mtcars["wt"], mtcars[c("mpg", "hp", "disp")], verbosity = 0L) plot(model, coefname = "wt") plot_manhattan(model, coefname = "wt")model <- massGLM(mtcars["wt"], mtcars[c("mpg", "hp", "disp")], verbosity = 0L) plot(model, coefname = "wt") plot_manhattan(model, coefname = "wt")
S7 generic for SupervisedRes results, including
regression and classification. Uses recorded per-resample metrics in
resample_ids order; list names do not change that producer contract.
The default metric is balanced_accuracy for classification and rsq for
regression. Classification selects overall metrics, not per-class scores.
plot_metric(x, ...)plot_metric(x, ...)
x |
rtemis::SupervisedRes: Resampled fitted model. |
... |
Method arguments, including |
All available training and test reports are selected by default. An explicitly requested unavailable report is an error. Missing metric values remain missing; a metric absent from every selected report is an error. No predictions or aggregate means are used to reconstruct fold values.
htmlwidget: Metric distributions with all observations by default.
model <- train(mtcars[, c("wt", "mpg")], hyperparameters = setup_GLM(), outer_resampling_config = setup_KFold(n_resamples = 3L), execution_config = setup_SerialExecution(), verbosity = 0L ) plot_metric(model)model <- train(mtcars[, c("wt", "mpg")], hyperparameters = setup_GLM(), outer_resampling_config = setup_KFold(n_resamples = 3L), execution_config = setup_SerialExecution(), verbosity = 0L ) plot_metric(model)
S7 generic for ordinary and resampled rtemis classification objects using ECharts. All available training, validation, and test probability samples are selected by default. Resampled results use training and test. An explicit unavailable sample is an error; absence of training probabilities does not hide test data.
plot_roc(x, ...)plot_roc(x, ...)
x |
rtemis classification object: Ordinary or resampled result. |
... |
Method arguments, including |
variant = "aggregate" pools aligned prediction rows, retaining repeated
observations. "per_resample" draws individual curves with mean and sample
SD of fold AUCs. Missing probability folds remain undefined curves and are
disclosed; they are not zero AUCs. All curves use the same named classes and
binary positive class, defaulting to the first fold's second outcome level.
An ECharts htmlwidget.
model <- train(iris, hyperparameters = setup_CART(), verbosity = 0L) plot_roc(model)model <- train(iris, hyperparameters = setup_CART(), verbosity = 0L) plot_roc(model)
Plots the session timeline of a Supervised or SupervisedRes object using
rtemis.draw::draw_gantt().
plot_session(x, ...)plot_session(x, ...)
x |
|
... |
Additional arguments passed to |
Dispatches on ordinary and resampled supervised results.
htmlwidget: Widget object.
EDG
# GLM keeps the example dependency-free: rtemis fits it with stats::glm(). mod <- train( mtcars[, c("wt", "hp", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L ) plot_session(mod)# GLM keeps the example dependency-free: rtemis fits it with stats::glm(). mod <- train( mtcars[, c("wt", "hp", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L ) plot_session(mod)
S7 generic for ECharts plots of rtemis regression and classification results.
plot_true_pred(x, ...)plot_true_pred(x, ...)
x |
rtemis regression or classification object: Ordinary or resampled result. |
... |
Method arguments, including |
what = "all" selects available training, validation, and test pairs for
a regression model, or training and test pairs for a resampled model.
An explicitly requested missing sample is an error. Resampled observations
are pooled in fold order, keeping repeated observations. Pair lengths and
names are checked within each fold before pooling.
Rendering is provided by rtemis.draw::draw_fit(). The API uses draw argument names,
including se, square, equal_axes, and title, and a draw rtemis.draw::Theme.
Supported fits are "glm", "gam", or NULL.
Classification uses rtemis.draw::draw_confusion() with stored confusion frequencies
when available, preserving the producer's class order. Otherwise it counts
aligned reference/predicted pairs. An omitted what selects test, validation,
then training for an ordinary classifier, or all available samples for a
resampled classifier. Multiple samples share one widget and one export.
Balanced accuracy in this view is macro recall; it is not the legacy
multiclass average of one-versus-rest balanced accuracies. See
rtemis.draw::ConfusionConfig for zero-denominator and pooled-count semantics.
htmlwidget: ECharts drawing.
model <- train( mtcars[, c("wt", "hp", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L ) plot_true_pred(model)model <- train( mtcars[, c("wt", "hp", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L ) plot_true_pred(model)
Draw importance recorded by a rtemis Supervised or SupervisedRes object,
or computed from a SHAP explanation by get_varimp, using
rtemis.draw::draw_varimp().
plot_varimp(x, ...)plot_varimp(x, ...)
x |
|
... |
Additional arguments to |
Named measures and variable identities are preserved. Resampled records
retain their fold IDs before summarizing. The first measure in the first
available fold is selected when measure is omitted; columns missing in
other folds are unavailable scores. The full fold list is passed to the
renderer, including folds with no importance result.
CART's importance and LightGBM's Gain, Cover, and Frequency come
from sparse split summaries: omitted variables in a reporting fold have
zero importance. These measures use absent = "zero". Other measures use
absent = "missing"; pass absent explicitly to declare another contract.
Explicit NA values and wholly unavailable folds are always kept missing.
Use type = "boxplot" for resampled fold distributions with all contributing
scores overlaid. Summary bars remain the default. Both views share selection,
ranking, and the producer's missing-score contract. Ordinary models have no
fold distribution and require the bar view.
A SHAP explanation is drawn from the mean absolute contribution of each
feature, with one measure per class for a multiclass outcome.
Models without any importance records produce an informative error.
The default title names the algorithm; title = NULL omits it.
See rtemis.draw::draw_varimp() for selection, ranking, and missing-score semantics.
htmlwidget: ECharts importance bars or fold distributions.
model <- train( mtcars[, c("wt", "hp", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L ) plot_varimp(model) features <- mtcars[, c("wt", "hp")] plot_varimp(explain(model, features, background = features, verbosity = 0L))model <- train( mtcars[, c("wt", "hp", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L ) plot_varimp(model) features <- mtcars[, c("wt", "hp")] plot_varimp(explain(model, features, background = features, verbosity = 0L))
Preprocess data for analysis and visualization.
preprocess( x, config, dat_validation = NULL, dat_test = NULL, verbosity = 1L, ... )preprocess( x, config, dat_validation = NULL, dat_test = NULL, verbosity = 1L, ... )
x |
Tabular data, i.e. data.frame, data.table, or tbl_df (tibble): Training set data to preprocess. |
config |
|
dat_validation |
Optional tabular data: Validation set data. Preprocessed using the values learned from the training set data. |
dat_test |
Optional tabular data: Test set data. Preprocessed using the values learned from the training set data. |
verbosity |
Integer: Verbosity level. |
... |
setup_Preprocessor arguments: Only used when |
preprocess() preprocesses training data and learns any data-dependent values (e.g. scale
centers and coefficients, one-hot levels). Optional dat_validation and dat_test data are
preprocessed using the values learned from the training data. To apply a trained
Preprocessor to new data, use apply_preprocessor.
For interactive use, config may be omitted and setup_Preprocessor arguments passed
directly instead, e.g. preprocess(x, scale = TRUE, center = TRUE). At least one
preprocessing parameter must be specified: preprocess(x) is an error.
The preprocessed data comes back in the structure it was given – data.frame, data.table or tibble – and the object passed in is never modified. It carries no row names: a case identifier that matters belongs in a column, where it can be selected, joined, validated and serialized.
Preprocessor object.
EDG
apply_preprocessor, setup_Preprocessor
# Setup a `Preprocessor`: this outputs a `PreprocessorConfig` object. prp <- setup_Preprocessor(remove_duplicates = TRUE, scale = TRUE, center = TRUE) # Includes a long list of parameters prp # Resample iris to get train and test data res <- resample(iris, setup_KFold(seed = 2026)) iris_train <- iris[res[[1]], ] iris_test <- iris[-res[[1]], ] # Preprocess training data iris_pre <- preprocess(iris_train, prp) # Alternatively, for interactive use, pass `setup_Preprocessor()` arguments directly iris_pre <- preprocess(iris_train, remove_duplicates = TRUE, scale = TRUE, center = TRUE) # Access preprocessed training data with `preprocessed()` preprocessed(iris_pre) # Apply the same preprocessing to test data with `apply_preprocessor()`, # which returns the preprocessed data directly. # The scale and center values learned from the training data will be used. iris_test_pre <- apply_preprocessor(iris_pre, iris_test)# Setup a `Preprocessor`: this outputs a `PreprocessorConfig` object. prp <- setup_Preprocessor(remove_duplicates = TRUE, scale = TRUE, center = TRUE) # Includes a long list of parameters prp # Resample iris to get train and test data res <- resample(iris, setup_KFold(seed = 2026)) iris_train <- iris[res[[1]], ] iris_test <- iris[-res[[1]], ] # Preprocess training data iris_pre <- preprocess(iris_train, prp) # Alternatively, for interactive use, pass `setup_Preprocessor()` arguments directly iris_pre <- preprocess(iris_train, remove_duplicates = TRUE, scale = TRUE, center = TRUE) # Access preprocessed training data with `preprocessed()` preprocessed(iris_pre) # Apply the same preprocessing to test data with `apply_preprocessor()`, # which returns the preprocessed data directly. # The scale and center values learned from the training data will be used. iris_test_pre <- apply_preprocessor(iris_pre, iris_test)
Preprocessor.Returns the preprocessed data from a Preprocessor object.
preprocessed(x)preprocessed(x)
x |
|
data.frame: The preprocessed data.
prp <- preprocess(iris, setup_Preprocessor(scale = TRUE, center = TRUE)) preprocessed(prp)prp <- preprocess(iris, setup_Preprocessor(scale = TRUE, center = TRUE)) preprocessed(prp)
A single model prints its describe() output, unless verbosity = 0, and
returns its default plot() view: true/predicted values for regression,
confusion matrices for classification, and stored metric distributions for
resampled models. plot_roc() draws ROC curves for classification models
with predicted probabilities.
present(x, ...)present(x, ...)
x |
rtemis model or List: Fitted ordinary/resampled models. |
... |
Arguments for the selected presentation: |
A nonempty homogeneous list compares models of the same task and sampling
kind. Ordinary models use grouped metric bars. Resampled models use one
boxplot panel per sample with common value limits and aligned model labels.
Fold counts may differ; fold scores are neither paired nor pooled across
models. Missing scores stay missing. Wholly unavailable samples are omitted
under what = "all"; explicit unavailable samples are errors.
Comparison labels use model_names, complete list names, or algorithm
names, made unique in that order. The existing rtemis data-fingerprint
mismatch notice is retained, including when descriptions are disabled.
htmlwidget: One chart or one complete rtemis.draw::draw_panels() figure.
plot() on a fitted model draws the view present() returns, without the
description:
Regression: plot_true_pred() for all available samples.
Classification: confusion matrices for all available samples, as drawn
by plot_true_pred().
RegressionRes and ClassificationRes: plot_metric() for all
available samples.
Arguments after x are passed to the corresponding plot_*() method, for
example plot(model, what = "test") or plot(model, metric = "rmse").
Model plots color each data split the same way: training teal, validation
purple, test magenta. A supplied palette replaces these
colors. Confusion matrices shade correct predictions blue and incorrect
predictions orange.
model <- train(mtcars[, c("wt", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L) present(model, verbosity = 0L) plot(model)model <- train(mtcars[, c("wt", "mpg")], hyperparameters = setup_GLM(), verbosity = 0L) present(model, verbosity = 0L) plot(model)
Read data and optionally clean column names, keep unique rows, and convert characters to factors
read( filename, datadir = NULL, remove_duplicates = FALSE, character2factor = FALSE, clean_colnames = TRUE, delim_reader = c("data.table", "vroom", "duckdb", "arrow"), parquet_reader = c("nanoparquet", "arrow"), xlsx_sheet = 1, sep = NULL, quote = "\"", na_strings = c(""), output = c("data.table", "tibble", "data.frame"), attr = NULL, value = NULL, verbosity = 1L, fread_verbosity = 0L, timed = verbosity > 0L, ... )read( filename, datadir = NULL, remove_duplicates = FALSE, character2factor = FALSE, clean_colnames = TRUE, delim_reader = c("data.table", "vroom", "duckdb", "arrow"), parquet_reader = c("nanoparquet", "arrow"), xlsx_sheet = 1, sep = NULL, quote = "\"", na_strings = c(""), output = c("data.table", "tibble", "data.frame"), attr = NULL, value = NULL, verbosity = 1L, fread_verbosity = 0L, timed = verbosity > 0L, ... )
filename |
Character: filename or full path if |
datadir |
Character: Optional path to directory where |
remove_duplicates |
Logical: If TRUE, keep unique rows only. |
character2factor |
Logical: If TRUE, convert character variables to factors. |
clean_colnames |
Logical: If TRUE, clean columns names using clean_colnames. |
delim_reader |
Character: package to use for reading delimited data. |
parquet_reader |
Character: package to use for reading Parquet files. If undefined and system is WASM, uses "nanoparquet", otherwise "arrow". |
xlsx_sheet |
Integer or character: Name or number of XLSX sheet to read. |
sep |
Single character: field separator. If |
quote |
Single character: quote character. |
na_strings |
Character vector: Strings to be interpreted as NA values.
For |
output |
Character: "default" or "data.table", If default, return the delim_reader's default data structure, otherwise convert to data.table. |
attr |
Character: Attribute to set (Optional). |
value |
Character: Value to set (if |
verbosity |
Integer: Verbosity level. |
fread_verbosity |
Integer: Verbosity level. Passed to |
timed |
Logical: If TRUE, time the process and print to console |
... |
Additional arguments to pass to |
read is a convenience function to read:
Delimited files using data.table:fread(), arrow:read_delim_arrow(),
vroom::vroom(), or duckdb::duckdb_read_csv()
ARFF files using farff::readARFF()
Parquet files using nanoparquet::read_parquet or arrow::read_parquet()
XLSX files using readxl::read_excel()
DTA files from Stata using haven::read_dta()
FASTA files using seqinr::read.fasta()
RDS files using readRDS()
data.frame, data.table, or tibble.
EDG
## Not run: # Replace with your own data directory and filename datadir <- "/Data" dat <- read("iris.csv", datadir) ## End(Not run)## Not run: # Replace with your own data directory and filename datadir <- "/Data" dat <- read("iris.csv", datadir) ## End(Not run)
Read a schema.rtemis.org JSON config and return the appropriate rtemis object.
Two families of config are supported: pipeline recipes that bundle a data
path, algorithm config, and output directory (SuperConfig,
DecomposeConfig, ClusterConfig), and the bare algorithm configs they wrap
(DecompositionConfig, ClusteringConfig). The file is JSON, as written by
write_config and consumed by rtemislive and the rtemis CLI.
read_config(file)read_config(file)
file |
Character: Path to input JSON config file. |
The config family is taken from the instance's $schema, which must be one of
the supported schemas; a missing or unrecognized $schema is an error.
A run record is rejected, and named as such. A record declares the same
fields as the config it came from, so it would read as one – but every value
in it is resolved, including values a run derived from data this call has
never seen. Accepting it would silently pin settings the new call should
decide for itself. Records are written by write_record and identify
themselves with a record.json schema.
Validation is entirely rtemis's own: check_wire_keys() rejects an unknown
key at every level of the document, and each setup_* then constructs an S7
object whose properties enforce their declared types, bounds, enums and
arities. Those properties are the same PropertySpecs the published JSON
Schemas are generated from, so reading a config in R applies the published
contract by construction – there is nothing an external validator could add.
A SuperConfig, DecomposeConfig, ClusterConfig,
DecompositionConfig, or ClusteringConfig object.
EDG
# Create a SuperConfig object x <- setup_SuperConfig( dat_training_path = "~/Data/iris.csv", hyperparameters = setup_LightRF() ) # Write JSON config file tmpdir <- tempdir() tmpfile <- file.path(tmpdir, "rtemis_test.json") write_config(x, tmpfile, overwrite = TRUE) # Read config back from JSON file x_read <- read_config(tmpfile)# Create a SuperConfig object x <- setup_SuperConfig( dat_training_path = "~/Data/iris.csv", hyperparameters = setup_LightRF() ) # Write JSON config file tmpdir <- tempdir() tmpfile <- file.path(tmpdir, "rtemis_test.json") write_config(x, tmpfile, overwrite = TRUE) # Read config back from JSON file x_read <- read_config(tmpfile)
Reconstruct the report's classes from the supplied schema and defaults
artifacts. Parsing does not open referenced files. With load_data = TRUE,
verify file integrity and dimensions, then validate the materialized values.
Native fitted objects are not restored.
read_result(file, registry, load_data = FALSE)read_result(file, registry, load_data = FALSE)
file |
Character: Result JSON path. |
registry |
Character: Local registry directory containing versioned
schema documents and |
load_data |
Logical: Materialize Parquet references. |
An S7 report reconstructed from registry declarations.
# A local registry is supplied explicitly; reading never fetches schemas. reader <- function(file, registry) read_result(file, registry, load_data = TRUE)# A local registry is supplied explicitly; reading never fetches schemas. reader <- function(file, registry) read_result(file, registry, load_data = TRUE)
Encode data with a fitted decomposition and decode it back, giving the
rank-k approximation of the input in its original units and column layout.
reconstruct(decom, x, execution_config = NULL, verbosity = 1L)reconstruct(decom, x, execution_config = NULL, verbosity = 1L)
decom |
|
x |
Tabular data (data.frame, data.table, or tibble): Data to
reconstruct. Its columns must match those |
execution_config |
Optional |
verbosity |
Integer: Verbosity level. |
The round trip apply_decomp leaves half-done. The reconstruction is x
with everything outside the first k components removed, i.e. a denoised
x. The residual, x - reconstruct(decom, x), is what the decomposition
could not represent: rowMeans(residual^2) scores how anomalous each case
is, and colMeans(residual^2) shows which variables the decomposition fails
to capture.
Available for algorithms whose invertible trait is TRUE; see
decomposition_traits. tSNE, UMAP and Isomap embed without an inverse, so
there is no map back for them at all.
The reconstruction is in the units of the data as it was passed to decomp,
with any centering or scaling the backend applied internally undone, so it
can be compared with x directly. Columns the fit did not decompose (when
decom@config@features is set) pass through unchanged and column order is
preserved, so the result lines up cell for cell with x.
A data.frame with the same columns as x, holding the
reconstruction of the decomposed features.
EDG
x <- exc(iris, "Species") iris_pca <- decomp(x, algorithm = "PCA", config = setup_PCA(k = 2L)) reconstructed <- reconstruct(iris_pca, x) # What the two components could not represent, per case: head(rowMeans((as.matrix(x) - as.matrix(reconstructed))^2))x <- exc(iris, "Species") iris_pca <- decomp(x, algorithm = "PCA", config = setup_PCA(k = 2L)) reconstructed <- reconstruct(iris_pca, x) # What the two components could not represent, per case: head(rowMeans((as.matrix(x) - as.matrix(reconstructed))^2))
The record of what ran: every config value resolved, an origin saying where
each came from, and a provenance block. Derived on demand from the configs
the object already holds.
record(x, ...)record(x, ...)
x |
Fitted model object. |
... |
Passed to methods. |
Named list, conforming to the family's record.json.
EDG
mod <- train(iris, hyperparameters = setup_CART()) names(record(mod))mod <- train(iris, hyperparameters = setup_CART()) names(record(mod))
Regression Metrics
regression_metrics(true, predicted, na.rm = TRUE, sample = NULL)regression_metrics(true, predicted, na.rm = TRUE, sample = NULL)
true |
Numeric vector: True values. |
predicted |
Numeric vector: Predicted values. |
na.rm |
Logical: If TRUE, remove NA values before computation. |
sample |
Optional Character {"Training", "Validation", "Test", "Calibrated Training", "Calibrated Validation", "Calibrated Test"}: Sample the metrics describe. |
RegressionMetrics object.
EDG
true <- rnorm(100) predicted <- true + rnorm(100, sd = 0.5) regression_metrics(true, predicted)true <- rnorm(100) predicted <- true + rnorm(100, sd = 0.5) regression_metrics(true, predicted)
Create resamples of your data, e.g. for model building or validation.
"KFold" creates stratified folds, , "StratSub" creates stratified subsamples,
"Bootstrap" gives the standard bootstrap, i.e. random sampling with replacement,
while "StratBoot" uses StratSub and then randomly duplicates some of the training cases to
reach the original length of the input, or the length defined by target_length.
resample(x, config = setup_KFold(), verbosity = 1L)resample(x, config = setup_KFold(), verbosity = 1L)
x |
Vector or data.frame: Usually the outcome; |
config |
Resampler object created by one of the |
verbosity |
Integer: Verbosity level. |
Note that option 'KFold' may result in resamples of slightly different length. Avoid all operations which rely on equal-length vectors. For example, you can't place resamples in a data.frame, but must use a list instead.
Resampler object.
EDG
y <- rnorm(200) # 10-fold (stratified) y_10fold <- resample(y, setup_KFold(10L)) y_10fold # 25 stratified subsamples y_25strat <- resample(y, setup_StratSub(25L)) y_25strat # 100 stratified bootstraps y_100strat <- resample(y, setup_StratBoot(100L)) y_100strat # LOOCV y_loocv <- resample(y, setup_LOOCV()) y_loocv # User-supplied resamples y_custom <- resample( y, setup_Custom(resamples = list(1:150, 51:200)) ) y_customy <- rnorm(200) # 10-fold (stratified) y_10fold <- resample(y, setup_KFold(10L)) y_10fold # 25 stratified subsamples y_25strat <- resample(y, setup_StratSub(25L)) y_25strat # 100 stratified bootstraps y_100strat <- resample(y, setup_StratBoot(100L)) y_100strat # LOOCV y_loocv <- resample(y, setup_LOOCV()) y_loocv # User-supplied resamples y_custom <- resample( y, setup_Custom(resamples = list(1:150, 51:200)) ) y_custom
Assess a trained model: whether its evaluation can be trusted given the sample size and the number of predictors, whether it performs better than a baseline that ignores the predictors, and whether it overfits. The review is deterministic: it draws no random numbers.
review(x, confidence_level = NULL, min_cases_per_predictor = NULL, ...)review(x, confidence_level = NULL, min_cases_per_predictor = NULL, ...)
x |
|
confidence_level |
Optional Numeric (0, 1): Confidence level of every interval. NULL uses 0.95. |
min_cases_per_predictor |
Optional Numeric (0, Inf): Training cases per learner column – minority-class cases for classification – below which the review notes a shortfall. NULL uses 10, an events-per-variable rule of thumb from logistic regression (see References). |
... |
Not used. |
The review holds every value it rests on, so a reader can judge for
themselves: @sample (sample sizes, input predictors and the columns the
learner received), @class_counts, @performance (one row per metric:
training, test, training minus test, the spread over resamples, and the
test interval or pooled value), @baseline (one row per comparison with a
reference that ignores the predictors, naming the reference and the method)
and @tuning (tuned hyperparameters against their search range). Its
findings state what it observes. Printing shows a summary: one row per
metric – mean (SD) over resamples for a resampled model – the baseline
comparisons, the findings and the limitations.
Single split. The test cases are independent of the fitted model, so
the review computes confidence intervals and two-sided comparisons at
confidence_level. Accuracy is compared with always predicting the most
common training class by the exact McNemar test, which pairs the two
predictors' results case by case. Balanced accuracy and AUC are compared
with their chance levels (1/K, 0.5) through their intervals:
per-class binomial variances for balanced accuracy, the DeLong method for
AUC. The Brier score, MSE and MAE are compared with a constant baseline
(training proportion, training mean) through a paired t interval of the
per-case loss reduction; the skill score is reported as a point estimate.
An interval that cannot be computed – too few cases, a class absent from
the test set, an AUC of 0 or 1 – is left unset and no verdict is made from
it. A training value of the headline metric (balanced accuracy, or mean
squared error for regression) outside its test interval is reported as a
diagnostic sign of possible overfitting; it is not a test of the
train-test difference.
Resampled models. Resamples share training cases, so their test results are dependent, and the review makes no interval or test from them. Every metric is reported as its mean and standard deviation over the outer resamples, each baseline is fit to the training data of its resample, and the review counts the resamples in which the model beat its baseline. When every case is tested once, as with k-fold resampling, pooled out-of-sample values are reported as descriptions for metrics that average over cases; AUC is not pooled, since it would rank scores from different fitted models together.
A tuned hyperparameter selected at the edge of the values searched is reported, since a better value may lie beyond it.
The cases-per-predictor check counts the columns the learner received, after preprocessing and decomposition. Its threshold is a rule of thumb from logistic regression (events per variable; see References), reported for context.
Preprocessing, decomposition and tuning inside train() are fitted on the
training cases of each split and only applied to its test cases. Steps
taken before the data is passed to train() – selecting predictors or
transforming cases using all the data, or choosing among models by their
test performance – can bias evaluation, and the fitted model cannot show
whether they happened. Performance metrics also cannot establish whether a
model is useful. Every review states both.
Print the result to read it; write_text writes it as Markdown.
SupervisedReview object, whose tables are data.frames.
EDG
Clopper CJ, Pearson ES (1934). The use of confidence or fiducial limits illustrated in the case of the binomial. Biometrika, 26(4), 404-413.
DeLong ER, DeLong DM, Clarke-Pearson DL (1988). Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach. Biometrics, 44(3), 837-845.
McNemar Q (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12(2), 153-157.
Peduzzi P, Concato J, Kemper E, Holford TR, Feinstein AR (1996). A simulation study of the number of events per variable in logistic regression analysis. Journal of Clinical Epidemiology, 49(12), 1373-1379.
idx <- c(1:40, 51:90, 101:140) mod <- train( iris[idx, ], dat_test = iris[-idx, ], hyperparameters = setup_CART(), verbosity = 0L ) review(mod) # Resampled mod_res <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(5L), verbosity = 0L ) review(mod_res)idx <- c(1:40, 51:90, 101:140) mod <- train( iris[idx, ], dat_test = iris[-idx, ], hyperparameters = setup_CART(), verbosity = 0L ) review(mod) # Resampled mod_res <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(5L), verbosity = 0L ) review(mod_res)
Create a matrix or data frame of defined dimensions, whose columns are random normal vectors
rnormmat( nrow = 10, ncol = 10, mean = 0, sd = 1, return_df = FALSE, seed = NULL )rnormmat( nrow = 10, ncol = 10, mean = 0, sd = 1, return_df = FALSE, seed = NULL )
nrow |
Integer: Number of rows. |
ncol |
Integer: Number of columns. |
mean |
Float: Mean. |
sd |
Float: Standard deviation. |
return_df |
Logical: If TRUE, return data.frame, otherwise matrix. |
seed |
Integer: Set seed for |
matrix or data.frame.
EDG
x <- rnormmat(20, 5, mean = 12, sd = 6, return_df = TRUE, seed = 2026) xx <- rnormmat(20, 5, mean = 12, sd = 6, return_df = TRUE, seed = 2026) x
Compute the points of one or more ROC curves from true labels and predicted
probabilities, returning tidy (class, fpr, tpr, auc) rows. The rows serve any consumer of the
curve data, such as a client that renders the curve.
roc_curve(true_labels, predicted_prob, max_points = NULL)roc_curve(true_labels, predicted_prob, max_points = NULL)
true_labels |
Factor: True outcome labels. |
predicted_prob |
Numeric vector or matrix [0, 1]: Predicted
probabilities for the positive class (second level of |
max_points |
Optional Integer [2, Inf): Cap on the number of vertices
per curve. |
Binary problems yield a single curve for the positive class (the second
level of true_labels, rtemis convention); multiclass problems yield one
one-vs-rest curve per class. Points are ordered along the curve; pass
max_points to down-sample very long curves (one vertex per distinct score)
to a compact, smooth line.
data.frame with columns class, fpr, tpr, auc (the AUC is
constant within a class group, repeated per vertex). Zero rows when no
curve is defined.
EDG
true_labels <- factor(c("A", "B", "A", "A", "B", "A", "B", "B", "A", "B")) predicted_prob <- c(0.1, 0.4, 0.35, 0.8, 0.65, 0.2, 0.9, 0.55, 0.3, 0.7) roc_curve(true_labels, predicted_prob)true_labels <- factor(c("A", "B", "A", "A", "B", "A", "B", "B", "A", "B")) predicted_prob <- c(0.1, 0.4, 0.35, 0.8, 0.65, 0.2, 0.9, 0.55, 0.3, 0.7) roc_curve(true_labels, predicted_prob)
Errors signalled by rtemis are classed R conditions, so they can be
handled selectively with tryCatch() or withCallingHandlers() by class. Each error carries a class vector ordered from the
most specific failure mode to the most general, so a handler can catch
narrowly (e.g. only type errors) or broadly (e.g. any invalid input).
Every rtemis error inherits, in order: its specific class (when applicable),
its category class, and finally "rtemis_error", "error", "condition".
Catching rtemis_error therefore catches all rtemis errors.
Not applicable. This page documents the condition classes; the functions that signal them do not return when they error.
rtemis_input_errorA function argument supplied by the caller is invalid. Specific classes:
rtemis_type_errorArgument is of the wrong type or class.
rtemis_value_errorArgument has a disallowed value or choice.
rtemis_length_errorArgument has the wrong length or count.
rtemis_range_errorArgument is outside its allowed range.
rtemis_null_inputA required argument is NULL or empty.
rtemis_data_errorThe supplied dataset is unsuitable for the requested operation. Specific classes:
rtemis_dim_errorData has the wrong dimensions (e.g. too few columns).
rtemis_level_mismatchFactor levels do not match across data splits.
rtemis_missing_dataData contains missing values where none are allowed.
rtemis_outcome_errorThe outcome column has an invalid or mismatched type.
rtemis_io_errorA filesystem operation failed. Specific classes:
rtemis_file_not_foundA path or file does not exist.
rtemis_file_existsA file already exists and overwriting was not permitted.
rtemis_unsupported_errorThe requested algorithm, feature, or combination is not supported (e.g. multiclass classification for an algorithm that only handles binary outcomes). No specific subclass.
rtemis_runtime_errorA model or algorithm call failed during execution. The original error is
attached as the condition's $parent. No specific subclass.
EDG
# Every rtemis error inherits `rtemis_error`. Catch a category broadly: result <- tryCatch( set_outcome(iris, "nonexistent_column"), rtemis_input_error = function(e) { message("Caught an input error: ", conditionMessage(e)) NULL } ) # Or catch a specific failure mode only: result <- tryCatch( set_outcome(iris, "nonexistent_column"), rtemis_value_error = function(e) { message("Caught a value error: ", conditionMessage(e)) NULL } )# Every rtemis error inherits `rtemis_error`. Catch a category broadly: result <- tryCatch( set_outcome(iris, "nonexistent_column"), rtemis_input_error = function(e) { message("Caught an input error: ", conditionMessage(e)) NULL } ) # Or catch a specific failure mode only: result <- tryCatch( set_outcome(iris, "nonexistent_column"), rtemis_value_error = function(e) { message("Caught a value error: ", conditionMessage(e)) NULL } )
Get rtemis version and system info
rtversion()rtversion()
List: rtemis version and system info, invisibly.
EDG
rtversion()rtversion()
Create a matrix or data frame of defined dimensions, whose columns are random uniform vectors
runifmat( nrow = 10, ncol = 10, min = 0, max = 1, return_df = FALSE, seed = NULL )runifmat( nrow = 10, ncol = 10, min = 0, max = 1, return_df = FALSE, seed = NULL )
nrow |
Integer: Number of rows. |
ncol |
Integer: Number of columns. |
min |
Float: Min. |
max |
Float: Max. |
return_df |
Logical: If TRUE, return data.frame, otherwise matrix. |
seed |
Integer: Set seed for |
matrix or data.frame.
EDG
x <- runifmat(20, 5, min = 12, max = 18, return_df = TRUE, seed = 2026) xx <- runifmat(20, 5, min = 12, max = 18, return_df = TRUE, seed = 2026) x
Assembles the <family>/v1 schema for a config family: an object holding
the discriminator (algorithm, type, ...), the properties the family base
declares for every variant, and an allOf of if/then clauses that apply
the selected variant's leaf schema (<family>/<variant>/v1) to the whole
object. The discriminator enum, the leaf $ref URLs and the allOf table
are all derived from the classes, so the dispatcher cannot drift from the
leaves it dispatches to.
S7_dispatcher_JSONSchema( classes, id, discriminator = "algorithm", base = NULL, title = NULL, description = "", discriminator_description = "Algorithm name.", record = FALSE, instance_schema_url = NULL )S7_dispatcher_JSONSchema( classes, id, discriminator = "algorithm", base = NULL, title = NULL, description = "", discriminator_description = "Algorithm name.", record = FALSE, instance_schema_url = NULL )
classes |
List of S7 classes: the family's per-variant subclasses (each carries a computed constant discriminator property). |
id |
Character: Dispatcher |
discriminator |
Character: Name of the property that selects the variant (e.g. "algorithm", "type"). |
base |
Optional S7 class: The family base class. Its own
|
title |
Optional Character: Schema title. |
description |
Character: Schema description. If empty, omitted. The shape rule – settings are siblings of the discriminator – is appended, so every family states it the same way. |
discriminator_description |
Character: Description of the discriminator property. |
record |
Logical: If TRUE, dispatch to the variants' record
schemas ( |
instance_schema_url |
Character or NULL: If set, adds a |
The leaf URLs are derived from id: for a dispatcher
.../<family>/v1/schema.json, variant A maps to
.../<family>/<tolower(A)>/v1/schema.json – matching S7_to_JSONSchema's
id convention for the leaves.
One shape, matching how every family serializes (dispatched_props()): the
variant's settings are siblings of the discriminator. A document holding
only the discriminator is that variant with every default, so "nothing set"
is said by absence, as a delta config says everything else, and a writer
has no empty settings object to emit.
Each then is exactly the leaf $ref, applied to the whole object; readers
key on that. additionalProperties is evaluated per schema and would not
see the leaf's properties, so strictness comes from draft 2020-12's
unevaluatedProperties: false, which does account for properties evaluated
by the applied $ref. Leaves must therefore be generated open
(closed = FALSE in S7_to_JSONSchema) so they compose.
The leaf's keys and the dispatcher's are disjoint by construction: base
subtracts every base property, the discriminator included, from each leaf,
so a setting can never land on a key the dispatcher declares.
base closes the loop with S7_to_JSONSchema's base argument, which
subtracts the family base's properties from every leaf: the dispatcher
adds them back at the top level, from the same PropertySpec, so the shared
fields are declared once. Base properties carrying no spec are class
machinery (a computed settings list, run state) and are skipped, as is the
discriminator, which is generated from the variant enum.
Named list: the dispatcher JSON Schema. Serialize with write_JSONSchema.
EDG
## Not run: schema <- S7_dispatcher_JSONSchema( classes = list(PCAConfig, ICAConfig), id = "https://schema.rtemis.org/decomposition/r/v1/schema.json", base = DecompositionConfig ) ## End(Not run)## Not run: schema <- S7_dispatcher_JSONSchema( classes = list(PCAConfig, ICAConfig), id = "https://schema.rtemis.org/decomposition/r/v1/schema.json", base = DecompositionConfig ) ## End(Not run)
prop_* factories to a JSON SchemaWalks the class's properties, reads each attached PropertySpec, and
assembles a draft 2020-12 JSON Schema. Which properties take part is decided
by their declared role (see prop_role()), not by a list kept here:
"config" and "state" properties are generated from their spec, state
being marked readOnly, while "computed" and "r_only" properties are
omitted – the first because everything it derives from is published, the
second because it has no wire form at all. A spec-less property with no role
is an error, so a class that drifts from the factory vocabulary fails schema
generation.
S7_to_JSONSchema( x, id, title = NULL, description = "", base = NULL, required = NULL, record = FALSE, asserted = FALSE, provenance_url = NULL, session_url = NULL, fold_refs = NULL, metrics_refs = NULL, metrics_ref = NULL, reference_urls = NULL, closed = TRUE, instance_schema_url = NULL )S7_to_JSONSchema( x, id, title = NULL, description = "", base = NULL, required = NULL, record = FALSE, asserted = FALSE, provenance_url = NULL, session_url = NULL, fold_refs = NULL, metrics_refs = NULL, metrics_ref = NULL, reference_urls = NULL, closed = TRUE, instance_schema_url = NULL )
x |
S7 class (e.g. |
id |
Character: Schema |
title |
Character: Schema title. Defaults to the class name. |
description |
Character: Schema description. If empty, the "description" keyword is omitted from the schema. |
base |
S7 class or NULL: The family base class, whose inherited
properties are machinery ( |
required |
Character: Names of required properties. Default NULL: all
optional, so omitted fields fall back to their |
record |
Logical: If TRUE, emit the record form of the schema: the
same properties, but every one required. A record states what a run
actually used, so nothing in it may fall back to a reader's defaults – an
unset value is written as an explicit |
asserted |
Logical: If TRUE, emit an assertion schema: the input
form, but with every property required. For a results class – a document
rtemis produces rather than one a caller authors, and which has no record
sibling to carry the requirement. The config contract's reason for omitting
|
provenance_url |
Character or NULL: If set (and |
session_url |
Character or NULL: If set (and |
fold_refs |
Named character or NULL: If set (and |
metrics_refs |
Named character or NULL: If set (and |
metrics_ref |
Character or NULL: If set (and |
reference_urls |
Optional named character: Publication URLs keyed by qualified class identity. If omitted, derived from the package catalog. |
closed |
Logical: If TRUE (default) the schema sets
|
instance_schema_url |
Character or NULL: If set, adds a |
Named list: the JSON Schema. Serialize with write_JSONSchema.
EDG
## Not run: schema <- S7_to_JSONSchema( LightRFHyperparameters, id = "https://schema.rtemis.org/hyperparameters/r/lightrf/v1/schema.json", base = Hyperparameters ) ## End(Not run)## Not run: schema <- S7_to_JSONSchema( LightRFHyperparameters, id = "https://schema.rtemis.org/hyperparameters/r/lightrf/v1/schema.json", base = Hyperparameters ) ## End(Not run)
Two fingerprints are comparable only if they were produced the same way, so
this is FALSE when encoding or algorithm differ.
same_data(x, y)same_data(x, y)
x, y
|
|
Logical.
EDG
same_data(data_fingerprint(iris), data_fingerprint(iris))same_data(data_fingerprint(iris), data_fingerprint(iris))
Computes standard errors of the fit for newdata from the fitted model,
after applying the model's stored preprocessing.
se(x, newdata, ...)se(x, newdata, ...)
x |
|
newdata |
tabular data: Features to compute standard errors for. |
... |
Additional arguments passed to methods. |
Available for GLM and GAM, which report the standard error of the linear predictor, for BART, which reports the posterior standard deviation of the mean function, and for LINADForest, which reports the infinitesimal jackknife estimate. A multiclass GAM and every other algorithm return NULL.
Numeric vector of standard errors, one per case, or NULL when the algorithm reports none.
EDG
x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) se(mod, features(x)[1:5, ])x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) se(mod, features(x)[1:5, ])
Flatten the execution graph captured in a SupervisedSession (from
train()) into a timeline (Gantt) table: one row per recorded node, ordered
as a depth-first walk of the execution tree, with start/end offsets in
milliseconds from session start.
session_timeline(session)session_timeline(session)
session |
|
This is the single source of the tree-walk, labeling, and status logic for
timeline renderers. rtemis.server consumes it for the job.result
session slice, which the rtemislive web UI draws; pair it with
session_kind_colors() to color bars by node kind.
Nodes that never closed (status "running" or "aborted" with no end time)
are drawn up to the session finish time when known, else to the latest
recorded node start.
data.table with one row per node in depth-first order and columns:
label Character: Unique display label, indented two spaces per tree
depth (duplicates disambiguated with " #<n>" suffixes).
start Numeric: Node start, milliseconds from session start.
end Numeric: Node end, milliseconds from session start.
kind Character: Node kind (e.g. "tune", "grid_cell", "train_alg").
status Character {"ok", "error", "aborted", "running"}: Node status.
failed Logical: TRUE when status is "error" or "aborted".
tip Character: Preformatted tooltip text ("name -- duration [status]").
EDG
mod <- train(iris, hyperparameters = setup_CART()) # One row per recorded node, depth-first: the run, then the steps under it. session_timeline(mod@session)mod <- train(iris, hyperparameters = setup_CART()) # One row per recorded node, depth-first: the run, then the steps under it. session_timeline(mod@session)
Move outcome to last column
set_outcome(dat, outcome_column)set_outcome(dat, outcome_column)
dat |
tabular dataset. |
outcome_column |
Character: Name of outcome column. |
object of same class as data
EDG
ir <- set_outcome(iris, "Sepal.Length") head(ir)ir <- set_outcome(iris, "Sepal.Length") head(ir)
Checks and sets the positive class for binary classification in a tabular dataset.
set_positive_class(x, positive_class)set_positive_class(x, positive_class)
x |
Tabular data, i.e. data.frame, data.table, or tbl_df (tibble): Input dataset. The last column will be treated as the outcome variable. |
positive_class |
Character scalar: The name of the positive class. Must be one of the levels of the outcome variable. |
Tabular data of the same class as x, with the positive class set as the second level of the outcome factor.
EDG
dat <- data.frame(x = rnorm(100), y = factor(sample(c("Case", "Control"), 100, replace = TRUE))) levels(dat[["y"]]) dat <- set_positive_class(dat, "Case") levels(dat[["y"]])dat <- data.frame(x = rnorm(100), y = factor(sample(c("Case", "Control"), 100, replace = TRUE))) levels(dat[["y"]]) dat <- set_positive_class(dat, "Case") levels(dat[["y"]])
Symmetric Set Difference
setdiffsym(x, y)setdiffsym(x, y)
x |
vector |
y |
vector of same type as |
Vector.
EDG
setdiff(1:10, 1:5) setdiff(1:5, 1:10) setdiffsym(1:10, 1:5) setdiffsym(1:5, 1:10)setdiff(1:10, 1:5) setdiff(1:5, 1:10) setdiffsym(1:10, 1:5) setdiffsym(1:5, 1:10)
ARFFIngestConfig
Reading an ARFF file. Its header declares the attribute types.
setup_ARFFIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE )setup_ARFFIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE )
columns |
Optional Named vector: Declared column types, keyed by column
name, in the |
character2factor |
Logical: If TRUE, read character columns as factors. |
clean_colnames |
Logical: If TRUE, normalize column names. |
remove_duplicates |
Logical: If TRUE, drop rows repeating an earlier row. |
ARFFIngestConfig object.
EDG
setup_ARFFIngest()setup_ARFFIngest()
Setup the average silhouette width criterion for setup_PAMK: every candidate number of clusters is scored by the mean silhouette width over all cases, and the highest wins.
setup_ASWCriterion()setup_ASWCriterion()
ASWCriterionConfig object.
EDG
setup_ASWCriterion()setup_ASWCriterion()
A fully connected autoencoder built and trained with torch: an encoder maps
the features to k components through the hidden layers, and a decoder
mirroring it maps the components back.
setup_Autoencoder( k = 2L, hidden_units = NULL, activation = "relu", norm = NULL, dropout = 0, input_dropout = 0, weight_decay = 0, input_noise = 0, loss = "mse", optimizer = "adamw", lr = 0.001, beta1 = NULL, beta2 = NULL, eps = NULL, momentum = NULL, lr_scheduler = NULL, batch_size = NULL, max_epochs = 100L, patience = 10L, max_grad_norm = NULL, validation_fraction = 0.1, features = NULL )setup_Autoencoder( k = 2L, hidden_units = NULL, activation = "relu", norm = NULL, dropout = 0, input_dropout = 0, weight_decay = 0, input_noise = 0, loss = "mse", optimizer = "adamw", lr = 0.001, beta1 = NULL, beta2 = NULL, eps = NULL, momentum = NULL, lr_scheduler = NULL, batch_size = NULL, max_epochs = 100L, patience = 10L, max_grad_norm = NULL, validation_fraction = 0.1, features = NULL )
k |
Integer [1, Inf): Number of components, the width of the latent layer. |
|
Optional Integer [1, Inf) vector: Units in each hidden layer of the encoder, input side first. |
|
activation |
Character {"relu", "gelu", "silu", "elu", "selu", "leaky_relu", "tanh"}: Activation applied after every hidden layer. |
norm |
Optional Character {"batch_norm", "layer_norm"}: Normalization applied in every hidden layer. NULL applies none. |
dropout |
Numeric [0, 1): Dropout probability applied after every hidden layer. |
input_dropout |
Numeric [0, 1): Probability of zeroing each standardized input during training. |
weight_decay |
Numeric [0, Inf): L2 penalty, decoupled from the gradient under the adamw optimizer. |
input_noise |
Numeric [0, Inf): Standard deviation of the Gaussian noise added to the standardized inputs during training. |
loss |
Character {"mse", "l1", "smooth_l1"}: Reconstruction loss. |
optimizer |
Character {"adamw", "adam", "sgd", "rmsprop"}: Optimization algorithm. |
lr |
Numeric (0, Inf): Learning rate. |
beta1 |
Optional Numeric [0, 1): Exponential decay rate of the first moment estimate. Applies to the adam and adamw optimizers. |
beta2 |
Optional Numeric [0, 1): Exponential decay rate of the second moment estimate. Applies to the adam and adamw optimizers. |
eps |
Optional Numeric (0, Inf): Term added to the denominator for numerical stability. Applies to the adam, adamw and rmsprop optimizers. |
momentum |
Optional Numeric [0, Inf): Momentum factor. Applies to the sgd and rmsprop optimizers. |
lr_scheduler |
Optional Character {"step", "cosine_annealing", "one_cycle", "reduce_on_plateau"}: Learning-rate schedule. NULL holds the learning rate fixed. |
batch_size |
Optional Integer [1, Inf): Cases per optimization step. |
max_epochs |
Integer [1, Inf): Largest number of passes over the training cases. |
patience |
Integer [1, Inf): Epochs without improvement of the held-out loss before stopping early. |
max_grad_norm |
Optional Numeric (0, Inf): Clip the gradient norm to this value before each step. NULL does not clip. |
validation_fraction |
Numeric [0, 1): Fraction of the cases held out for early stopping. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
Architecture. hidden_units gives the encoder's hidden widths from the
input side, e.g. c(64L, 16L); the decoder uses them in reverse, and both
the latent layer and the output layer are linear. NULL uses one hidden
layer of width round(sqrt(p * k)) for p features, the geometric mean of
the input and latent widths, held between 32 and 512 and never below k.
batch_size = NULL uses a tenth of the training cases, held between 16 and
256, so small data still gets several optimization steps per epoch. The fit
reports and records both values it used.
Inputs are always centered and scaled with the training cases' statistics (a constant feature is only centered). reconstruct undoes this, so reconstructions and the reconstruction metrics are in the units of the data, comparable with any other decomposition's.
Denoising. input_noise adds Gaussian noise of that standard deviation to
the standardized inputs, and input_dropout zeroes each input with that
probability, during training only. The model learns to reconstruct the
uncorrupted input, which regularizes the components; apply_decomp and
reconstruct never corrupt.
Early stopping. validation_fraction of the cases, drawn at random, are
held out; training stops after patience epochs without improvement of
their reconstruction loss and keeps the weights of the best epoch. The
components are then computed for every case, held-out ones included.
validation_fraction = 0 trains for max_epochs.
Reproducibility, threads and device come from the execution config
passed to decomp: its seed seeds torch as well as R, its algorithm
threads are libtorch's thread count, and its device is the compute device.
Unset, the device is cuda where available and cpu otherwise. "mps",
the Apple silicon GPU, runs only when named. In rtemis benchmarks on an Apple
M5 the CPU fitted faster than "mps" in every configuration measured, up to
50,000 cases, 5,000 features, 1,024 hidden units and batches of 2,048, by
1.1 to 3.7 times; "mps" also slows down across many fits in one R
session. A seed does not reach dropout on "mps", so a seeded fit there
reproduces only while dropout and input_dropout are 0, and warns
otherwise.
The optimizer, schedule and early-stopping settings mean what they do in setup_MLP.
AutoencoderConfig object.
EDG
ae_config <- setup_Autoencoder(k = 2L, hidden_units = 8L, input_noise = 0.1) ae_configae_config <- setup_Autoencoder(k = 2L, hidden_units = 8L, input_noise = 0.1) ae_config
Setup hyperparameters for Bayesian Additive Regression Trees training.
setup_BART( num_trees = 200L, alpha = 0.95, beta = 2, min_samples_leaf = 5L, max_depth = 10L, num_features_subsample = NULL, variance_forest_num_trees = 0L, num_gfr = 5L, num_burnin = 0L, num_mcmc = 100L, num_chains = 1L, keep_every = 1L, cutpoint_grid_size = 100L, standardize = TRUE, link = "probit", seed = NULL, ifw = FALSE )setup_BART( num_trees = 200L, alpha = 0.95, beta = 2, min_samples_leaf = 5L, max_depth = 10L, num_features_subsample = NULL, variance_forest_num_trees = 0L, num_gfr = 5L, num_burnin = 0L, num_mcmc = 100L, num_chains = 1L, keep_every = 1L, cutpoint_grid_size = 100L, standardize = TRUE, link = "probit", seed = NULL, ifw = FALSE )
num_trees |
(Tunable) Integer [1, Inf): Number of trees in the mean forest. |
alpha |
(Tunable) Numeric (0, 1): Base of the tree split prior |
beta |
(Tunable) Numeric [0, Inf): Depth penalty exponent of the tree split prior |
min_samples_leaf |
(Tunable) Integer [1, Inf): Minimum number of training cases in a leaf. |
max_depth |
(Tunable) Optional Integer [1, Inf): Maximum depth of any tree. NULL imposes no limit. |
num_features_subsample |
(Tunable) Optional Integer [1, Inf): Number of features subsampled when growing each tree. NULL uses every feature. |
variance_forest_num_trees |
(Tunable) Integer [0, Inf): Number of trees in the conditional variance forest. 0 fits a homoskedastic model, any larger value a heteroskedastic one. |
num_gfr |
Integer [0, Inf): Number of grow-from-root warm-start iterations. |
num_burnin |
Integer [0, Inf): Number of burn-in MCMC iterations. |
num_mcmc |
Integer [1, Inf): Number of retained MCMC iterations per chain. |
num_chains |
Integer [1, Inf): Number of independent MCMC chains. Cannot exceed |
keep_every |
Integer [1, Inf): Thinning interval: retain one MCMC sample in every |
cutpoint_grid_size |
Integer [1, Inf): Maximum number of candidate cutpoints considered by the grow-from-root algorithm. |
standardize |
Logical: If TRUE, center and scale the outcome before sampling. |
link |
Character {"probit", "cloglog"}: Link function of the binary outcome model. Classification only. |
seed |
Optional Integer: Random seed for the sampler. NULL leaves the sampler seeded by the system. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Both outcome types are fit with stochtree::bart, which samples a sum-of-trees
model by MCMC, optionally warm-started by the grow-from-root algorithm.
Regression uses a continuous outcome model, binary classification a discrete
one with the link named by link. Multiclass classification is not supported.
Factors are expanded by the backend, so no encoding is needed beforehand.
Case weights scale the residual variance and are honored under the default
link = "probit", but stochtree rejects them under "cloglog", so that
combination makes training abort.
Because the fit is a posterior rather than a point estimate, se() returns
the standard deviation of the retained draws, and get_varimp() reports two
measures rather than one:
importance: the variable inclusion proportion, the share of splitting
rules that use the feature, averaged across draws.
inclusion_sd: its standard deviation across draws, separating a feature
the sampler uses consistently from one whose importance rests on a few
draws.
plot_varimp(mod, measure = "inclusion_sd") plots the second; the first is
the default.
Inclusion proportions only discriminate when trees compete for splits. At
the default num_trees each tree is a weak learner and uninformative
features still get used, so the proportions flatten towards 1/n_features;
refit with a small ensemble (num_trees = 10L to 20L) when the goal is
variable selection rather than prediction.
BARTHyperparameters object.
EDG
bart_hyperparams <- setup_BART(num_trees = 50L, num_mcmc = 200L) bart_hyperparamsbart_hyperparams <- setup_BART(num_trees = 50L, num_mcmc = 200L) bart_hyperparams
Setup Bootstrap Resampler
setup_Bootstrap(n_resamples = 10L, id_strat = NULL, seed = NULL)setup_Bootstrap(n_resamples = 10L, id_strat = NULL, seed = NULL)
n_resamples |
Integer [1, Inf): Number of resamples to make. |
id_strat |
Optional Character: Name of the column holding per-case grouping IDs, e.g.
subject IDs when the dataset contains repeated measurements. Cases sharing an ID stay in the
same resample, so a case can only be present in the training or the test set, not both.
Requires that |
seed |
Optional Integer [0, Inf): Random seed. |
BootstrapConfig object.
EDG
bootstrap_resampler <- setup_Bootstrap(n_resamples = 10L, seed = 2026L) bootstrap_resamplerbootstrap_resampler <- setup_Bootstrap(n_resamples = 10L, seed = 2026L) bootstrap_resampler
Setup hyperparameters for CART training.
setup_CART( cp = 0.01, maxdepth = 20L, minsplit = 2L, minbucket = 1L, prune_cp = NULL, method = "auto", model = TRUE, maxcompete = 4L, maxsurrogate = 5L, usesurrogate = 2L, surrogatestyle = 0L, xval = 0L, cost = NULL, ifw = FALSE )setup_CART( cp = 0.01, maxdepth = 20L, minsplit = 2L, minbucket = 1L, prune_cp = NULL, method = "auto", model = TRUE, maxcompete = 4L, maxsurrogate = 5L, usesurrogate = 2L, surrogatestyle = 0L, xval = 0L, cost = NULL, ifw = FALSE )
cp |
(Tunable) Numeric [0, Inf): Complexity parameter. |
maxdepth |
(Tunable) Integer [1, 30]: Maximum depth of tree. |
minsplit |
(Tunable) Integer [1, Inf): Minimum number of observations in a node to split. |
minbucket |
(Tunable) Integer [1, Inf): Minimum number of observations in a terminal node. |
prune_cp |
(Tunable) Optional Numeric [0, Inf): Complexity for cost-complexity pruning after tree is built. NULL prunes nothing after the tree is built. |
method |
Character {"auto", "anova", "class", "poisson", "exp"}: Splitting method. |
model |
Logical: If TRUE, keep a copy of the model frame. |
maxcompete |
Integer [0, Inf): Maximum number of competitive splits. |
maxsurrogate |
Integer [0, Inf): Maximum number of surrogate splits. |
usesurrogate |
Integer [0, 2]: Number of surrogate splits to use. |
surrogatestyle |
Integer [0, 1]: Type of surrogate splits. |
xval |
Integer [0, Inf): Number of cross-validation folds. |
cost |
Optional Numeric (0, Inf) vector: One for each feature. NULL uses 1 for every feature. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from rpart::rpart and rpart::rpart.control.
CARTHyperparameters object.
EDG
cart_hyperparams <- setup_CART(cp = 0.01, maxdepth = 10L, ifw = TRUE) cart_hyperparamscart_hyperparams <- setup_CART(cp = 0.01, maxdepth = 10L, ifw = TRUE) cart_hyperparams
Setup the Calinski-Harabasz criterion for setup_PAMK: every candidate number of clusters is scored by the ratio of between-cluster to within-cluster dispersion, and the highest wins.
setup_CHCriterion()setup_CHCriterion()
CHCriterionConfig object.
EDG
setup_CHCriterion()setup_CHCriterion()
Setup a ClusterConfig object. ClusterConfig is a portable, data-agnostic
recipe for a clustering pipeline: dat_path is optional, so the same config
can be validated, shared, or described without data and have a path bound
later (e.g. by the rtemis CLI) before cluster.
setup_ClusterConfig( dat_path = NULL, clustering_config = NULL, execution_config = setup_FutureExecution(), outdir = "results/", verbosity = 1L )setup_ClusterConfig( dat_path = NULL, clustering_config = NULL, execution_config = setup_FutureExecution(), outdir = "results/", verbosity = 1L )
dat_path |
Character or NULL: Path to input data file. NULL leaves the recipe unbound; set it (or supply data) before cluster. |
clustering_config |
|
execution_config |
|
outdir |
Character: Output directory for results. |
verbosity |
Integer [0, Inf): Verbosity level. |
ClusterConfig object.
EDG
cc <- setup_ClusterConfig( dat_path = "data.csv", clustering_config = setup_KMeans(k = 3L), outdir = "results/" )cc <- setup_ClusterConfig( dat_path = "data.csv", clustering_config = setup_KMeans(k = 3L), outdir = "results/" )
Setup CMeansConfig
setup_CMeans( k = 2L, max_iter = 100L, dist = "euclidean", method = "cmeans", m = 2, rate_par = NULL, weights = 1, control = list(), features = NULL )setup_CMeans( k = 2L, max_iter = 100L, dist = "euclidean", method = "cmeans", m = 2, rate_par = NULL, weights = 1, control = list(), features = NULL )
k |
Integer [1, Inf): Number of clusters. |
max_iter |
Integer [1, Inf): Maximum number of iterations. |
dist |
Character {"euclidean", "manhattan"}: Distance measure to use. |
method |
Character {"cmeans", "ufcl"}: "cmeans" - fuzzy c-means clustering; "ufcl": on-line update. |
m |
Numeric (1, Inf): Degree of fuzzification. |
rate_par |
Optional Numeric [0, 1]: Learning rate for the online variant. |
weights |
Numeric vector: Case weights. Either a scalar, applied to every case, or a vector with one value per case. |
control |
List: Control config for clustering algorithm. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
CMeansConfig object.
EDG
cmeans_config <- setup_CMeans(k = 4L, dist = "euclidean") cmeans_configcmeans_config <- setup_CMeans(k = 4L, dist = "euclidean") cmeans_config
Setup hyperparameters for the Conditional SuperLearner, which selects the best model from a library conditional on the covariates rather than combining them.
setup_ConditionalSuperLearner( base_learners = list(setup_GLM(), setup_GLMNET(), setup_Ranger()), meta_learner = setup_Ranger(), inner_resampling_config = setup_KFold(n_resamples = 10L), n_iterations = 4L, loss = NULL, init = "full", min_region_size = 10L, expand_search_spaces = TRUE, ifw = FALSE )setup_ConditionalSuperLearner( base_learners = list(setup_GLM(), setup_GLMNET(), setup_Ranger()), meta_learner = setup_Ranger(), inner_resampling_config = setup_KFold(n_resamples = 10L), n_iterations = 4L, loss = NULL, init = "full", min_region_size = 10L, expand_search_spaces = TRUE, ifw = FALSE )
base_learners |
List of |
meta_learner |
|
inner_resampling_config |
|
n_iterations |
(Tunable) Integer [1, Inf): Alternations between fitting the oracle and refitting the experts. |
loss |
Optional Character {"squared_error", "log_loss"}: Per-case loss the oracle minimizes. |
init |
Character {"full", "random"}: Region each expert starts from. |
min_region_size |
Integer [1, Inf): Fewest cases an expert's region may hold before the expert keeps its previous fit instead of being refitted. |
expand_search_spaces |
Logical: If TRUE, expand a base learner's search space into one expert per combination. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
The model is sum_k 1\{o(x) = k\} F_k(x): an "oracle" o assigns each case to
one of the K "experts" F_k, and that expert predicts it. Oracle and experts
are fitted by alternating, in the manner of k-means: with the experts fixed,
the oracle minimizes the total loss, which reduces to a weighted K-class
classification over an extended dataset holding each case once per expert; with
the oracle fixed, each expert is refitted on the cases assigned to it. The
losses are cross-validated throughout, so an expert is never scored on a case
it was trained on.
The oracle is a classifier over the original covariates whatever the outcome is, so with more than two experts it must handle more than two classes. Its variable importance – which covariates decide which model applies – is what get_varimp returns for a fitted model, and a simple oracle such as setup_CART makes the partition itself readable.
Supports regression and binary classification.
Reference: Valdes, Interian, Gennatas & van der Laan, "Conditional Super Learner", IEEE Transactions on Pattern Analysis and Machine Intelligence (2022). doi:10.1109/TPAMI.2021.3131976
ConditionalSuperLearnerHyperparameters object.
EDG
csl_hyperparams <- setup_ConditionalSuperLearner( base_learners = list(setup_GLM(), setup_CART()) ) csl_hyperparamscsl_hyperparams <- setup_ConditionalSuperLearner( base_learners = list(setup_GLM(), setup_CART()) ) csl_hyperparams
Configure conformalized quantile regression for conformal.
setup_CQR(alpha = 0.1)setup_CQR(alpha = 0.1)
alpha |
Numeric (0, 1): Miscoverage rate. Also sets the quantile levels
queried, |
Split conformal adds and subtracts one number, so every case gets the same
width whether the model is confident or not. CQR (Romano, Patterson and
Candes, 2019) starts from the model's own alpha/2 and 1 - alpha/2
quantiles and conformalizes the pair with the score
max(qlo - y, y - qhi), which widens or narrows both ends by one calibrated
amount. Adaptive width, same finite-sample guarantee.
It needs a backend that answers a quantile query from the model already
fitted. Today that is Ranger trained with setup_Ranger(quantreg = TRUE):
a quantile regression forest keeps the training outcomes at its terminal
nodes, so one fit answers every level. A gradient booster on the quantile
objective targets the single level it was trained for, so a pair of bounds
would be a pair of models – a training configuration, not something
conformal() can do to a model it is handed.
It always needs calibration data. A Supervised stores its test
predictions but not its test features, and CQR must query the model for
quantiles at the calibration cases, so the stored-split default does not
apply here.
CQRConfig object.
EDG
setup_CQR() setup_CQR(alpha = 0.05)setup_CQR() setup_CQR(alpha = 0.05)
Request an NVIDIA GPU through CUDA as the compute device of an execution
config, naming which GPUs to use, e.g.
setup_FutureExecution(device = setup_CUDA(ids = 1L)). Without ids,
device = "cuda" is the same request. Algorithms that run on CUDA are the torch-backed ones
(MLP, TabNet) and the LightGBM family built with CUDA support; every other
algorithm runs on the CPU.
setup_CUDA(ids = NULL)setup_CUDA(ids = NULL)
ids |
Optional Integer [0, Inf) vector: Zero-based indices of the GPUs to
use. |
CUDADeviceConfig object.
EDG
setup_CUDA() setup_CUDA(ids = 1L)setup_CUDA() setup_CUDA(ids = 1L)
Setup Custom Resampler
setup_Custom(resamples = NULL)setup_Custom(resamples = NULL)
resamples |
Optional List: Resamples to use, one integer vector of training-case indices per resample. |
CustomConfig object.
EDG
custom_resampler <- setup_Custom(resamples = list(1:3, 2:4)) custom_resamplercustom_resampler <- setup_Custom(resamples = list(1:3, 2:4)) custom_resampler
Configure CV+, jackknife+ and cross-conformal prediction for conformal over a model trained with outer resampling.
setup_CVPlus(alpha = 0.1, score = NULL, seed = NULL)setup_CVPlus(alpha = 0.1, score = NULL, seed = NULL)
alpha |
Numeric (0, 1): Miscoverage rate. The region covers with
probability at least |
score |
Optional Character {"absolute", "LAC", "APS"}: Nonconformity score. NULL resolves to "absolute" for a regression and "APS" for a classification. See setup_SplitConformal for the trade between the two set-valued scores, and for why APS draws. |
seed |
Optional Integer [0, Inf): Random seed for the APS draw. NULL draws one and records it. |
CV+ (Barber, Candes, Ramdas and Tibshirani, 2021) spends no data on
calibration: every case is out-of-fold exactly once, so every case both
trains and calibrates. Over a SupervisedRes the expensive part is already
paid – the per-fold models and their out-of-fold predictions are stored –
and what remains is predicting newdata under each fold's model and taking
two order statistics.
It delivers 1 - 2 * alpha in the worst case, not 1 - alpha. The bound
is conservative and observed coverage usually sits near 1 - alpha; the
region states the guarantee it carries.
The folds must partition the cases, each case out-of-fold exactly once.
setup_KFold() and setup_LOOCV() do; the subsampling and
bootstrap types do not, and conformal() refuses them by checking the
indices.
Which relative runs follows from the object: leave-one-out folds make it jackknife+, and a classification outcome makes it cross-conformal (Vovk, 2015), CV+ being defined for intervals. The result records which.
CVPlusConfig object.
EDG
setup_CVPlus() setup_CVPlus(alpha = 0.2)setup_CVPlus() setup_CVPlus(alpha = 0.2)
Setup DBSCANConfig
setup_DBSCAN( eps = 0.5, min_points = 5L, weights = NULL, border_points = TRUE, search = "kdtree", bucket_size = 100L, split_rule = "SUGGEST", approx = 0, features = NULL )setup_DBSCAN( eps = 0.5, min_points = 5L, weights = NULL, border_points = TRUE, search = "kdtree", bucket_size = 100L, split_rule = "SUGGEST", approx = 0, features = NULL )
eps |
Numeric (0, Inf): Radius of neighborhood. |
min_points |
Integer [1, Inf): Minimum number of points in a neighborhood to form a cluster. |
weights |
Optional Numeric vector: Weights for data points. |
border_points |
Logical: If TRUE, assign border points to clusters. |
search |
Character {"kdtree", "linear", "dist"}: Nearest neighbor search strategy. |
bucket_size |
Integer [1, Inf): Size of buckets for k-d tree search. |
split_rule |
Character {"SUGGEST", "STD", "MIDPT", "FAIR", "SL_MIDPT", "SL_FAIR"}: Rule for splitting the k-d tree. |
approx |
Numeric [0, Inf): Approximation factor for the nearest neighbor
search ( |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
DBSCANConfig object.
EDG
dbscan_config <- setup_DBSCAN(eps = 0.5, min_points = 5L) dbscan_configdbscan_config <- setup_DBSCAN(eps = 0.5, min_points = 5L) dbscan_config
Setup a DecomposeConfig object. DecomposeConfig is a portable,
data-agnostic recipe for a decomposition pipeline: dat_path is optional, so
the same config can be validated, shared, or described without data and have a
path bound later (e.g. by the rtemis CLI) before decomp.
setup_DecomposeConfig( dat_path = NULL, decomposition_config = NULL, execution_config = setup_FutureExecution(), outdir = "results/", verbosity = 1L )setup_DecomposeConfig( dat_path = NULL, decomposition_config = NULL, execution_config = setup_FutureExecution(), outdir = "results/", verbosity = 1L )
dat_path |
Character or NULL: Path to input data file. NULL leaves the recipe unbound; set it (or supply data) before decomp. |
decomposition_config |
|
execution_config |
|
outdir |
Character: Output directory for results. |
verbosity |
Integer [0, Inf): Verbosity level. |
DecomposeConfig object.
EDG
dc <- setup_DecomposeConfig( dat_path = "data.csv", decomposition_config = setup_PCA(k = 3L), outdir = "results/" )dc <- setup_DecomposeConfig( dat_path = "data.csv", decomposition_config = setup_PCA(k = 3L), outdir = "results/" )
DelimitedIngestConfig
Reading a delimited file – the format that declares nothing, and therefore the one with the most to say.
One constructor per format: each takes exactly the settings its format has, so an argument from another format is rejected by R as unused, and each format's own enums and defaults can be documented against the class they belong to.
setup_DelimitedIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE, reader = "data.table", sep = NULL, quote = "\"", na_strings = "" )setup_DelimitedIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE, reader = "data.table", sep = NULL, quote = "\"", na_strings = "" )
columns |
Optional Named vector: Declared column types, keyed by column
name, in the |
character2factor |
Logical: If TRUE, read character columns as factors. |
clean_colnames |
Logical: If TRUE, normalize column names. |
remove_duplicates |
Logical: If TRUE, drop rows repeating an earlier row. |
reader |
Character {"data.table", "vroom", "duckdb", "arrow"}: Library used to read the file. |
sep |
Optional Character: Field separator. If |
quote |
Character: Quote character. |
na_strings |
Character vector: Strings to read as missing. |
DelimitedIngestConfig object.
EDG
setup_DelimitedIngest(sep = ";")setup_DelimitedIngest(sep = ";")
DTAIngestConfig
Reading a Stata file. Its types are declared in the file.
setup_DTAIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE )setup_DTAIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE )
columns |
Optional Named vector: Declared column types, keyed by column
name, in the |
character2factor |
Logical: If TRUE, read character columns as factors. |
clean_colnames |
Logical: If TRUE, normalize column names. |
remove_duplicates |
Logical: If TRUE, drop rows repeating an earlier row. |
DTAIngestConfig object.
EDG
setup_DTAIngest()setup_DTAIngest()
FutureExecutionConfig
Parallel execution through future. A plan is required, and is filled in
from getOption("future.plan", "mirai_multisession") when not given.
setup_FutureExecution( n_workers = NULL, n_workers_outer = NULL, n_workers_tuning = NULL, n_workers_algorithm = NULL, device = NULL, future_plan = getOption("future.plan", "mirai_multisession"), on_error = c("continue", "stop", "stop_outer"), seed = NULL, shared_memory = c("auto", "none", "always") )setup_FutureExecution( n_workers = NULL, n_workers_outer = NULL, n_workers_tuning = NULL, n_workers_algorithm = NULL, device = NULL, future_plan = getOption("future.plan", "mirai_multisession"), on_error = c("continue", "stop", "stop_outer"), seed = NULL, shared_memory = c("auto", "none", "always") )
n_workers |
Integer [1, Inf): Number of parallel workers. Left |
n_workers_outer |
Optional Integer [1, Inf): Workers for outer resampling, overriding the automatic assignment. |
n_workers_tuning |
Optional Integer [1, Inf): Workers for tuning, overriding the automatic assignment. |
n_workers_algorithm |
Optional Integer [1, Inf): Threads for a self-parallelizing algorithm, overriding the automatic assignment. |
device |
Optional |
future_plan |
Character: Future plan to use. Defaults to
|
on_error |
Character {"continue", "stop", "stop_outer"}: Failure policy.
|
seed |
Optional Integer [0, Inf): Master seed for the run's computation RNG,
from which one independent substream per parallel task is derived. Left |
shared_memory |
Character {"none", "auto", "always"}: Whether to hand workers
the training data through OS shared memory instead of serializing a copy to each.
|
Worker levels
There are three levels that can absorb workers: a self-parallelizing algorithm,
tuning, and outer resampling. Left alone, n_workers is assigned to exactly one of
them, in that order of priority, so no two levels compete for the same cores.
Naming any of n_workers_outer, n_workers_tuning or n_workers_algorithm takes
over that assignment: the automatic one is switched off entirely and any level not
named gets 1, so a run never mixes a hand-picked level with an inferred one.
Outer resampling and tuning dispatch to worker processes, and an outer fold runs
inside one of those processes, so only one of the two can be parallel – setting both
above 1 is an error. n_workers_algorithm is threads within a worker, so it combines
with either.
Reproducibility
Substreams are assigned by task index, so a run gives the same answer under every backend and worker count, and the parallel result matches the sequential one exactly.
Shared memory needs mori, whose minimum R version (4.3) is above
rtemis's own (4.1), so "auto" is the portable setting for a script that may
run anywhere. It is local RAM: workers on another machine cannot map it.
FutureExecutionConfig object.
EDG
setup_FutureExecution(n_workers = 4L, future_plan = "multisession")setup_FutureExecution(n_workers = 4L, future_plan = "multisession")
Setup hyperparameters for GAM training.
setup_GAM(k = 5L, ifw = FALSE)setup_GAM(k = 5L, ifw = FALSE)
k |
(Tunable) Integer [1, Inf): Number of knots. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from mgcv::gam.
GAMHyperparameters object.
EDG
gam_hyperparams <- setup_GAM(k = 5L, ifw = FALSE) gam_hyperparamsgam_hyperparams <- setup_GAM(k = 5L, ifw = FALSE) gam_hyperparams
Setup hyperparameters for GLM training.
setup_GLM(ifw = FALSE)setup_GLM(ifw = FALSE)
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
GLMHyperparameters object.
EDG
glm_hyperparams <- setup_GLM(ifw = TRUE) glm_hyperparamsglm_hyperparams <- setup_GLM(ifw = TRUE) glm_hyperparams
Setup hyperparameters for GLMNET training.
setup_GLMNET( alpha = 1, family = NULL, which_lambda_cv = "lambda.1se", nlambda = 100L, lambda = NULL, penalty_factor = NULL, standardize = TRUE, intercept = TRUE, ifw = TRUE )setup_GLMNET( alpha = 1, family = NULL, which_lambda_cv = "lambda.1se", nlambda = 100L, lambda = NULL, penalty_factor = NULL, standardize = TRUE, intercept = TRUE, ifw = TRUE )
alpha |
(Tunable) Numeric [0, 1]: Elastic net mixing parameter. |
family |
Optional Character {"gaussian", "binomial", "poisson", "multinomial", "cox", "mgaussian"}: Family. NULL = set from outcome type. |
which_lambda_cv |
Character {"lambda.1se", "lambda.min"}: Which lambda to use for prediction. |
nlambda |
Integer [1, Inf): Number of lambda values. |
lambda |
Optional Numeric [0, Inf) vector: Lambda values. NULL = determined by cv.glmnet during tuning. |
penalty_factor |
Optional Numeric [0, Inf) vector: Penalty factor for each design-matrix column (factors expanded to indicator columns). NULL uses 1 for every column. |
standardize |
Logical: If TRUE, standardize features. |
intercept |
Logical: If TRUE, include intercept. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from glmnet::glmnet.
GLMNETHyperparameters object.
EDG
glm_hyperparams <- setup_GLMNET(alpha = 1, ifw = TRUE) glm_hyperparamsglm_hyperparams <- setup_GLMNET(alpha = 1, ifw = TRUE) glm_hyperparams
Setup hyperparameters for GLMTree: model-based recursive partitioning, a tree carrying a generalized linear model in each leaf.
setup_GLMTree( alpha = 0.05, minsize = NULL, maxdepth = NULL, mtry = NULL, trim = 0.1, prune = NULL, numsplit = "left", catsplit = "binary", ordinal = "chisq", ifw = FALSE, regressors = NULL, partitioning_variables = NULL, bonferroni = TRUE, breakties = FALSE, restart = TRUE, dfsplit = TRUE, vcov = "opg", nrep = 10000L )setup_GLMTree( alpha = 0.05, minsize = NULL, maxdepth = NULL, mtry = NULL, trim = 0.1, prune = NULL, numsplit = "left", catsplit = "binary", ordinal = "chisq", ifw = FALSE, regressors = NULL, partitioning_variables = NULL, bonferroni = TRUE, breakties = FALSE, restart = TRUE, dfsplit = TRUE, vcov = "opg", nrep = 10000L )
alpha |
(Tunable) Numeric (0, 1]: Significance level a parameter-instability test must reach before a node is split. |
minsize |
(Tunable) Optional Integer [1, Inf): Fewest cases a node may hold. NULL uses ten times the number of parameters in a leaf's model. |
maxdepth |
(Tunable) Optional Integer [1, Inf): Deepest the tree may grow. NULL is unlimited. |
mtry |
(Tunable) Optional Integer [1, Inf): Partitioning variables sampled at each node. NULL tests every one. |
trim |
(Tunable) Numeric [0, Inf): Trimming for the split-point search; a fraction of cases below 1, a count at or above it. |
prune |
(Tunable) Optional Character {"AIC", "BIC"}: Post-prune the grown tree by an information criterion. NULL keeps every split. |
numsplit |
(Tunable) Character {"left", "center"}: Where a numeric split is placed. |
catsplit |
(Tunable) Character {"binary", "multiway"}: How a categorical variable is split. |
ordinal |
(Tunable) Character {"chisq", "max", "L2"}: Test statistic for an ordered partitioning variable. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
regressors |
Optional Character vector: Features entering the linear model in each leaf. NULL uses every feature. |
partitioning_variables |
Optional Character vector: Features the tree may split on. NULL uses every feature. |
bonferroni |
Logical: If TRUE, Bonferroni-adjust the test p-values for the number of partitioning variables. |
breakties |
Logical: If TRUE, break ties in numeric partitioning variables by adding noise. |
restart |
Logical: If TRUE, restart each leaf's model from scratch rather than from its parent's fit. |
dfsplit |
Logical: If TRUE, count each split against the degrees of freedom when pruning. |
vcov |
Character {"opg", "info", "sandwich"}: Covariance estimator the instability test is built on. |
nrep |
Integer [1, Inf): Simulation replicates for the p-value of an ordinal split statistic. |
Where a decision tree predicts a constant in each leaf, a GLMTree fits a
regression there, so the model reads as "in this subgroup, these are the
coefficients". partykit::lmtree() fits a regression, partykit::glmtree()
a binary logistic one; rtemis selects between them from the outcome.
GLMTreeHyperparameters object.
Not by loss reduction. A node is split when a parameter-instability test
says its model's coefficients are not constant across a candidate
partitioning variable – a structural change test, at significance level
alpha. That is the method's distinguishing feature and the source of both
its strengths and its limits:
Splits carry p-values, and
alpha is a significance level with a direct interpretation.
Which a tree splitting on the response cannot: there is nothing in the mean to find.
With few cases, many partitioning
variables, or both, the tests do not reach alpha and the tree does not
split at all – returning a single global model.
minsize before alpha
The default minsize is ten times the number of parameters in a leaf's
model, and that scales with the number of regressors. A split has to leave
minsize cases on each side, so with p regressors no split is possible
below n = 20 * (p + 1) – 420 cases at 20 regressors, whatever alpha
says. A tree that returns one leaf on a wide design has usually hit this,
not the significance level, and raising alpha will not move it. Set
minsize directly, or narrow regressors.
regressors and partitioning_variables are separable, and the separation
is the point: the model in each leaf need not read the variables the tree
splits on. Both default to every feature.
Every leaf carries a full model over regressors – there is no selection or
shrinkage, so a leaf holds one coefficient per regressor whether or not it
earned one. Restrict regressors to keep that number down.
No variable-importance measure: partykit has one for cforest and for
constant-fit trees, and none for a model-based tree. get_varimp() therefore
returns NULL, and get_varimp(explain(mod, newdata)) is the route to a
per-feature measure.
EDG
Zeileis A, Hothorn T, Hornik K (2008). Model-Based Recursive Partitioning. Journal of Computational and Graphical Statistics, 17(2), 492-514. doi:10.1198/106186008X319331
glmtree_hyperparams <- setup_GLMTree(alpha = 0.01) glmtree_hyperparamsglmtree_hyperparams <- setup_GLMTree(alpha = 0.01) glmtree_hyperparams
Setup a GMMConfig object for Gaussian Mixture Model clustering, via the
'mclust' package.
setup_GMM(k = NULL, model_names = NULL, features = NULL)setup_GMM(k = NULL, model_names = NULL, features = NULL)
k |
Optional Integer [1, Inf): Number of mixture components. Unset selects it by BIC. |
model_names |
Optional Character {"EII", "VII", "EEI", "VEI", "EVI", "VVI", "EEE", "VEE", "EVE", "VVE", "EEV", "VEV", "EVV", "VVV"} vector: Covariance parameterizations to consider. Unset considers all of them. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
A GMM is the model-based counterpart of the prototype methods: each cluster is a Gaussian component with its own mean and covariance, so clusters may be elongated, differently oriented and differently sized, and every case gets a posterior probability for each component as well as a label. The result is therefore a soft clustering.
Both the number of components and the covariance parameterization are
selected by BIC, which makes k optional: leave it unset to have the number
of components chosen, or set it to fix the number and let BIC choose only the
parameterization.
Argument names are rtemis' own: k is mclust::Mclust()'s G and
model_names is its modelNames.
GMMConfig object.
EDG
Scrucca L, Fop M, Murphy TB, Raftery AE (2016). mclust 5: Clustering, Classification and Density Estimation Using Gaussian Finite Mixture Models. The R Journal, 8(1), 289-317. doi:10.32614/RJ-2016-021
gmm_config <- setup_GMM(k = 3L) gmm_configgmm_config <- setup_GMM(k = 3L) gmm_config
Create a GridSearchConfig object that can be passed to train.
setup_GridSearch( resampler_config = setup_KFold(n_resamples = 5L), search_type = "exhaustive", randomize_p = NULL, metrics_aggregate_fn = "mean", metric = NULL, maximize = NULL )setup_GridSearch( resampler_config = setup_KFold(n_resamples = 5L), search_type = "exhaustive", randomize_p = NULL, metrics_aggregate_fn = "mean", metric = NULL, maximize = NULL )
resampler_config |
Optional |
search_type |
Character {"exhaustive", "randomized"}: Type of
grid search to use. Exhaustive search will try all combinations of
config. Randomized will try a random sample of size
|
randomize_p |
Optional Numeric (0, 1): Randomly test this proportion of
combinations. Required when |
metrics_aggregate_fn |
Character: Name of function to use to aggregate error metrics. |
metric |
Optional Character: Metric to minimize or maximize. NULL sets it from the outcome type. |
maximize |
Optional Logical: If TRUE, maximize |
A GridSearchConfig object.
EDG
gridsearch_config <- setup_GridSearch( resampler_config = setup_KFold(n_resamples = 5L), search_type = "exhaustive" ) gridsearch_configgridsearch_config <- setup_GridSearch( resampler_config = setup_KFold(n_resamples = 5L), search_type = "exhaustive" ) gridsearch_config
GroupPartitionConfig
A split that keeps every case sharing a group ID on the same side.
setup_GroupPartition(column = NULL, train_p = 0.75, seed = NULL)setup_GroupPartition(column = NULL, train_p = 0.75, seed = NULL)
column |
Optional Character: Name of the column holding per-case group IDs. |
train_p |
Numeric (0, 1): Approximate training set fraction, honored at the group level. |
seed |
Optional Integer [0, Inf): Random seed. |
GroupPartitionConfig object.
EDG
setup_GroupPartition(column = "subject_id", train_p = 0.8, seed = 2026L)setup_GroupPartition(column = "subject_id", train_p = 0.8, seed = 2026L)
Setup hyperparameters for Highly Adaptive Lasso training.
setup_HAL( max_degree = 2L, smoothness_orders = 1L, reduce_basis = NULL, num_knots = NULL, use_min = TRUE, nfolds = 10L, max_basis = 5000000L, seed = NULL, ifw = FALSE )setup_HAL( max_degree = 2L, smoothness_orders = 1L, reduce_basis = NULL, num_knots = NULL, use_min = TRUE, nfolds = 10L, max_basis = 5000000L, seed = NULL, ifw = FALSE )
max_degree |
(Tunable) Integer [1, Inf): Highest order of interaction among features that a basis function may represent. |
smoothness_orders |
(Tunable) Integer [0, 9]: Smoothness of the basis functions: 0 fits zero-order indicators, 1 piecewise linear splines, higher values higher-order splines. |
reduce_basis |
(Tunable) Optional Numeric (0, 1]: Minimum proportion of cases a basis function must be non-zero in to be kept. Applies only when |
num_knots |
Optional Integer [1, Inf) vector: Number of knots per interaction degree, one value per degree, non-increasing. NULL generates them from max_degree and smoothness_orders. |
use_min |
Logical: If TRUE, select |
nfolds |
Integer [3, Inf): Number of folds of the internal cross-validation that selects lambda. |
max_basis |
Integer [1, Inf): Largest projected basis-function count that will be fit. |
seed |
Optional Integer: Random seed for the internal cross-validation's fold assignment. NULL leaves it drawn from the ambient RNG. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Both outcome types are fit with hal9001::fit_hal, which spans the outcome
with a basis of indicator or spline terms over every interaction of the
features up to max_degree, then fits a lasso over that basis.
Regression uses the gaussian family, binary classification the binomial one;
hal9001 has no multinomial family, so multiclass classification is not
supported.
lambda is selected by cross-validation inside the fit and is not a search
dimension. seed fixes that cross-validation's fold assignment; nfolds
and use_min control it.
hal9001 takes a numeric matrix, so factors are one-hot encoded first and
the encoder is re-applied at predict time.
Scaling: the basis has one function per knot per feature subset, so its size
grows as C(n_features, max_degree) and, through the knots, with the number
of cases – making the lasso that follows quadratic in the number of cases.
Training projects the basis size up front, reports it at verbosity >= 1,
warns past a million, and aborts past max_basis. max_degree is the
strongest lever on that count, num_knots the next.
get_varimp() reports two measures, both aggregated over the basis
functions that involve each feature:
importance: the sum of the absolute values of their non-zero
coefficients.
max_coefficient: the largest single such absolute coefficient,
separating a feature carried by one strong term from one carried by many
weak ones.
plot_varimp(mod, measure = "max_coefficient") plots the second; the first
is the default. Both read coefficients on the scale of the basis functions.
At smoothness_orders = 0 the basis is made of indicators, so the
coefficients are unit-free and directly comparable across features; at
higher orders each basis function carries the units of its feature, so scale
the features first if they are not already comparable.
HALHyperparameters object.
EDG
hal_hyperparams <- setup_HAL(max_degree = 1L) hal_hyperparamshal_hyperparams <- setup_HAL(max_degree = 1L) hal_hyperparams
Setup HardCLConfig
setup_HardCL(k = 3L, dist = "euclidean", features = NULL)setup_HardCL(k = 3L, dist = "euclidean", features = NULL)
k |
Integer [1, Inf): Number of clusters. |
dist |
Character {"euclidean", "manhattan"}: Distance measure to use. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
HardCLConfig object.
EDG
hardcl_config <- setup_HardCL(k = 4L, dist = "euclidean") hardcl_confighardcl_config <- setup_HardCL(k = 4L, dist = "euclidean") hardcl_config
Setup a HOPACHConfig object for Hierarchical Ordered Partitioning and
Collapsing Hybrid (HOPACH) clustering, via the Bioconductor package
'hopach'.
setup_HOPACH( dist = "cosangle", level_selection = "best", max_levels = 15L, max_children = 9L, max_children_mss = 9L, collapse = "seq", new_medoid = "medsil", mss = "med", min_improvement = 0, initial_order = "co", element_order = "own", features = NULL )setup_HOPACH( dist = "cosangle", level_selection = "best", max_levels = 15L, max_children = 9L, max_children_mss = 9L, collapse = "seq", new_medoid = "medsil", mss = "med", min_improvement = 0, initial_order = "co", element_order = "own", features = NULL )
dist |
Character {"cosangle", "abscosangle", "euclid", "cor", "abscor"}: Distance measure. |
level_selection |
Character {"best", "greedy"}: Which level of the tree becomes the returned partition. "best": the level minimizing MSS; "greedy": the first level below which MSS increases. |
max_levels |
Integer [1, 15]: Maximum number of levels in the tree. |
max_children |
Integer [2, 9]: Maximum number of children at each node. |
max_children_mss |
Integer [2, 9]: Maximum number of children at each node when computing MSS. |
collapse |
Character {"seq", "all"}: How collapsing is performed at each level. "seq": collapse pairs sequentially from the closest while MSS decreases; "all": collapse any pair that decreases MSS. |
new_medoid |
Character {"medsil", "center", "nn", "uwnn"}: How the medoid of a collapsed pair is chosen. |
mss |
Character {"med", "mean"}: Split silhouette criterion; median or mean. |
min_improvement |
Numeric [0, 1]: Relative improvement in MSS required to accept a collapse step. |
initial_order |
Character {"co", "clust"}: How clusters in the first level are ordered. |
element_order |
Character {"own", "neighbor"}: How elements are ordered within a cluster. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
HOPACH identifies the number of clusters itself, by building an ordered
hierarchical tree and selecting the level with maximally homogeneous
clusters under the Median (or Mean) Split Silhouette criterion. There is
therefore no k to set: max_levels and max_children bound the tree, and
the number of clusters found is reported by the resulting Clustering.
Argument names are rtemis' own. They map to hopach::hopach() as:
dist -> d, level_selection -> clusters, max_levels -> K,
max_children -> kmax, max_children_mss -> khigh,
collapse -> coll, new_medoid -> newmed, mss -> mss,
min_improvement -> impr, initial_order -> initord,
element_order -> ord.
Two values hopach documents are not offered, because neither works:
d = "abseuclid", which distancematrix() has no branch for, and
ord = "co", which errors for every input.
On some datasets hopach collapses its tree all the way to a single
cluster and cannot split it further, which ends the run with an error.
Whether it happens depends on the data and on dist, so another dist
clusters the same data.
HOPACHConfig object.
EDG
van der Laan MJ, Pollard KS (2003). A new algorithm for hybrid hierarchical clustering with visualization and the bootstrap. Journal of Statistical Planning and Inference, 117(2), 275-303. doi:10.1016/S0378-3758(02)00388-9
hopach_config <- setup_HOPACH(dist = "euclid", max_levels = 3L) hopach_confighopach_config <- setup_HOPACH(dist = "euclid", max_levels = 3L) hopach_config
Setup ICA config.
setup_ICA( k = 3L, type = "parallel", fun = "logcosh", alpha = 1, row_norm = TRUE, maxit = 100L, tol = 1e-04, features = NULL )setup_ICA( k = 3L, type = "parallel", fun = "logcosh", alpha = 1, row_norm = TRUE, maxit = 100L, tol = 1e-04, features = NULL )
k |
Integer [1, Inf): Number of components. |
type |
Character {"parallel", "deflation"}: Type of ICA. |
fun |
Character {"logcosh", "exp"}: ICA function. |
alpha |
Numeric [1, 2]: Used in approximation to neg-entropy with |
row_norm |
Logical: If TRUE, standardize each case across features
before ICA, i.e. subtract each case's mean and divide by its standard
deviation. Appropriate when the features share units and each case's overall
level and scale are a nuisance rather than signal, as for spectra or assays
whose total intensity varies by sample – the usual situation for the wide,
single-instrument matrices decomposition is run on, which is why it is the
default. It spends two degrees of freedom per case, so its cost is roughly
|
maxit |
Integer [1, Inf): Maximum number of iterations. |
tol |
Numeric [0, Inf): Tolerance. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
ICAConfig object.
EDG
ica_config <- setup_ICA(k = 3L) ica_configica_config <- setup_ICA(k = 3L) ica_config
Setup Isomap config.
setup_Isomap( k = 2L, dist_method = "euclidean", nsd = 0L, path = "shortest", features = NULL )setup_Isomap( k = 2L, dist_method = "euclidean", nsd = 0L, path = "shortest", features = NULL )
k |
Integer [1, Inf): Number of components. |
dist_method |
Character {"euclidean", "manhattan"}: Distance method. |
nsd |
Integer [0, Inf): Number of shortest dissimilarities retained. |
path |
Character {"shortest", "extended"}: Path argument for |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
IsomapConfig object.
EDG
isomap_config <- setup_Isomap(k = 3L) isomap_configisomap_config <- setup_Isomap(k = 3L) isomap_config
Setup hyperparameters for Isotonic Regression.
setup_Isotonic(ifw = FALSE)setup_Isotonic(ifw = FALSE)
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
There are not hyperparameters for this algorithm at this moment.
IsotonicHyperparameters object.
EDG
isotonic_hyperparams <- setup_Isotonic(ifw = TRUE) isotonic_hyperparamsisotonic_hyperparams <- setup_Isotonic(ifw = TRUE) isotonic_hyperparams
Setup KFold Resampler
setup_KFold( n_resamples = 10L, stratify_var = NULL, strat_n_bins = 4L, id_strat = NULL, seed = NULL )setup_KFold( n_resamples = 10L, stratify_var = NULL, strat_n_bins = 4L, id_strat = NULL, seed = NULL )
n_resamples |
Integer [1, Inf): Number of resamples to make. |
stratify_var |
Optional Character: Variable to stratify by. |
strat_n_bins |
Integer [1, Inf): Number of bins to stratify by. |
id_strat |
Optional Character: Name of the column holding per-case grouping IDs, e.g.
subject IDs when the dataset contains repeated measurements. Cases sharing an ID stay in the
same resample, so a case can only be present in the training or the test set, not both.
Requires that |
seed |
Optional Integer [0, Inf): Random seed. |
KFoldConfig object.
EDG
tenfold_resampler <- setup_KFold(n_resamples = 10L, seed = 2026L) tenfold_resamplertenfold_resampler <- setup_KFold(n_resamples = 10L, seed = 2026L) tenfold_resampler
Setup KMeansConfig
setup_KMeans(k = 3L, dist = "euclidean", features = NULL)setup_KMeans(k = 3L, dist = "euclidean", features = NULL)
k |
Integer [1, Inf): Number of clusters. |
dist |
Character {"euclidean", "manhattan"}: Distance measure to use. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
KMeansConfig object.
EDG
kmeans_config <- setup_KMeans(k = 4L, dist = "euclidean") kmeans_configkmeans_config <- setup_KMeans(k = 4L, dist = "euclidean") kmeans_config
Setup hyperparameters for k-Nearest Neighbors training.
setup_KNN(k = 7L, kernel = "optimal", distance = 2, scale = TRUE, ifw = FALSE)setup_KNN(k = 7L, kernel = "optimal", distance = 2, scale = TRUE, ifw = FALSE)
k |
(Tunable) Integer [1, Inf): Number of neighbors. Must be less than the number of training cases. |
kernel |
(Tunable) Character {"rectangular", "triangular", "epanechnikov", "biweight", "triweight", "cos", "inv", "gaussian", "rank", "optimal"}: Kernel used to weight neighbors by distance. |
distance |
(Tunable) Numeric (0, Inf): Parameter of the Minkowski distance. |
scale |
Logical: If TRUE, scale features to unit variance before computing distances. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Both outcome types are fit with kknn::train.kknn, which selects between
regression and classification from the outcome. Factors are one-hot encoded
by rtemis first, as an algorithm-internal preprocessor that is re-applied at
predict time: the backend's own factor handling resolves a contrast function
off the search path, which is not reachable when kknn is loaded but not
attached, as a suggested package is.
kknn provides no case weights, so ifw cannot be honored: enabling it
makes training abort.
KNNHyperparameters object.
EDG
knn_hyperparams <- setup_KNN(k = 11L, kernel = "rectangular") knn_hyperparamsknn_hyperparams <- setup_KNN(k = 11L, kernel = "rectangular") knn_hyperparams
Setup hyperparameters for LightCART training.
setup_LightCART( num_leaves = 32L, max_depth = -1L, lambda_l1 = 0, lambda_l2 = 0, max_cat_threshold = 32L, min_data_per_group = 100L, linear_tree = FALSE, objective = NULL, force_col_wise = TRUE, feature_fraction = 1, feature_fraction_bynode = 1, feature_fraction_seed = 2L, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, linear_lambda = NULL, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, alpha = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, ifw = FALSE )setup_LightCART( num_leaves = 32L, max_depth = -1L, lambda_l1 = 0, lambda_l2 = 0, max_cat_threshold = 32L, min_data_per_group = 100L, linear_tree = FALSE, objective = NULL, force_col_wise = TRUE, feature_fraction = 1, feature_fraction_bynode = 1, feature_fraction_seed = 2L, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, linear_lambda = NULL, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, alpha = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, ifw = FALSE )
num_leaves |
(Tunable) Integer [1, Inf): Maximum number of leaves in one tree. |
max_depth |
(Tunable) Integer: Maximum depth of trees. -1 = no limit. |
lambda_l1 |
(Tunable) Numeric [0, Inf): L1 regularization. |
lambda_l2 |
(Tunable) Numeric [0, Inf): L2 regularization. |
max_cat_threshold |
(Tunable) Integer [1, Inf): Maximum number of categories for categorical features. |
min_data_per_group |
(Tunable) Integer [1, Inf): Minimum number of observations per categorical group. |
linear_tree |
(Tunable) Logical: If TRUE, use linear trees. |
objective |
Optional Character: Objective function. NULL = set from outcome type. |
force_col_wise |
Logical: Force column-wise histogram building (CPU only). |
feature_fraction |
(Tunable) Numeric (0, 1]: Fraction of features sampled per tree. |
feature_fraction_bynode |
(Tunable) Numeric (0, 1]: Fraction of features sampled at each node, on top of the per-tree fraction. |
feature_fraction_seed |
Integer: Random seed for feature sampling. |
deterministic |
Logical: Force reproducible results at some cost in speed. |
objective_seed |
Integer: Random seed for the objective, where it draws. |
force_row_wise |
Logical: Force row-wise histogram building. Cheaper in memory than column-wise, slower per iteration. |
histogram_pool_size |
Numeric: Memory cap in MB for the histogram cache; -1 leaves it uncapped. |
cegb_tradeoff |
(Tunable) Numeric [0, Inf): Overall multiplier on every cost-efficiency penalty. Its scale is not comparable between boosting modes. |
cegb_penalty_split |
(Tunable) Numeric [0, Inf): Cost charged per split, in units of loss reduction. |
cegb_penalty_feature_lazy |
Optional List: Per-feature cost charged the first time a case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
cegb_penalty_feature_coupled |
Optional List: Per-feature cost charged the first time any case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
use_quantized_grad |
Logical: Discretize gradients before finding splits. Faster, and changes the fit. |
num_grad_quant_bins |
(Tunable) Optional Integer [2, Inf): Bins the gradients are
discretized into. Requires |
quant_train_renew_leaf |
Optional Logical: Recompute leaf values from the exact
gradients after each iteration. Requires |
stochastic_rounding |
Optional Logical: Round gradients stochastically rather than
to nearest. Requires |
monotone_constraints |
Optional Integer [-1, 1] vector: Per-feature monotonicity: 1 increasing, -1 decreasing, 0 unconstrained. One value per feature. NULL constrains no feature. |
monotone_constraints_method |
Optional Character {"basic", "intermediate",
"advanced"}: How monotonicity is enforced. Requires |
monotone_penalty |
(Tunable) Optional Numeric [0, Inf): Depth penalty on splits
that would break monotonicity. Requires |
interaction_constraints |
Optional Character: Feature groups permitted to interact, in LightGBM's own bracketed form, e.g. "[0,1],[2,3]". NULL permits every interaction. |
feature_contri |
Optional Numeric vector: Per-feature multiplier on split gain, one value per feature. NULL uses 1 for every feature. |
min_data_in_leaf |
(Tunable) Integer [0, Inf): Minimum number of cases in a leaf. |
min_sum_hessian_in_leaf |
(Tunable) Numeric [0, Inf): Minimum sum of hessians in a leaf: the smooth counterpart of a case count. |
min_gain_to_split |
(Tunable) Numeric [0, Inf): Minimum loss reduction a split must buy to be made. |
max_delta_step |
(Tunable) Numeric: Cap on each leaf's output; 0 or less leaves it uncapped. |
path_smooth |
(Tunable) Numeric [0, Inf): Smooth each leaf towards its parent, more strongly the fewer cases it holds. |
extra_trees |
(Tunable) Logical: Choose one split threshold per feature at random rather than the best. |
extra_seed |
Integer: Random seed for the thresholds |
linear_lambda |
(Tunable) Optional Numeric [0, Inf): L2 penalty on the linear models
fitted at the leaves. Requires |
max_bin |
(Tunable) Integer [2, Inf): Most bins a feature is discretized into. Fewer is faster and more regularized. |
min_data_in_bin |
(Tunable) Integer [1, Inf): Minimum number of cases per bin. |
use_missing |
Logical: Handle missing values. FALSE ignores them. |
zero_as_missing |
Logical: Treat zeros as missing, rather than only NA. |
cat_l2 |
(Tunable) Numeric [0, Inf): L2 regularization on a categorical split. |
cat_smooth |
(Tunable) Numeric [0, Inf): Smoothing over categorical levels, which reduces the effect of rare ones. |
max_cat_to_onehot |
(Tunable) Integer [1, Inf): Below this many levels, split one-versus-rest rather than by partition. |
alpha |
(Tunable) Optional Numeric (0, Inf): Huber delta or quantile level.
Requires |
tweedie_variance_power |
(Tunable) Optional Numeric [1, 2): Tweedie power: 1 is
Poisson-like, near 2 is gamma-like. Requires |
fair_c |
(Tunable) Optional Numeric (0, Inf): Fair loss scale. Requires
|
poisson_max_delta_step |
(Tunable) Optional Numeric (0, Inf): Step cap
safeguarding Poisson optimization. Requires |
sigmoid |
(Tunable) Optional Numeric (0, Inf): Sigmoid slope, for a binary or one-vs-all objective. NULL uses LightGBM's default of 1. |
boost_from_average |
Optional Logical: Start boosting from the constant score that best fits the outcome under the objective, such as its mean for regression. NULL uses LightGBM's default of TRUE. |
reg_sqrt |
Optional Logical: Fit the square root of the outcome and square the prediction back, for the "regression", "regression_l1", "fair", "quantile" or "mape" objective. NULL uses LightGBM's default of FALSE. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from lightgbm::lgb.train.
LightCARTHyperparameters object.
EDG
lightcart_hyperparams <- setup_LightCART(num_leaves = 32L, ifw = FALSE) lightcart_hyperparamslightcart_hyperparams <- setup_LightCART(num_leaves = 32L, ifw = FALSE) lightcart_hyperparams
Setup hyperparameters for LightGBM training.
setup_LightGBM( max_nrounds = 1000L, force_nrounds = NULL, early_stopping_rounds = 10L, num_leaves = 8L, max_depth = -1L, learning_rate = 0.01, feature_fraction = 1, bagging_fraction = 1, bagging_freq = 1L, lambda_l1 = 0, lambda_l2 = 0, max_cat_threshold = 32L, min_data_per_group = 32L, linear_tree = FALSE, ifw = FALSE, objective = NULL, early_stopping_min_delta = 0, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, top_k = NULL, pos_bagging_fraction = 1, neg_bagging_fraction = 1, bagging_seed = 3L, feature_fraction_bynode = 1, feature_fraction_seed = 2L, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, linear_lambda = NULL, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, boosting = "gbdt", data_sample_strategy = "bagging", drop_rate = NULL, max_drop = NULL, skip_drop = NULL, uniform_drop = NULL, xgboost_dart_mode = NULL, drop_seed = NULL, top_rate = NULL, other_rate = NULL, alpha = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, device_type = NULL, tree_learner = "serial", force_col_wise = TRUE )setup_LightGBM( max_nrounds = 1000L, force_nrounds = NULL, early_stopping_rounds = 10L, num_leaves = 8L, max_depth = -1L, learning_rate = 0.01, feature_fraction = 1, bagging_fraction = 1, bagging_freq = 1L, lambda_l1 = 0, lambda_l2 = 0, max_cat_threshold = 32L, min_data_per_group = 32L, linear_tree = FALSE, ifw = FALSE, objective = NULL, early_stopping_min_delta = 0, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, top_k = NULL, pos_bagging_fraction = 1, neg_bagging_fraction = 1, bagging_seed = 3L, feature_fraction_bynode = 1, feature_fraction_seed = 2L, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, linear_lambda = NULL, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, boosting = "gbdt", data_sample_strategy = "bagging", drop_rate = NULL, max_drop = NULL, skip_drop = NULL, uniform_drop = NULL, xgboost_dart_mode = NULL, drop_seed = NULL, top_rate = NULL, other_rate = NULL, alpha = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, device_type = NULL, tree_learner = "serial", force_col_wise = TRUE )
max_nrounds |
Integer [1, Inf): Maximum number of boosting rounds. |
force_nrounds |
Optional Integer [1, Inf): Use this many boosting rounds. Disables search for nrounds. NULL selects |
early_stopping_rounds |
Integer [1, Inf): Number of rounds without improvement to stop training. |
num_leaves |
(Tunable) Integer [1, Inf): Maximum number of leaves in one tree. |
max_depth |
(Tunable) Integer: Maximum depth of trees. -1 = no limit. |
learning_rate |
(Tunable) Numeric (0, 1]: Learning rate. |
feature_fraction |
(Tunable) Numeric (0, 1]: Fraction of features to use. |
bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of cases sampled per tree. |
bagging_freq |
(Tunable) Integer [1, Inf): Resample every this many iterations. |
lambda_l1 |
(Tunable) Numeric [0, Inf): L1 regularization. |
lambda_l2 |
(Tunable) Numeric [0, Inf): L2 regularization. |
max_cat_threshold |
(Tunable) Integer [1, Inf): Maximum number of categories for categorical features. |
min_data_per_group |
(Tunable) Integer [1, Inf): Minimum number of observations per categorical group. |
linear_tree |
(Tunable) Logical: If TRUE, use linear trees. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
objective |
Optional Character: Objective function. NULL = set from outcome type. |
early_stopping_min_delta |
(Tunable) Numeric [0, Inf): Smallest improvement that resets the early-stopping counter. |
deterministic |
Logical: Force reproducible results at some cost in speed. |
objective_seed |
Integer: Random seed for the objective, where it draws. |
force_row_wise |
Logical: Force row-wise histogram building. Cheaper in memory than column-wise, slower per iteration. |
histogram_pool_size |
Numeric: Memory cap in MB for the histogram cache; -1 leaves it uncapped. |
top_k |
(Tunable) Optional Integer [1, Inf): Features each machine votes for in
the voting tree learner. Requires |
pos_bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of positive cases sampled per tree, for a binary outcome. |
neg_bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of negative cases sampled per tree, for a binary outcome. |
bagging_seed |
Integer: Random seed for bagging. |
feature_fraction_bynode |
(Tunable) Numeric (0, 1]: Fraction of features sampled at each node, on top of the per-tree fraction. |
feature_fraction_seed |
Integer: Random seed for feature sampling. |
cegb_tradeoff |
(Tunable) Numeric [0, Inf): Overall multiplier on every cost-efficiency penalty. Its scale is not comparable between boosting modes. |
cegb_penalty_split |
(Tunable) Numeric [0, Inf): Cost charged per split, in units of loss reduction. |
cegb_penalty_feature_lazy |
Optional List: Per-feature cost charged the first time a case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
cegb_penalty_feature_coupled |
Optional List: Per-feature cost charged the first time any case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
use_quantized_grad |
Logical: Discretize gradients before finding splits. Faster, and changes the fit. |
num_grad_quant_bins |
(Tunable) Optional Integer [2, Inf): Bins the gradients are
discretized into. Requires |
quant_train_renew_leaf |
Optional Logical: Recompute leaf values from the exact
gradients after each iteration. Requires |
stochastic_rounding |
Optional Logical: Round gradients stochastically rather than
to nearest. Requires |
monotone_constraints |
Optional Integer [-1, 1] vector: Per-feature monotonicity: 1 increasing, -1 decreasing, 0 unconstrained. One value per feature. NULL constrains no feature. |
monotone_constraints_method |
Optional Character {"basic", "intermediate",
"advanced"}: How monotonicity is enforced. Requires |
monotone_penalty |
(Tunable) Optional Numeric [0, Inf): Depth penalty on splits
that would break monotonicity. Requires |
interaction_constraints |
Optional Character: Feature groups permitted to interact, in LightGBM's own bracketed form, e.g. "[0,1],[2,3]". NULL permits every interaction. |
feature_contri |
Optional Numeric vector: Per-feature multiplier on split gain, one value per feature. NULL uses 1 for every feature. |
min_data_in_leaf |
(Tunable) Integer [0, Inf): Minimum number of cases in a leaf. |
min_sum_hessian_in_leaf |
(Tunable) Numeric [0, Inf): Minimum sum of hessians in a leaf: the smooth counterpart of a case count. |
min_gain_to_split |
(Tunable) Numeric [0, Inf): Minimum loss reduction a split must buy to be made. |
max_delta_step |
(Tunable) Numeric: Cap on each leaf's output; 0 or less leaves it uncapped. |
path_smooth |
(Tunable) Numeric [0, Inf): Smooth each leaf towards its parent, more strongly the fewer cases it holds. |
extra_trees |
(Tunable) Logical: Choose one split threshold per feature at random rather than the best. |
extra_seed |
Integer: Random seed for the thresholds |
linear_lambda |
(Tunable) Optional Numeric [0, Inf): L2 penalty on the linear models
fitted at the leaves. Requires |
max_bin |
(Tunable) Integer [2, Inf): Most bins a feature is discretized into. Fewer is faster and more regularized. |
min_data_in_bin |
(Tunable) Integer [1, Inf): Minimum number of cases per bin. |
use_missing |
Logical: Handle missing values. FALSE ignores them. |
zero_as_missing |
Logical: Treat zeros as missing, rather than only NA. |
cat_l2 |
(Tunable) Numeric [0, Inf): L2 regularization on a categorical split. |
cat_smooth |
(Tunable) Numeric [0, Inf): Smoothing over categorical levels, which reduces the effect of rare ones. |
max_cat_to_onehot |
(Tunable) Integer [1, Inf): Below this many levels, split one-versus-rest rather than by partition. |
boosting |
Character {"gbdt", "rf", "dart"}: Boosting algorithm: gradient boosting, random forest, or DART (dropout). |
data_sample_strategy |
Character {"bagging", "goss"}: How cases are
subsampled: at random, or by gradient magnitude (GOSS). GOSS cannot be combined
with bagging, so it requires |
drop_rate |
(Tunable) Optional Numeric [0, 1]: Fraction of existing trees
to drop per iteration. Requires |
max_drop |
(Tunable) Optional Integer: Most trees dropped in one iteration;
0 or less removes the cap. Requires |
skip_drop |
(Tunable) Optional Numeric [0, 1]: Probability of skipping
dropout for an iteration. Requires |
uniform_drop |
(Tunable) Optional Logical: Drop trees uniformly rather than
weighted. Requires |
xgboost_dart_mode |
(Tunable) Optional Logical: Use the XGBoost DART
normalization. Requires |
drop_seed |
Optional Integer: Random seed for choosing which trees to drop.
Requires |
top_rate |
(Tunable) Optional Numeric [0, 1]: Share of large-gradient cases
GOSS retains. Requires |
other_rate |
(Tunable) Optional Numeric [0, 1]: Share of the remaining cases
GOSS retains; with |
alpha |
(Tunable) Optional Numeric (0, Inf): Huber delta or quantile level.
Requires |
tweedie_variance_power |
(Tunable) Optional Numeric [1, 2): Tweedie power: 1 is
Poisson-like, near 2 is gamma-like. Requires |
fair_c |
(Tunable) Optional Numeric (0, Inf): Fair loss scale. Requires
|
poisson_max_delta_step |
(Tunable) Optional Numeric (0, Inf): Step cap
safeguarding Poisson optimization. Requires |
sigmoid |
(Tunable) Optional Numeric (0, Inf): Sigmoid slope, for a binary or one-vs-all objective. NULL uses LightGBM's default of 1. |
boost_from_average |
Optional Logical: Start boosting from the constant score that best fits the outcome under the objective, such as its mean for regression. NULL uses LightGBM's default of TRUE. |
reg_sqrt |
Optional Logical: Fit the square root of the outcome and square the prediction back, for the "regression", "regression_l1", "fair", "quantile" or "mape" objective. NULL uses LightGBM's default of FALSE. |
device_type |
Optional Character: Deprecated and ignored. Set the compute device in the
|
tree_learner |
Character {"serial", "feature", "data", "voting"}: Tree learner type. |
force_col_wise |
Logical: Use only with CPU - If TRUE, force col-wise histogram building. |
Get more information from lightgbm::lgb.train.
nrounds is auto-tuned using early stopping (up to max_nrounds) unless
force_nrounds is set.
LightGBMHyperparameters object.
EDG
lightgbm_hyperparams <- setup_LightGBM( max_nrounds = 500L, learning_rate = tune_over(0.001, 0.01, 0.05), ifw = TRUE ) lightgbm_hyperparamslightgbm_hyperparams <- setup_LightGBM( max_nrounds = 500L, learning_rate = tune_over(0.001, 0.01, 0.05), ifw = TRUE ) lightgbm_hyperparams
Setup hyperparameters for LightRF training.
setup_LightRF( nrounds = 500L, num_leaves = 4096L, max_depth = -1L, feature_fraction = NULL, bagging_fraction = 0.623, lambda_l1 = 0, lambda_l2 = 0, max_cat_threshold = 32L, min_data_per_group = 32L, linear_tree = FALSE, ifw = FALSE, objective = NULL, early_stopping_min_delta = 0, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, top_k = NULL, pos_bagging_fraction = 1, neg_bagging_fraction = 1, bagging_seed = 3L, feature_fraction_bynode = 1, feature_fraction_seed = 2L, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, linear_lambda = NULL, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, alpha = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, device_type = NULL, tree_learner = "serial", force_col_wise = TRUE )setup_LightRF( nrounds = 500L, num_leaves = 4096L, max_depth = -1L, feature_fraction = NULL, bagging_fraction = 0.623, lambda_l1 = 0, lambda_l2 = 0, max_cat_threshold = 32L, min_data_per_group = 32L, linear_tree = FALSE, ifw = FALSE, objective = NULL, early_stopping_min_delta = 0, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, top_k = NULL, pos_bagging_fraction = 1, neg_bagging_fraction = 1, bagging_seed = 3L, feature_fraction_bynode = 1, feature_fraction_seed = 2L, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, linear_lambda = NULL, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, alpha = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, device_type = NULL, tree_learner = "serial", force_col_wise = TRUE )
nrounds |
(Tunable) Integer [1, Inf): Number of boosting rounds. |
num_leaves |
(Tunable) Integer [1, Inf): Maximum number of leaves in one tree. |
max_depth |
(Tunable) Integer: Maximum depth of trees. -1 = no limit. |
feature_fraction |
(Tunable) Optional Numeric (0, 1]: Fraction of features to use. NULL derives it from the data: sqrt(n_features)/n_features for classification, 0.33 for regression. |
bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of cases sampled per tree. |
lambda_l1 |
(Tunable) Numeric [0, Inf): L1 regularization. |
lambda_l2 |
(Tunable) Numeric [0, Inf): L2 regularization. |
max_cat_threshold |
(Tunable) Integer [1, Inf): Maximum number of categories for categorical features. |
min_data_per_group |
(Tunable) Integer [1, Inf): Minimum number of observations per categorical group. |
linear_tree |
(Tunable) Logical: If TRUE, use linear trees. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
objective |
Optional Character: Objective function. NULL = set from outcome type. |
early_stopping_min_delta |
(Tunable) Numeric [0, Inf): Smallest improvement that resets the early-stopping counter. |
deterministic |
Logical: Force reproducible results at some cost in speed. |
objective_seed |
Integer: Random seed for the objective, where it draws. |
force_row_wise |
Logical: Force row-wise histogram building. Cheaper in memory than column-wise, slower per iteration. |
histogram_pool_size |
Numeric: Memory cap in MB for the histogram cache; -1 leaves it uncapped. |
top_k |
(Tunable) Optional Integer [1, Inf): Features each machine votes for in
the voting tree learner. Requires |
pos_bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of positive cases sampled per tree, for a binary outcome. |
neg_bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of negative cases sampled per tree, for a binary outcome. |
bagging_seed |
Integer: Random seed for bagging. |
feature_fraction_bynode |
(Tunable) Numeric (0, 1]: Fraction of features sampled at each node, on top of the per-tree fraction. |
feature_fraction_seed |
Integer: Random seed for feature sampling. |
cegb_tradeoff |
(Tunable) Numeric [0, Inf): Overall multiplier on every cost-efficiency penalty. Its scale is not comparable between boosting modes. |
cegb_penalty_split |
(Tunable) Numeric [0, Inf): Cost charged per split, in units of loss reduction. |
cegb_penalty_feature_lazy |
Optional List: Per-feature cost charged the first time a case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
cegb_penalty_feature_coupled |
Optional List: Per-feature cost charged the first time any case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
use_quantized_grad |
Logical: Discretize gradients before finding splits. Faster, and changes the fit. |
num_grad_quant_bins |
(Tunable) Optional Integer [2, Inf): Bins the gradients are
discretized into. Requires |
quant_train_renew_leaf |
Optional Logical: Recompute leaf values from the exact
gradients after each iteration. Requires |
stochastic_rounding |
Optional Logical: Round gradients stochastically rather than
to nearest. Requires |
monotone_constraints |
Optional Integer [-1, 1] vector: Per-feature monotonicity: 1 increasing, -1 decreasing, 0 unconstrained. One value per feature. NULL constrains no feature. |
monotone_constraints_method |
Optional Character {"basic", "intermediate",
"advanced"}: How monotonicity is enforced. Requires |
monotone_penalty |
(Tunable) Optional Numeric [0, Inf): Depth penalty on splits
that would break monotonicity. Requires |
interaction_constraints |
Optional Character: Feature groups permitted to interact, in LightGBM's own bracketed form, e.g. "[0,1],[2,3]". NULL permits every interaction. |
feature_contri |
Optional Numeric vector: Per-feature multiplier on split gain, one value per feature. NULL uses 1 for every feature. |
min_data_in_leaf |
(Tunable) Integer [0, Inf): Minimum number of cases in a leaf. |
min_sum_hessian_in_leaf |
(Tunable) Numeric [0, Inf): Minimum sum of hessians in a leaf: the smooth counterpart of a case count. |
min_gain_to_split |
(Tunable) Numeric [0, Inf): Minimum loss reduction a split must buy to be made. |
max_delta_step |
(Tunable) Numeric: Cap on each leaf's output; 0 or less leaves it uncapped. |
path_smooth |
(Tunable) Numeric [0, Inf): Smooth each leaf towards its parent, more strongly the fewer cases it holds. |
extra_trees |
(Tunable) Logical: Choose one split threshold per feature at random rather than the best. |
extra_seed |
Integer: Random seed for the thresholds |
linear_lambda |
(Tunable) Optional Numeric [0, Inf): L2 penalty on the linear models
fitted at the leaves. Requires |
max_bin |
(Tunable) Integer [2, Inf): Most bins a feature is discretized into. Fewer is faster and more regularized. |
min_data_in_bin |
(Tunable) Integer [1, Inf): Minimum number of cases per bin. |
use_missing |
Logical: Handle missing values. FALSE ignores them. |
zero_as_missing |
Logical: Treat zeros as missing, rather than only NA. |
cat_l2 |
(Tunable) Numeric [0, Inf): L2 regularization on a categorical split. |
cat_smooth |
(Tunable) Numeric [0, Inf): Smoothing over categorical levels, which reduces the effect of rare ones. |
max_cat_to_onehot |
(Tunable) Integer [1, Inf): Below this many levels, split one-versus-rest rather than by partition. |
alpha |
(Tunable) Optional Numeric (0, Inf): Huber delta or quantile level.
Requires |
tweedie_variance_power |
(Tunable) Optional Numeric [1, 2): Tweedie power: 1 is
Poisson-like, near 2 is gamma-like. Requires |
fair_c |
(Tunable) Optional Numeric (0, Inf): Fair loss scale. Requires
|
poisson_max_delta_step |
(Tunable) Optional Numeric (0, Inf): Step cap
safeguarding Poisson optimization. Requires |
sigmoid |
(Tunable) Optional Numeric (0, Inf): Sigmoid slope, for a binary or one-vs-all objective. NULL uses LightGBM's default of 1. |
boost_from_average |
Optional Logical: Start boosting from the constant score that best fits the outcome under the objective, such as its mean for regression. NULL uses LightGBM's default of TRUE. |
reg_sqrt |
Optional Logical: Fit the square root of the outcome and square the prediction back, for the "regression", "regression_l1", "fair", "quantile" or "mape" objective. NULL uses LightGBM's default of FALSE. |
device_type |
Optional Character: Deprecated and ignored. Set the compute device in the
|
tree_learner |
Character {"serial", "feature", "data", "voting"}: Tree learner type. |
force_col_wise |
Logical: Use only with CPU - If TRUE, force col-wise histogram building. |
Get more information from lightgbm::lgb.train.
Note that boosting, learning_rate, bagging_freq and
early_stopping_rounds are constants here: they cannot be set, because
they are what makes lightgbm train a random forest. All of them are
settable when training gradient boosting with LightGBM.
LightRFHyperparameters object.
EDG
lightrf_hyperparams <- setup_LightRF(nrounds = 1000L, ifw = FALSE) lightrf_hyperparamslightrf_hyperparams <- setup_LightRF(nrounds = 1000L, ifw = FALSE) lightrf_hyperparams
Setup hyperparameters for LightRuleFit training.
setup_LightRuleFit( nrounds = 200L, num_leaves = 32L, max_depth = 4L, learning_rate = 0.1, bagging_fraction = 0.666, bagging_freq = 1L, lambda_l1 = 0, lambda_l2 = 0, objective = NULL, force_col_wise = TRUE, tree_learner = "serial", top_k = NULL, feature_fraction = 1, feature_fraction_bynode = 1, feature_fraction_seed = 2L, linear_tree = FALSE, linear_lambda = NULL, max_cat_threshold = 32L, min_data_per_group = 32L, alpha = NULL, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, pos_bagging_fraction = 1, neg_bagging_fraction = 1, bagging_seed = 3L, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, boosting = "gbdt", data_sample_strategy = "bagging", drop_rate = NULL, max_drop = NULL, skip_drop = NULL, uniform_drop = NULL, xgboost_dart_mode = NULL, drop_seed = NULL, top_rate = NULL, other_rate = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, ifw_lightgbm = FALSE, alpha_glmnet = 1, lambda_glmnet = NULL, ifw_glmnet = FALSE, ifw = FALSE )setup_LightRuleFit( nrounds = 200L, num_leaves = 32L, max_depth = 4L, learning_rate = 0.1, bagging_fraction = 0.666, bagging_freq = 1L, lambda_l1 = 0, lambda_l2 = 0, objective = NULL, force_col_wise = TRUE, tree_learner = "serial", top_k = NULL, feature_fraction = 1, feature_fraction_bynode = 1, feature_fraction_seed = 2L, linear_tree = FALSE, linear_lambda = NULL, max_cat_threshold = 32L, min_data_per_group = 32L, alpha = NULL, deterministic = FALSE, objective_seed = 5L, force_row_wise = FALSE, histogram_pool_size = -1, pos_bagging_fraction = 1, neg_bagging_fraction = 1, bagging_seed = 3L, cegb_tradeoff = 1, cegb_penalty_split = 0, cegb_penalty_feature_lazy = NULL, cegb_penalty_feature_coupled = NULL, use_quantized_grad = FALSE, num_grad_quant_bins = NULL, quant_train_renew_leaf = NULL, stochastic_rounding = NULL, monotone_constraints = NULL, monotone_constraints_method = NULL, monotone_penalty = NULL, interaction_constraints = NULL, feature_contri = NULL, min_data_in_leaf = 20L, min_sum_hessian_in_leaf = 0.001, min_gain_to_split = 0, max_delta_step = 0, path_smooth = 0, extra_trees = FALSE, extra_seed = 6L, max_bin = 255L, min_data_in_bin = 3L, use_missing = TRUE, zero_as_missing = FALSE, cat_l2 = 10, cat_smooth = 10, max_cat_to_onehot = 4L, boosting = "gbdt", data_sample_strategy = "bagging", drop_rate = NULL, max_drop = NULL, skip_drop = NULL, uniform_drop = NULL, xgboost_dart_mode = NULL, drop_seed = NULL, top_rate = NULL, other_rate = NULL, tweedie_variance_power = NULL, fair_c = NULL, poisson_max_delta_step = NULL, sigmoid = NULL, boost_from_average = NULL, reg_sqrt = NULL, ifw_lightgbm = FALSE, alpha_glmnet = 1, lambda_glmnet = NULL, ifw_glmnet = FALSE, ifw = FALSE )
nrounds |
(Tunable) Integer [1, Inf): Number of boosting rounds. |
num_leaves |
(Tunable) Integer [1, Inf): Maximum number of leaves in one tree. |
max_depth |
(Tunable) Integer: Maximum depth of trees. |
learning_rate |
(Tunable) Numeric (0, 1]: Learning rate. |
bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of cases sampled per tree. |
bagging_freq |
(Tunable) Integer [1, Inf): Resample every this many iterations. |
lambda_l1 |
(Tunable) Numeric [0, Inf): L1 regularization. |
lambda_l2 |
(Tunable) Numeric [0, Inf): L2 regularization. |
objective |
Optional Character: Objective function. NULL = set from outcome type. |
force_col_wise |
Logical: Force column-wise histogram building (CPU only). |
tree_learner |
Character {"serial", "feature", "data", "voting"}: Tree learner type. |
top_k |
(Tunable) Optional Integer [1, Inf): Features each machine votes for in
the voting tree learner. Requires |
feature_fraction |
(Tunable) Numeric (0, 1]: Fraction of features sampled per tree. |
feature_fraction_bynode |
(Tunable) Numeric (0, 1]: Fraction of features sampled at each node, on top of the per-tree fraction. |
feature_fraction_seed |
Integer: Random seed for feature sampling. |
linear_tree |
(Tunable) Logical: Fit linear models at leaves. |
linear_lambda |
(Tunable) Optional Numeric [0, Inf): L2 penalty on the linear models
fitted at the leaves. Requires |
max_cat_threshold |
(Tunable) Integer [1, Inf): Maximum number of split points for categorical features. |
min_data_per_group |
(Tunable) Integer [1, Inf): Minimum number of cases per categorical group. |
alpha |
(Tunable) Optional Numeric (0, Inf): Huber delta or quantile level.
Requires |
deterministic |
Logical: Force reproducible results at some cost in speed. |
objective_seed |
Integer: Random seed for the objective, where it draws. |
force_row_wise |
Logical: Force row-wise histogram building. Cheaper in memory than column-wise, slower per iteration. |
histogram_pool_size |
Numeric: Memory cap in MB for the histogram cache; -1 leaves it uncapped. |
pos_bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of positive cases sampled per tree, for a binary outcome. |
neg_bagging_fraction |
(Tunable) Numeric (0, 1]: Fraction of negative cases sampled per tree, for a binary outcome. |
bagging_seed |
Integer: Random seed for bagging. |
cegb_tradeoff |
(Tunable) Numeric [0, Inf): Overall multiplier on every cost-efficiency penalty. Its scale is not comparable between boosting modes. |
cegb_penalty_split |
(Tunable) Numeric [0, Inf): Cost charged per split, in units of loss reduction. |
cegb_penalty_feature_lazy |
Optional List: Per-feature cost charged the first time a case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
cegb_penalty_feature_coupled |
Optional List: Per-feature cost charged the first time any case uses it, in [0, Inf). One vector applied to every tree, or one vector per tree. NULL charges no cost. |
use_quantized_grad |
Logical: Discretize gradients before finding splits. Faster, and changes the fit. |
num_grad_quant_bins |
(Tunable) Optional Integer [2, Inf): Bins the gradients are
discretized into. Requires |
quant_train_renew_leaf |
Optional Logical: Recompute leaf values from the exact
gradients after each iteration. Requires |
stochastic_rounding |
Optional Logical: Round gradients stochastically rather than
to nearest. Requires |
monotone_constraints |
Optional Integer [-1, 1] vector: Per-feature monotonicity: 1 increasing, -1 decreasing, 0 unconstrained. One value per feature. NULL constrains no feature. |
monotone_constraints_method |
Optional Character {"basic", "intermediate",
"advanced"}: How monotonicity is enforced. Requires |
monotone_penalty |
(Tunable) Optional Numeric [0, Inf): Depth penalty on splits
that would break monotonicity. Requires |
interaction_constraints |
Optional Character: Feature groups permitted to interact, in LightGBM's own bracketed form, e.g. "[0,1],[2,3]". NULL permits every interaction. |
feature_contri |
Optional Numeric vector: Per-feature multiplier on split gain, one value per feature. NULL uses 1 for every feature. |
min_data_in_leaf |
(Tunable) Integer [0, Inf): Minimum number of cases in a leaf. |
min_sum_hessian_in_leaf |
(Tunable) Numeric [0, Inf): Minimum sum of hessians in a leaf: the smooth counterpart of a case count. |
min_gain_to_split |
(Tunable) Numeric [0, Inf): Minimum loss reduction a split must buy to be made. |
max_delta_step |
(Tunable) Numeric: Cap on each leaf's output; 0 or less leaves it uncapped. |
path_smooth |
(Tunable) Numeric [0, Inf): Smooth each leaf towards its parent, more strongly the fewer cases it holds. |
extra_trees |
(Tunable) Logical: Choose one split threshold per feature at random rather than the best. |
extra_seed |
Integer: Random seed for the thresholds |
max_bin |
(Tunable) Integer [2, Inf): Most bins a feature is discretized into. Fewer is faster and more regularized. |
min_data_in_bin |
(Tunable) Integer [1, Inf): Minimum number of cases per bin. |
use_missing |
Logical: Handle missing values. FALSE ignores them. |
zero_as_missing |
Logical: Treat zeros as missing, rather than only NA. |
cat_l2 |
(Tunable) Numeric [0, Inf): L2 regularization on a categorical split. |
cat_smooth |
(Tunable) Numeric [0, Inf): Smoothing over categorical levels, which reduces the effect of rare ones. |
max_cat_to_onehot |
(Tunable) Integer [1, Inf): Below this many levels, split one-versus-rest rather than by partition. |
boosting |
Character {"gbdt", "rf", "dart"}: Boosting algorithm: gradient boosting, random forest, or DART (dropout). |
data_sample_strategy |
Character {"bagging", "goss"}: How cases are
subsampled: at random, or by gradient magnitude (GOSS). GOSS cannot be combined
with bagging, so it requires |
drop_rate |
(Tunable) Optional Numeric [0, 1]: Fraction of existing trees
to drop per iteration. Requires |
max_drop |
(Tunable) Optional Integer: Most trees dropped in one iteration;
0 or less removes the cap. Requires |
skip_drop |
(Tunable) Optional Numeric [0, 1]: Probability of skipping
dropout for an iteration. Requires |
uniform_drop |
(Tunable) Optional Logical: Drop trees uniformly rather than
weighted. Requires |
xgboost_dart_mode |
(Tunable) Optional Logical: Use the XGBoost DART
normalization. Requires |
drop_seed |
Optional Integer: Random seed for choosing which trees to drop.
Requires |
top_rate |
(Tunable) Optional Numeric [0, 1]: Share of large-gradient cases
GOSS retains. Requires |
other_rate |
(Tunable) Optional Numeric [0, 1]: Share of the remaining cases
GOSS retains; with |
tweedie_variance_power |
(Tunable) Optional Numeric [1, 2): Tweedie power: 1 is
Poisson-like, near 2 is gamma-like. Requires |
fair_c |
(Tunable) Optional Numeric (0, Inf): Fair loss scale. Requires
|
poisson_max_delta_step |
(Tunable) Optional Numeric (0, Inf): Step cap
safeguarding Poisson optimization. Requires |
sigmoid |
(Tunable) Optional Numeric (0, Inf): Sigmoid slope, for a binary or one-vs-all objective. NULL uses LightGBM's default of 1. |
boost_from_average |
Optional Logical: Start boosting from the constant score that best fits the outcome under the objective, such as its mean for regression. NULL uses LightGBM's default of TRUE. |
reg_sqrt |
Optional Logical: Fit the square root of the outcome and square the prediction back, for the "regression", "regression_l1", "fair", "quantile" or "mape" objective. NULL uses LightGBM's default of FALSE. |
ifw_lightgbm |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in the LightGBM step. |
alpha_glmnet |
(Tunable) Numeric [0, 1]: Alpha for GLMNET. |
lambda_glmnet |
Optional Numeric [0, Inf) vector: Lambda for GLMNET. NULL = determined by cv.glmnet. |
ifw_glmnet |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in the GLMNET step. |
ifw |
Logical: If TRUE, use Inverse Frequency Weighting in classification. This applies IFW
to both LightGBM and GLMNET; cannot be combined with |
Get more information from lightgbm::lgb.train.
LightRuleFitHyperparameters object.
EDG
lightrulefit_hyperparams <- setup_LightRuleFit(nrounds = 300L, max_depth = 3L) lightrulefit_hyperparamslightrulefit_hyperparams <- setup_LightRuleFit(nrounds = 300L, max_depth = 3L) lightrulefit_hyperparams
Setup hyperparameters for LINAD, the Linear Additive Tree. LINAD generalizes the decision tree and the regularized linear model: CART, the Additive Tree and a penalized linear fit are each a special case of it, recovered exactly by the hyperparameter combinations given under Details.
setup_LINAD( max_leaves = 20L, min_cases_split = 2L, min_cases_leaf = 1L, min_cases_node_model = NULL, nvmax = NULL, forward_stop = NULL, lambda = NULL, alpha = NULL, learning_rate = 0.1, root_nvmax = NULL, root_lambda = NULL, root_alpha = NULL, root_learning_rate = 1, n_cuts = NULL, gamma = 0.1, split_binning = NULL, split_bin_type = "frequency", node_test = NULL, split_criterion = NULL, line_search = "expansion", constant_rule = "closed_form", ifw = FALSE, patience = NULL, force_max_leaves = FALSE, smooth_validation_curve = NULL, node_model = "forward", root_model = NULL, split_search = "stump", split_features = NULL, linear_features = NULL, global_features = NULL, line_search_max = 1000, root_forward_stop = NULL, root_node_test = NULL )setup_LINAD( max_leaves = 20L, min_cases_split = 2L, min_cases_leaf = 1L, min_cases_node_model = NULL, nvmax = NULL, forward_stop = NULL, lambda = NULL, alpha = NULL, learning_rate = 0.1, root_nvmax = NULL, root_lambda = NULL, root_alpha = NULL, root_learning_rate = 1, n_cuts = NULL, gamma = 0.1, split_binning = NULL, split_bin_type = "frequency", node_test = NULL, split_criterion = NULL, line_search = "expansion", constant_rule = "closed_form", ifw = FALSE, patience = NULL, force_max_leaves = FALSE, smooth_validation_curve = NULL, node_model = "forward", root_model = NULL, split_search = "stump", split_features = NULL, linear_features = NULL, global_features = NULL, line_search_max = 1000, root_forward_stop = NULL, root_node_test = NULL )
max_leaves |
(Tunable) Integer [1, Inf): Largest number of terminal nodes to grow. |
min_cases_split |
(Tunable) Integer [2, Inf): Fewest cases a node may hold and still be considered for splitting. |
min_cases_leaf |
(Tunable) Integer [1, Inf): Fewest cases a split must leave on each side. |
min_cases_node_model |
(Tunable) Optional Integer [1, Inf): Fewest cases needed to fit a linear model at a node. Applies only when |
nvmax |
(Tunable) Optional Integer [1, Inf): Most terms forward selection may add beside the intercept. Applies only when |
forward_stop |
(Tunable) Optional Character {"bic", "aic", "none"}: Cost a term must earn to be added by forward selection. Applies only when |
lambda |
(Tunable) Optional Numeric [0, Inf): L2 penalty on the leaf models. Applies only when |
alpha |
(Tunable) Optional Numeric [0, 1]: Elastic-net mixing, 0 ridge to 1 lasso. Applies only when |
learning_rate |
(Tunable) Numeric (0, 1]: Shrinkage applied to every functional update. |
root_nvmax |
(Tunable) Optional Integer [1, Inf): |
root_lambda |
(Tunable) Optional Numeric [0, Inf): |
root_alpha |
(Tunable) Optional Numeric [0, 1]: |
root_learning_rate |
(Tunable) Numeric [0, 1]: Shrinkage applied to the root model's slopes. |
n_cuts |
(Tunable) Optional Integer [2, Inf): Cut points tried per feature; |
gamma |
(Tunable) Numeric [0, 1]: Weight a case retains in the branch it does not belong to. 0 is a hard partition. |
split_binning |
(Tunable) Optional Integer [2, Inf): Discretize each numeric feature into this many bins and consider only bin boundaries as splits. Applies to both split searches. |
split_bin_type |
(Tunable) Character {"frequency", "width"}: How bin edges are placed. |
node_test |
(Tunable) Optional Character {"none", "aic", "bic"}: Cost a node's slopes must earn over the constant alone. Applies only when |
split_criterion |
(Tunable) Optional Character {"mean", "linear"}: What the stump search scores a candidate side by. Applies only when |
line_search |
(Tunable) Character {"expansion", "child", "none"}: Scope of the Newton step for each update. |
constant_rule |
(Tunable) Character {"closed_form", "least_squares"}: How a node's constant is computed. The two coincide for regression and differ only for classification. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
patience |
(Tunable) Optional Integer [1, Inf): Expansions without validation improvement before growth stops. Requires a validation set. NULL disables patience-based early stopping. |
force_max_leaves |
Logical: If TRUE, keep every leaf grown instead of selecting a size on the validation set. |
smooth_validation_curve |
Optional Logical: If TRUE, smooth the validation curve before reading its minimum. Applies only when |
node_model |
Character {"forward", "ridge", "elasticnet", "constant"}: Model fitted at each node. "constant" is the intercept-only model every decision tree node carries; the others add a regularized linear model on top of it. |
root_model |
Optional Character {"forward", "ridge", "elasticnet", "constant"}: Model fitted at the root. NULL uses |
split_search |
Character {"stump", "exhaustive"}: How a split is chosen. |
split_features |
Optional Character vector: Features that may define a split. NULL imposes no constraint, so every feature may. |
linear_features |
Optional Character vector: Features that get a slope in the node models. NULL imposes no constraint, so every feature does. |
global_features |
Optional Character vector: Linear features whose slope is shared by every leaf. Must be a subset of |
line_search_max |
Numeric (0, Inf): Largest absolute step the line search may take. |
root_forward_stop |
(Tunable) Optional Character {"bic", "aic", "none"}: |
root_node_test |
(Tunable) Optional Character {"none", "aic", "bic"}: |
Every node carries a constant, as any decision tree's nodes do. node_model
selects the model fitted at each node: "constant" for that constant alone,
or a regularized linear model on top of it. That, with max_leaves and
gamma, makes LINAD a generalization: the familiar algorithms are points in
its hyperparameter space, and everything between them is reachable too.
LINADHyperparameters object.
Each of the following is a special case of LINAD, recovered exactly:
max_leaves = 1. Nothing is split, so the model
is the root's alone – ridge, elastic net or forward stepwise selection,
whichever node_model names. Verified against a direct penalized solve.
node_model = "constant", gamma = 0, learning_rate = 1,
line_search = "none". Constants only, a hard partition and no
shrinkage. Fitted values match rpart's to machine precision.
The same, with gamma > 0. Soft weighting is
precisely what separates the Additive Tree from CART (Luna and
colleagues, 2019; see References).
Any node_model other than "constant", with
max_leaves > 1 – a tree whose nodes each carry a linear model.
Every setting named above is tunable, so the data can select where a dataset
belongs in that space:
a linear generating process should select a full root fit and no splitting,
while terminal nodes needing opposite-signed coefficients should select a
split first. root_learning_rate is the dial for that first step – at 0 the
root is the outcome's mean and the tree splits first, at 1 a full linear
model is fitted before any split.
LINAD fits a regularized linear model on the whole sample, splits on the gradient of the loss, fits a model on each side of the split, and repeats. Every update is linear, so the coefficients along a root-to-leaf path sum: the finished model is a tree with one linear model per leaf, optimized stagewise rather than fitted leaf by leaf. Prediction routes a case to its leaf and evaluates that leaf's coefficients.
Splits are found on the features as given, so a factor splits on a set of its levels; the node models use a reference-coded design matrix built internally. LINAD therefore needs no encoding preprocessor and handles factors directly.
max_leaves plays the role that the number of trees plays in gradient
boosting, and like it is chosen on held-out data: the tree is grown to
max_leaves and the size with the lowest validation loss is kept, unless
force_max_leaves is TRUE. Pass dat_validation to train to control the
set that choice is made on.
gamma lets every case carry weight into both branches, decaying as
gamma^depth, so each node's model is pulled toward what the rest of the
data supports. It is the algorithm's main variance-reducing device.
split_search = "exhaustive" scores each candidate split by the loss after
fitting both child models, rather than taking the best split of the gradient.
It costs more per split and finds structure no stump can see: an interaction
that changes another feature's slope without changing either side's mean
leaves no trace in any one feature's marginal fit.
A node's model is fitted to what its parent left, so its slopes are the
change to the parent's coefficients and lambda and alpha penalize that
change. At alpha = 1 the change is a lasso, so a feature whose coefficient
does not need to move gets exactly zero and inherits its parent's value: the
tree decides per feature, per node, whether an effect keeps adapting. Ridge
shrinks every change but zeroes none, so every coefficient moves at every
node.
node_test lets the tree decide, node by node, whether a linear model is
warranted at all: the slopes are kept only where they reduce the node's
residual sum of squares by more than they cost, and the node takes a plain
constant otherwise. A tree whose flat regions carry constants and whose
structured regions carry coefficients is both smaller to read and a statement
about where the response is locally linear. It buys that sparsity at a price
in accuracy, so it is off by default.
It applies to the shrinking models only. Forward selection charges the same
cost per term through forward_stop, and a set of terms that each paid for
itself always pays for itself jointly, so a node-level test could never
overturn it. One cost rule per node model, at the granularity that model
admits.
split_criterion sets what the stump scores a side by, and closes part of
that gap cheaply. "mean" scores the level its fit explains, which is the CART
criterion and is blind to curvature – a parabola's two halves have the same
mean by construction, so the correct split at the vertex scores near last.
"linear" adds the slope in the split variable, at one further pass per
feature per node, and on such a problem recovers the exhaustive search's fit.
It cannot recover the cross-variable case above, and where the change belongs
to another feature it fits the wrong one more confidently, so it is offered
as a tunable rather than the default.
split_binning discretizes numeric features before either search, so a
candidate split falls on a bin boundary rather than between any two distinct
values; n_cuts then thins what is left, for the exhaustive search only.
split_bin_type governs both: "frequency" spaces cuts evenly through the
cases, "width" evenly through the feature's range.
A feature's behavior has two independent axes: whether it may define a partition, and whether its modeled effect is absent, shared by every subgroup, or free to change along a path. Three name-based selectors set them, and on each of the three NULL imposes no constraint – which means "all" for the first two and "nothing pinned" for the third:
split_featuresFeatures the tree may split on.
linear_featuresFeatures that receive a slope in the node models.
global_featuresLinear features whose slope is shared by every
leaf: the root estimates it and no node below may change it. Must be a
subset of linear_features where that is set.
The axes are independent, so a feature may split without entering any node model, enter every node model without ever splitting, do both, or neither. Roles are assigned to source features: naming a factor moves all of its encoded columns together, never one of them.
Declaring effect scope turns LINAD into a varying-coefficient model with a
hierarchical form – a global baseline plus the node deviations accumulated
down the path. global is a hard constraint on the coefficient: it holds
exactly, at any gamma. gamma is the soft, data-driven version of the same
idea, pulling every node's fit toward what the rest of the data supports
until, at gamma = 1, every coefficient is effectively global. The two
compose without interacting: gamma decides how much a node's adaptive
coefficients may move, and global_features decides which coefficients are
allowed to move at all.
Because a global coefficient is estimated at the root, root_learning_rate
shrinks it: at 0 the root fits no slopes and a global feature carries no
effect anywhere.
The constrained family keeps useful reductions. No splits (max_leaves = 1)
is a penalized linear model; node_model = "constant" is a tree of
constants; making every linear feature global gives a tree with shared
coefficients and node-specific constants; and leaving all three NULL
reproduces unconstrained LINAD exactly.
Restricting the split set is also the largest single speed-up available on wide data, since the search cost is linear in the number of candidate features.
learning_rate shrinks the update made at each node. It does not shrink
the root, which root_learning_rate governs and which defaults to 1: the
root model is the initialization F_0, not a boosting step, and shrinking an
initialization is not meaningful.
The consequence is worth stating, because it surprises: however small
learning_rate is, the fit never falls below a single global linear model.
On data whose signal is largely linear, that model is already good, so
shrinking the tree's correction moves the metrics very little and two very
different small learning rates look alike. On a signal the root cannot
represent – a step with no linear component – the same sweep moves test
R-squared from 0.58 to 0.97.
To shrink everything, including the root, set root_learning_rate to the
same value. That recovers the familiar picture in which a small rate leaves
the model badly under-fitted: at 1e-6 the fit reduces to the constant that
alone minimizes the loss – the weighted mean of the outcome, or half its log
odds for a classification – which scores an R-squared of 0 rather than
anything worse. root_learning_rate interpolates between that constant and
the full linear model, never towards zero.
The line_search step does not counteract this. It is scale-free – for
squared error it is the exact minimizer along the update direction, which is
near 1 whatever the residual's size – so the applied step stays proportional
to learning_rate. Measured node updates scale linearly with it, by a factor
of 50 across a 50-fold change in the rate.
line_search and constant_rule each select among
alternative update rules – the scope of the Newton step, which frontier node
is split next, and how a node's constant is computed. There is no settled
best choice among them, so each is tunable.
EDG
Luna JM, Gennatas ED, Ungar LH, Eaton E, Diffenderfer ES, Jensen ST, Simone CB 2nd, Friedman JH, Solberg TD, Valdes G (2019). Building more accurate decision trees with the additive tree. Proceedings of the National Academy of Sciences, 116(40), 19887-19893. doi:10.1073/pnas.1816748116
linad_hyperparams <- setup_LINAD(max_leaves = 10L, learning_rate = 0.1) linad_hyperparams # The Additive Tree is LINAD without the linear models addtree_hyperparams <- setup_LINAD(node_model = "constant", gamma = 0.8) addtree_hyperparamslinad_hyperparams <- setup_LINAD(max_leaves = 10L, learning_rate = 0.1) linad_hyperparams # The Additive Tree is LINAD without the linear models addtree_hyperparams <- setup_LINAD(node_model = "constant", gamma = 0.8) addtree_hyperparams
Setup hyperparameters for LINADForest: a bagged ensemble of Linear Additive
Trees. Each tree is fitted on a bootstrap sample of the cases, restricted to
mtry_tree of the features, searching mtry_split of them at each split,
and chooses its own number of leaves on the cases its bootstrap left out.
setup_LINADForest( n_trees = 50L, mtry_split = NULL, mtry_tree = NULL, max_leaves = 20L, min_cases_split = 2L, min_cases_leaf = 1L, min_cases_node_model = NULL, nvmax = NULL, forward_stop = NULL, lambda = NULL, alpha = NULL, learning_rate = 1, root_nvmax = NULL, root_lambda = NULL, root_alpha = NULL, root_learning_rate = 1, n_cuts = NULL, gamma = 0.1, split_binning = NULL, split_bin_type = "frequency", node_test = NULL, split_criterion = NULL, line_search = "expansion", constant_rule = "closed_form", ifw = FALSE, patience = NULL, force_max_leaves = FALSE, smooth_validation_curve = NULL, node_model = "forward", root_model = NULL, split_search = "stump", split_features = NULL, linear_features = NULL, global_features = NULL, line_search_max = 1000, root_forward_stop = NULL, root_node_test = NULL )setup_LINADForest( n_trees = 50L, mtry_split = NULL, mtry_tree = NULL, max_leaves = 20L, min_cases_split = 2L, min_cases_leaf = 1L, min_cases_node_model = NULL, nvmax = NULL, forward_stop = NULL, lambda = NULL, alpha = NULL, learning_rate = 1, root_nvmax = NULL, root_lambda = NULL, root_alpha = NULL, root_learning_rate = 1, n_cuts = NULL, gamma = 0.1, split_binning = NULL, split_bin_type = "frequency", node_test = NULL, split_criterion = NULL, line_search = "expansion", constant_rule = "closed_form", ifw = FALSE, patience = NULL, force_max_leaves = FALSE, smooth_validation_curve = NULL, node_model = "forward", root_model = NULL, split_search = "stump", split_features = NULL, linear_features = NULL, global_features = NULL, line_search_max = 1000, root_forward_stop = NULL, root_node_test = NULL )
n_trees |
(Tunable) Integer [1, Inf): Number of trees in the forest. |
mtry_split |
(Tunable) Optional Integer [1, Inf): Features sampled at each split search. NULL scans every feature the tree holds. |
mtry_tree |
(Tunable) Optional Integer [1, Inf): Features available to a whole tree. NULL gives every tree every feature. |
max_leaves |
(Tunable) Integer [1, Inf): Largest number of terminal nodes to grow in each tree. |
min_cases_split |
(Tunable) Integer [2, Inf): Fewest cases a node may hold and still be considered for splitting. |
min_cases_leaf |
(Tunable) Integer [1, Inf): Fewest cases a split must leave on each side. |
min_cases_node_model |
(Tunable) Optional Integer [1, Inf): Fewest cases needed to fit a linear model at a node. Applies only when |
nvmax |
(Tunable) Optional Integer [1, Inf): Most terms forward selection may add beside the intercept. Applies only when |
forward_stop |
(Tunable) Optional Character {"bic", "aic", "none"}: Cost a term must earn to be added by forward selection. Applies only when |
lambda |
(Tunable) Optional Numeric [0, Inf): L2 penalty on the node models. Applies only when |
alpha |
(Tunable) Optional Numeric [0, 1]: Elastic-net mixing, 0 ridge to 1 lasso. Applies only when |
learning_rate |
(Tunable) Numeric (0, 1]: Shrinkage applied to every functional update. |
root_nvmax |
(Tunable) Optional Integer [1, Inf): |
root_lambda |
(Tunable) Optional Numeric [0, Inf): |
root_alpha |
(Tunable) Optional Numeric [0, 1]: |
root_learning_rate |
(Tunable) Numeric [0, 1]: Shrinkage applied to the root model's slopes. |
n_cuts |
(Tunable) Optional Integer [2, Inf): Cut points tried per feature. Applies only when |
gamma |
(Tunable) Numeric [0, 1]: Weight a case retains in the branch it does not belong to. 0 is a hard partition. |
split_binning |
(Tunable) Optional Integer [2, Inf): Discretize each numeric feature into this many bins and consider only bin boundaries as splits. |
split_bin_type |
(Tunable) Character {"frequency", "width"}: How bin edges are placed. |
node_test |
(Tunable) Optional Character {"none", "aic", "bic"}: Cost a node's slopes must earn over the constant alone. Applies only when |
split_criterion |
(Tunable) Optional Character {"mean", "linear"}: What the stump search scores a candidate side by. Applies only when |
line_search |
(Tunable) Character {"expansion", "child", "none"}: Scope of the Newton step for each update. |
constant_rule |
(Tunable) Character {"closed_form", "least_squares"}: How a node's constant is computed. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
patience |
(Tunable) Optional Integer [1, Inf): Expansions without validation improvement before growth stops. Requires a validation set. NULL disables patience-based early stopping. |
force_max_leaves |
Logical: If TRUE, grow every tree to |
smooth_validation_curve |
Optional Logical: If TRUE, smooth the out-of-bag curve before reading its minimum. Applies only when |
node_model |
Character {"forward", "ridge", "elasticnet", "constant"}: Model fitted at each node. |
root_model |
Optional Character {"forward", "ridge", "elasticnet", "constant"}: Model fitted at each tree's root. NULL uses |
split_search |
Character {"stump", "exhaustive"}: How a split is chosen. |
split_features |
Optional Character vector: Features that may define a split. NULL imposes no constraint, so every feature may. |
linear_features |
Optional Character vector: Features that get a slope in the node models. NULL imposes no constraint, so every feature does. |
global_features |
Optional Character vector: Linear features whose slope is shared by every leaf of a tree. Must be a subset of |
line_search_max |
Numeric (0, Inf): Largest absolute step the line search may take. |
root_forward_stop |
(Tunable) Optional Character {"bic", "aic", "none"}: |
root_node_test |
(Tunable) Optional Character {"none", "aic", "bic"}: |
LINADForest is designed to be used untuned. Every tree-level hyperparameter of setup_LINAD is available here and tunable, but the defaults are the configuration the ensemble was first evaluated with, and the one structural choice that usually needs tuning – how large each tree should be – is made per tree from data.
LINADForestHyperparameters object.
Three sources of variation, each acting at a different level:
Each tree is fitted on n cases drawn with
replacement, so roughly 37% of cases are out-of-bag for any given tree.
mtry_treeEach tree is restricted to a random subset of the features, for its splits and its node models alike. A tree's coefficients then cover only the features it held.
mtry_splitEach split search sees a fresh sample of the features
the tree holds, which decorrelates the trees further. If that sample
finds no split worth making, the node is searched again over every
feature, so mtry_split changes which split is made and never whether a
node can split at all.
Both mtry_* default to NULL, meaning every feature, which is the
configuration the ensemble was first evaluated with.
A LINAD tree picks its number of leaves on held-out data, as gradient
boosting picks its number of trees. A bootstrap produces held-out data for
free, so each tree selects its own size on its own out-of-bag cases and no
validation set has to be supplied or set aside. force_max_leaves = TRUE
turns the selection off and grows every tree to max_leaves, which is what
the ensemble's first evaluation did.
The same out-of-bag predictions give the fitted forest an error estimate with
no resampling, reported by print().
learning_rate defaults to 1, where a single tree uses 0.1. A lone LINAD tree shrinks each node
update because nothing else controls its variance; in a forest the averaging
does that, so each tree should be a strong learner – the same reasoning that
leaves a random forest's trees unpruned.
LINADForest parallelizes across trees, by process rather than by thread.
n_workers_algorithm therefore has an effect only when the run is not
already dispatching: inside a parallel outer fold the forest runs its trees
sequentially, since a fold may not dispatch again. For a threaded backend
such as Ranger the same setting means threads within each fold.
EDG
Wager S, Hastie T, Efron B (2014). Confidence intervals for random forests: the jackknife and the infinitesimal jackknife. Journal of Machine Learning Research, 15, 1625-1651.
linadforest_hyperparams <- setup_LINADForest(n_trees = 25L) linadforest_hyperparamslinadforest_hyperparams <- setup_LINADForest(n_trees = 25L) linadforest_hyperparams
Setup hyperparameters for LinearSVM training.
setup_LinearSVM(cost = 1, ifw = FALSE)setup_LinearSVM(cost = 1, ifw = FALSE)
cost |
(Tunable) Numeric (0, Inf): Cost of constraints violation. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from e1071::svm.
LinearSVMHyperparameters object.
EDG
linear_svm_hyperparams <- setup_LinearSVM(cost = 0.5, ifw = TRUE) linear_svm_hyperparamslinear_svm_hyperparams <- setup_LinearSVM(cost = 0.5, ifw = TRUE) linear_svm_hyperparams
Leave-one-out cross-validation: one resample per case. n_resamples is not
a parameter here because only the data can say how many cases there are –
resample() fills it in.
setup_LOOCV()setup_LOOCV()
LOOCVConfig object.
EDG
loocv_resampler <- setup_LOOCV() loocv_resamplerloocv_resampler <- setup_LOOCV() loocv_resampler
Setup hyperparameters for Multivariate Adaptive Regression Splines training.
setup_MARS( degree = 1L, penalty = NULL, nk = NULL, nprune = NULL, thresh = 0.001, minspan = 0L, endspan = 0L, newvar_penalty = 0, fast_k = 20L, pmethod = "backward", nfold = 0L, ncross = 1L, stratify = TRUE, fast_beta = 1, ifw = FALSE )setup_MARS( degree = 1L, penalty = NULL, nk = NULL, nprune = NULL, thresh = 0.001, minspan = 0L, endspan = 0L, newvar_penalty = 0, fast_k = 20L, pmethod = "backward", nfold = 0L, ncross = 1L, stratify = TRUE, fast_beta = 1, ifw = FALSE )
degree |
(Tunable) Integer [1, Inf): Maximum degree of interaction. 1 builds an additive model with no interaction terms. |
penalty |
(Tunable) Optional Numeric [-1, Inf): Generalized Cross Validation penalty per knot. NULL uses 3 when |
nk |
(Tunable) Optional Integer [1, Inf): Maximum number of terms, including the intercept, created by the forward pass. NULL lets earth derive it from the number of features. |
nprune |
(Tunable) Optional Integer [1, Inf): Maximum number of terms, including the intercept, retained after pruning. NULL places no cap on the terms retained, which pruning still selects by |
thresh |
(Tunable) Numeric [0, 1): Forward pass stopping threshold: stop once adding a term changes R-squared by less than this. |
minspan |
(Tunable) Integer (-Inf, Inf): Minimum number of observations between knots. 0 derives the value internally, and a negative value instead sets the maximum number of equally spaced knots per feature. |
endspan |
(Tunable) Integer [0, Inf): Minimum number of observations before the first and after the final knot. 0 derives the value internally. |
newvar_penalty |
(Tunable) Numeric [0, Inf): Penalty for adding a feature not already in the model during the forward pass. |
fast_k |
(Tunable) Integer [0, Inf): Maximum number of parent terms considered at each step of the forward pass. 0 disables Fast MARS. |
pmethod |
Character {"backward", "none", "exhaustive", "forward", "seqrep", "cv"}: Pruning method. "cv" requires |
nfold |
Integer [0, Inf): Number of cross-validation folds used to estimate out-of-fold R-squared. 0 disables cross-validation. |
ncross |
Integer [1, Inf): Number of times the |
stratify |
Logical: If TRUE, stratify the cross-validation folds on the outcome. |
fast_beta |
Numeric [0, 1]: Fast MARS aging coefficient. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from earth::earth.
get_varimp() returns earth's three importance criteria, in this order:
importance (the GCV criterion), rss (the RSS criterion), and
subset_proportion (the fraction of pruning subsets that retain the
feature). See varimp_super in train_MARS.R for how each is derived.
MARSHyperparameters object.
EDG
mars_hyperparams <- setup_MARS(degree = 2L, nprune = 10L) mars_hyperparamsmars_hyperparams <- setup_MARS(degree = 2L, nprune = 10L) mars_hyperparams
Stress-minimizing multidimensional scaling with vegan::monoMDS(): finds k
coordinates per case whose distances match the dissimilarities between cases
as closely as possible, measured by Kruskal's stress-1. For classical
(Torgerson) scaling, which solves an eigenproblem instead, see setup_PCoA.
setup_MDS( k = 2L, dist_method = "euclidean", model = "global", nstart = 20L, max_iter = 200L, features = NULL )setup_MDS( k = 2L, dist_method = "euclidean", model = "global", nstart = 20L, max_iter = 200L, features = NULL )
k |
Integer [1, Inf): Number of components. (passed to |
dist_method |
Character {"euclidean", "manhattan", "chord", "bray",
"canberra", "jaccard", "kulczynski", "hellinger"}: Dissimilarity between
cases, computed with |
model |
Character {"global", "local", "linear"}: "global" is nonmetric
MDS (one monotone regression); "local" fits one monotone regression per case;
"linear" is metric MDS. (passed to |
nstart |
Integer [1, Inf): Number of starting configurations. 1 starts from the classical scaling solution only. |
max_iter |
Integer [1, Inf): Maximum number of iterations per start.
(passed to |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
Each start runs vegan::monoMDS() from its own initial configuration, and
the one with the lowest stress is kept. The first start is the classical
scaling solution, stats::cmdscale(); if that has fewer than k dimensions
with positive eigenvalues, the missing ones are random. Every other start is
uniform on [-1, 1]. The random values come from R's random number
generator, so the execution config's seed reproduces the fit. The final configuration is centered, scaled and rotated to its principal
axes, so its components are uncorrelated, but the first j components of a
k-dimensional solution are not the j-dimensional solution.
MDS cannot be applied to new data, so it cannot be used as the decomposition step in train, and reconstruct does not apply.
MDSConfig object.
EDG
mds_config <- setup_MDS(k = 2L, dist_method = "manhattan") mds_configmds_config <- setup_MDS(k = 2L, dist_method = "manhattan") mds_config
MiraiExecutionConfig
Parallel execution through mirai. Takes no plan: mirai has no
equivalent of a future_plan, which is why it is not an argument here.
setup_MiraiExecution( n_workers = NULL, n_workers_outer = NULL, n_workers_tuning = NULL, n_workers_algorithm = NULL, device = NULL, on_error = c("continue", "stop", "stop_outer"), seed = NULL, shared_memory = c("auto", "none", "always"), warm_workers = TRUE )setup_MiraiExecution( n_workers = NULL, n_workers_outer = NULL, n_workers_tuning = NULL, n_workers_algorithm = NULL, device = NULL, on_error = c("continue", "stop", "stop_outer"), seed = NULL, shared_memory = c("auto", "none", "always"), warm_workers = TRUE )
n_workers |
Integer [1, Inf): Number of parallel workers. Left |
n_workers_outer |
Optional Integer [1, Inf): Workers for outer resampling, overriding the automatic assignment. |
n_workers_tuning |
Optional Integer [1, Inf): Workers for tuning, overriding the automatic assignment. |
n_workers_algorithm |
Optional Integer [1, Inf): Threads for a self-parallelizing algorithm, overriding the automatic assignment. |
device |
Optional |
on_error |
Character {"continue", "stop", "stop_outer"}: Failure policy.
|
seed |
Optional Integer [0, Inf): Master seed for the run's computation RNG,
from which one independent substream per parallel task is derived. Left |
shared_memory |
Character {"none", "auto", "always"}: Whether to hand workers
the training data through OS shared memory instead of serializing a copy to each.
|
warm_workers |
Logical: Load rtemis in every worker as the pool is built, rather than leaving each worker to load it on its first task. Either way the result is the same; TRUE records the loading time in the run's worker-pool setup step. |
See setup_FutureExecution for how the three worker levels are assigned and how the run's seed is resolved; both are identical under either backend.
MiraiExecutionConfig object.
EDG
setup_MiraiExecution(n_workers = 2L)setup_MiraiExecution(n_workers = 2L)
Setup hyperparameters for MLP (Multilayer Perceptron) training.
setup_MLP( hidden_units = NULL, shape = NULL, shape_layers = NULL, shape_max_units = NULL, activation = "relu", norm = NULL, residual = FALSE, dropout = 0, input_dropout = 0, weight_decay = 0, l1_penalty = 0, embedding_dim = NULL, embedding_dropout = 0, optimizer = "adamw", lr = 0.001, batch_size = 256L, max_epochs = 100L, max_grad_norm = NULL, ifw = FALSE, norm_first = FALSE, bias = TRUE, embeddings = TRUE, beta1 = NULL, beta2 = NULL, eps = NULL, momentum = NULL, lr_scheduler = NULL, patience = 10L, loss = NULL, seed = NULL, num_workers = 0L, drop_last = FALSE )setup_MLP( hidden_units = NULL, shape = NULL, shape_layers = NULL, shape_max_units = NULL, activation = "relu", norm = NULL, residual = FALSE, dropout = 0, input_dropout = 0, weight_decay = 0, l1_penalty = 0, embedding_dim = NULL, embedding_dropout = 0, optimizer = "adamw", lr = 0.001, batch_size = 256L, max_epochs = 100L, max_grad_norm = NULL, ifw = FALSE, norm_first = FALSE, bias = TRUE, embeddings = TRUE, beta1 = NULL, beta2 = NULL, eps = NULL, momentum = NULL, lr_scheduler = NULL, patience = 10L, loss = NULL, seed = NULL, num_workers = 0L, drop_last = FALSE )
|
(Tunable) Optional Integer [1, Inf) vector: Units in each hidden layer, one value per layer. NULL generates the widths from the shape settings. |
|
shape |
(Tunable) Optional Character {"funnel", "constant", "triangle", "long_funnel", "diamond", "hexagon", "stairs"}: Profile of the generated hidden layer widths. Ignored when |
shape_layers |
(Tunable) Optional Integer [1, Inf): Number of hidden layers to generate. Ignored when |
shape_max_units |
(Tunable) Optional Integer [1, Inf): Widest generated hidden layer. Ignored when |
activation |
(Tunable) Character {"relu", "gelu", "silu", "elu", "selu", "leaky_relu", "tanh"}: Activation applied after every hidden layer. |
norm |
(Tunable) Optional Character {"batch_norm", "layer_norm"}: Normalization applied in every hidden layer. NULL applies none. |
residual |
(Tunable) Logical: If TRUE, add a residual connection around every hidden layer, projected when the layer changes width. |
dropout |
(Tunable) Numeric [0, 1): Dropout probability applied after every hidden layer. |
input_dropout |
(Tunable) Numeric [0, 1): Dropout probability applied to the encoded input. |
weight_decay |
(Tunable) Numeric [0, Inf): L2 penalty, decoupled from the gradient under the adamw optimizer. |
l1_penalty |
(Tunable) Numeric [0, Inf): L1 penalty on the linear weights, added to the loss. |
embedding_dim |
(Tunable) Optional Integer [1, Inf): Width of every embedding. NULL sizes each from its feature's cardinality. |
embedding_dropout |
(Tunable) Numeric [0, 1): Dropout probability applied to the concatenated embeddings. |
optimizer |
(Tunable) Character {"adamw", "adam", "sgd", "rmsprop"}: Optimization algorithm. |
lr |
(Tunable) Numeric (0, Inf): Learning rate. |
batch_size |
(Tunable) Integer [1, Inf): Cases per optimization step. |
max_epochs |
(Tunable) Integer [1, Inf): Largest number of passes over the training set. |
max_grad_norm |
(Tunable) Optional Numeric (0, Inf): Clip the gradient norm to this value before each step. NULL does not clip. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
norm_first |
Logical: If TRUE, normalize before the activation rather than after it. |
bias |
Logical: If TRUE, give every hidden layer and the output layer a bias term. |
embeddings |
Logical: If TRUE, represent each categorical feature by a learned embedding; if FALSE, one-hot encode them. |
beta1 |
Optional Numeric [0, 1): Exponential decay rate of the first moment estimate. Applies to the adam and adamw optimizers. |
beta2 |
Optional Numeric [0, 1): Exponential decay rate of the second moment estimate. Applies to the adam and adamw optimizers. |
eps |
Optional Numeric (0, Inf): Term added to the denominator for numerical stability. Applies to the adam, adamw and rmsprop optimizers. |
momentum |
Optional Numeric [0, Inf): Momentum factor. Applies to the sgd and rmsprop optimizers. |
lr_scheduler |
Optional Character {"step", "cosine_annealing", "one_cycle", "reduce_on_plateau"}: Learning-rate schedule. NULL holds the learning rate fixed. |
patience |
Integer [1, Inf): Epochs without validation improvement before stopping early. |
loss |
Optional Character {"mse", "l1", "smooth_l1", "cross_entropy"}: Training objective. NULL sets it from the outcome type. |
seed |
Optional Integer: Random seed for weight initialization, dropout and batch shuffling. |
num_workers |
Integer [0, Inf): Subprocesses used to load batches. |
drop_last |
Logical: If TRUE, drop the last incomplete batch of each training epoch. |
A fully connected feedforward network built and trained with torch, for
regression, binary and multiclass classification.
Architecture. Give the hidden layers directly with hidden_units –
c(256L, 128L, 64L) is three layers of those widths – or leave it NULL and
let shape, shape_layers and shape_max_units generate them. Setting both
is an error. The generated profiles are
funnel (a linear taper from the widest layer down to a third of it),
constant, triangle (a linear rise from the input width), long_funnel,
diamond, hexagon and stairs; the vocabulary is Talos's, by way of
AutoPyTorch. shape_max_units defaults to four times the encoded input
width, clamped to [64, 512] and never below that width.
The tabular deep-learning benchmarks tune and publish constant-width MLPs,
so shape = "constant" is what to compare against even though funnel is
the better default before tuning on the small-n, wide-p data rtemis is usually
pointed at.
Tuning. hidden_units is tunable like any other hyperparameter, with one
architecture per candidate:
setup_MLP(hidden_units = tune_over(c(64L, 32L), c(128L, 64L, 32L))). A
single bare vector there is one architecture, not a set of candidates, and is
rejected as such.
Categorical features are represented by learned embeddings, each sized
min(600, round(1.6 * cardinality^0.56)) unless embedding_dim fixes them
all. embeddings = FALSE one-hot encodes them. Numeric features are always
centered and scaled, and the fitted encoder is re-applied at predict time.
Device and reproducibility. The device is the execution config's: see the
device argument of setup_FutureExecution. Unset picks cuda where
available and cpu otherwise, and train names the one it resolved. "mps",
the Apple silicon GPU, runs only when named. In rtemis benchmarks on an Apple M5
the CPU was faster for every network narrower than about 1024 units or
trained in batches smaller than about 2048 cases, often by 2 to 5 times; with
both, and thousands of features, "mps" was faster by up to about 25%. It
also slows down across many fits in one R session. Try it for a wide network
on wide data. A seed governs weight initialization and batch shuffling on
mps but not dropout, so a seeded mps fit reproduces exactly until a
dropout rate is non-zero. That combination warns.
Early stopping needs a validation set: pass dat_validation to train,
and the fit keeps the weights of the best validation epoch rather than the
last. Without one it runs the full max_epochs and patience has no effect.
l1_penalty is not weight_decay. weight_decay is the L2 term the
torch optimizer applies, decoupled from the gradient under adamw;
l1_penalty has no torch equivalent and is accumulated over the linear
weights and added to the loss.
Batch normalization and dropout interact badly when combined; both are off by default.
The scheduler takes no settings of its own – each configures itself from
the run's budget: step decays by 0.1 every max_epochs / 3 epochs,
cosine_annealing anneals over max_epochs, one_cycle peaks at lr over
the run's real step count, and reduce_on_plateau decays by 0.1 after half
the early-stopping patience.
get_varimp() returns NULL: a torch MLP has no native importance measure.
MLPHyperparameters object.
EDG
mlp_hyperparams <- setup_MLP(hidden_units = c(64L, 32L), max_epochs = 20L) mlp_hyperparamsmlp_hyperparams <- setup_MLP(hidden_units = c(64L, 32L), max_epochs = 20L) mlp_hyperparams
Setup hyperparameters for modality stacking: a SuperLearner whose base learners each see one group of features.
setup_ModalityStacking( feature_groups = NULL, base_learners = list(setup_GLM(), setup_GLMNET(), setup_Ranger()), meta_learner = setup_NNLS(), inner_resampling_config = setup_KFold(n_resamples = 10L), discrete = FALSE, expand_search_spaces = TRUE, ifw = FALSE )setup_ModalityStacking( feature_groups = NULL, base_learners = list(setup_GLM(), setup_GLMNET(), setup_Ranger()), meta_learner = setup_NNLS(), inner_resampling_config = setup_KFold(n_resamples = 10L), discrete = FALSE, expand_search_spaces = TRUE, ifw = FALSE )
feature_groups |
Optional List: Features each base learner sees, as a named list of character vectors keyed by base learner name. Required by train. |
base_learners |
List of |
meta_learner |
|
inner_resampling_config |
|
discrete |
(Tunable) Logical: If TRUE, keep the single lowest-risk library entry rather than the weighted combination. |
expand_search_spaces |
Logical: If TRUE, expand a base learner's search space into one library entry per combination. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
With a wide x formed by concatenating modalities – imaging, genomics, labs
– and few cases, one model per modality can beat one model over everything,
and each modality can take the algorithm that suits it: SPLS for correlated
blocks, LASSO for sparse ones, gradient boosting for interactions. Training is
otherwise identical to setup_SuperLearner: cross-validated predictions from
each base learner, combined by the meta learner.
feature_groups maps each base learner's name to the features it sees. Pass
a single Hyperparameters object as base_learners to use the same algorithm
on every group.
Whether this beats one model over the concatenated modalities is the empirical
question it exists to answer, and two things decide it. Each base learner sees
only its own group, so what every other modality contributes to the outcome
is irreducible noise to it, which can hide a real signal in a weak modality
behind a strong one. And the default meta learner returns a convex
combination, which averages the modalities rather than adding them: where they
are complementary rather than competing, meta_learner = setup_NNLS(normalize = FALSE) lets their contributions sum.
feature_groups is checked against the training data at train time, not at
setup: it names columns, and there is no data to name them in yet.
Supports regression and binary classification.
ModalityStackingHyperparameters object.
EDG
modality_hyperparams <- setup_ModalityStacking( feature_groups = list(a = c("Sepal.Length", "Sepal.Width"), b = "Petal.Length"), base_learners = list(a = setup_GLM(), b = setup_CART()) ) modality_hyperparamsmodality_hyperparams <- setup_ModalityStacking( feature_groups = list(a = c("Sepal.Length", "Sepal.Width"), b = "Petal.Length"), base_learners = list(a = setup_GLM(), b = setup_CART()) ) modality_hyperparams
Setup hyperparameters for monotonic Highly Adaptive Lasso training.
setup_MonotonicHAL( smoothness_orders = 1L, reduce_basis = NULL, num_knots = NULL, penalized = TRUE, use_min = TRUE, nfolds = 10L, seed = NULL, ifw = FALSE )setup_MonotonicHAL( smoothness_orders = 1L, reduce_basis = NULL, num_knots = NULL, penalized = TRUE, use_min = TRUE, nfolds = 10L, seed = NULL, ifw = FALSE )
smoothness_orders |
(Tunable) Integer [0, 1]: Smoothness of the basis functions: 0 fits zero-order indicators and yields a step function, 1 fits piecewise linear splines and yields a continuous one. |
reduce_basis |
(Tunable) Optional Numeric (0, 1]: Minimum proportion of cases a basis function must be non-zero in to be kept. Applies only when |
num_knots |
Optional Integer [1, Inf): Number of knots spanning each feature. NULL generates them from smoothness_orders. |
penalized |
Logical: If TRUE, apply the lasso penalty to the basis functions; if FALSE, remove it. |
use_min |
Logical: If TRUE, select |
nfolds |
Integer [3, Inf): Largest number of folds of the internal cross-validation that selects lambda. |
seed |
Optional Integer: Random seed for the internal cross-validation's fold assignment. NULL leaves it drawn from the ambient RNG. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
A Highly Adaptive Lasso restricted to additive, monotonic non-decreasing
fits. hal9001::fit_hal is given a formula that constrains every basis
function's coefficient to be non-negative, and the interaction degree is
fixed at 1. Regression uses the gaussian family, binary classification the
binomial one; hal9001 has no multinomial family, so multiclass
classification is not supported.
The intended use is probability calibration, where the single feature is a classifier's score. Monotonicity is what makes that safe: a calibration map that reorders scores changes the ranking and so changes AUC, and a non-decreasing map cannot. Pass it to calibrate to use it instead of the default calibrator, setup_Isotonic.
Relative to Isotonic, which is the other monotonic calibrator, this fits on
the logit scale, so it does not saturate at 0 and 1 the way the boundary
bins of isotonic regression do – it can still round to an endpoint in
double precision
when the input scores are themselves extreme. At smoothness_orders = 1 it
is strictly increasing rather than a step function, so it introduces no ties
and leaves AUC unchanged.
smoothness_orders is the one substantive choice. 0 fits indicator basis
functions and recovers a step function; 1 fits piecewise linear splines and
yields a continuous map.
penalized = FALSE removes the lasso penalty, giving the non-parametric
maximum likelihood estimate over the monotonic class. Combined with
smoothness_orders = 0 that is isotonic regression, up to the logit-scale
parameterization.
lambda is selected by cross-validation inside the fit and is not a search
dimension. seed fixes that cross-validation's fold assignment; nfolds
and use_min control it. Calibration sets are often small, so nfolds is
an upper bound: training backs off to as many folds as the data supports at
three cases each, and says so at verbosity >= 1.
get_varimp() reports the same two measures as setup_HAL, importance
and max_coefficient. Both are of limited use at a single feature.
MonotonicHALHyperparameters object.
EDG
monotonichal_hyperparams <- setup_MonotonicHAL(smoothness_orders = 0L) monotonichal_hyperparamsmonotonichal_hyperparams <- setup_MonotonicHAL(smoothness_orders = 0L) monotonichal_hyperparams
Setup the subsampled average silhouette width criterion for setup_PAMK: the silhouette width is computed on random subsets of the cases and averaged, which makes the score affordable on many cases.
setup_MultiASWCriterion(n_subsets = NULL)setup_MultiASWCriterion(n_subsets = NULL)
n_subsets |
Optional Integer [1, Inf): Number of random subsets the average silhouette width is computed on. |
n_subsets maps to fpc::pamk()'s ns.
MultiASWCriterionConfig object.
EDG
setup_MultiASWCriterion(n_subsets = 20L)setup_MultiASWCriterion(n_subsets = 20L)
Setup NeuralGasConfig
setup_NeuralGas(k = 3L, dist = "euclidean", features = NULL)setup_NeuralGas(k = 3L, dist = "euclidean", features = NULL)
k |
Integer [1, Inf): Number of clusters. |
dist |
Character {"euclidean", "manhattan"}: Distance measure to use. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
NeuralGasConfig object.
EDG
neuralgas_config <- setup_NeuralGas(k = 4L, dist = "euclidean") neuralgas_configneuralgas_config <- setup_NeuralGas(k = 4L, dist = "euclidean") neuralgas_config
Setup NMF config.
setup_NMF(k = 2L, method = "brunet", nrun = 1L, features = NULL)setup_NMF(k = 2L, method = "brunet", nrun = 1L, features = NULL)
k |
Integer [1, Inf): Number of components. |
method |
Character: NMF method. See |
nrun |
Integer [1, Inf): Number of runs to perform. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
NMFConfig object.
EDG
nmf_config <- setup_NMF(k = 3L) nmf_confignmf_config <- setup_NMF(k = 3L) nmf_config
Setup hyperparameters for non-negative least squares.
setup_NNLS(normalize = TRUE, ifw = FALSE)setup_NNLS(normalize = TRUE, ifw = FALSE)
normalize |
(Tunable) Logical: If TRUE, scale the coefficients to sum to 1. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
NNLS fits y ~ Xb subject to b >= 0, with no intercept. It exists as the
default meta learner of the stacked meta learners (setup_SuperLearner,
setup_ModalityStacking), where the predictors are the base learners'
cross-validated predictions and a non-negative, sum-to-one coefficient vector
is the ensemble weighting. It is a poor general-purpose learner: with no
intercept and a sign constraint it can only fit outcomes that the predictors
already span.
With normalize = TRUE the coefficients are scaled to sum to 1, so the fit is
a convex combination of the predictors. For classification the outcome is
coded 0/1 on the second factor level and the fitted values are read as
probabilities of that level; unnormalized coefficients do not guarantee a
value in [0, 1], so predictions are clamped.
Get more information from nnls::nnls.
NNLSHyperparameters object.
EDG
nnls_hyperparams <- setup_NNLS(normalize = FALSE) nnls_hyperparamsnnls_hyperparams <- setup_NNLS(normalize = FALSE) nnls_hyperparams
Setup the Nystrom approximation for setup_SpectralRBF or
setup_SpectralLaplace. Passing one turns the approximation on; its
sample says how many cases it samples.
setup_Nystrom(sample = NULL)setup_Nystrom(sample = NULL)
sample |
Optional Integer [1, Inf): Number of cases the approximation samples. Must be fewer than the number of cases. Unset samples one sixth of them. |
sample maps to kernlab::specc()'s nystrom.sample; passing the config
at all sets nystrom.red = TRUE.
NystromConfig object.
EDG
setup_Nystrom(sample = 200L)setup_Nystrom(sample = 200L)
Setup a PAMConfig object for Partitioning Around Medoids (PAM) clustering,
via the 'cluster' package.
setup_PAM( k = 3L, dist = "euclidean", stand = FALSE, do_swap = TRUE, variant = "original", nstart = NULL, features = NULL )setup_PAM( k = 3L, dist = "euclidean", stand = FALSE, do_swap = TRUE, variant = "original", nstart = NULL, features = NULL )
k |
Integer [1, Inf): Number of clusters. Must be fewer than the number of cases. |
dist |
Character {"euclidean", "manhattan"}: Distance measure to use. |
stand |
Logical: If TRUE, standardize each variable before computing dissimilarities. |
do_swap |
Logical: If TRUE, perform the swap phase. |
variant |
Character {"original", "o_1", "o_2", "f_3", "f_4", "f_5", "faster"}: Algorithm variant; "original" is the published algorithm, the others trade exactness for speed. |
nstart |
Optional Integer [1, Inf): Number of random starts. NULL uses the deterministic build phase instead of drawing the initial medoids at random. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
PAM is the medoid-based counterpart of k-means: each cluster is represented by one of the cases, which makes it usable with non-Euclidean dissimilarities and less sensitive to outliers.
Argument names are rtemis' own. They map to cluster::pam() as:
dist -> metric, do_swap -> do.swap; the rest keep their names.
PAMConfig object.
EDG
Kaufman L, Rousseeuw PJ (1990). Finding Groups in Data: An Introduction to Cluster Analysis. Wiley. doi:10.1002/9780470316801
pam_config <- setup_PAM(k = 3L) pam_configpam_config <- setup_PAM(k = 3L) pam_config
Setup a PAMKConfig object for Partitioning Around Medoids with estimation
of the number of clusters (PAMK), via the 'fpc' package.
setup_PAMK( krange = 2:10, criterion = setup_ASWCriterion(), use_pam = TRUE, scaling = FALSE, alpha = 0.001, features = NULL )setup_PAMK( krange = 2:10, criterion = setup_ASWCriterion(), use_pam = TRUE, scaling = FALSE, alpha = 0.001, features = NULL )
krange |
Integer [1, Inf) vector: Candidate numbers of clusters to compare. Must include at least one value greater than 1. |
criterion |
|
use_pam |
Logical: If TRUE, fit each candidate with PAM; if FALSE, with CLARA. |
scaling |
Logical: If TRUE, scale each variable by its root mean square after centering. |
alpha |
Numeric [0, 1]: Significance level of the Duda-Hart test, used only when 1 is among the candidates. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
PAMK fits PAM (or CLARA) for every candidate in krange and keeps the one
scoring best under criterion. There is therefore no k to set, and the
number of clusters chosen is reported by the resulting Clustering.
Argument names are rtemis' own. They map to fpc::pamk() as:
use_pam -> usepam; the criterion's type -> criterion and its
n_subsets -> ns; the rest keep their names.
fpc::pamk() also accepts a per-variable numeric vector for scaling; only
the logical form is exposed here. Scale by column with preprocess instead,
where the decision is recorded and replayed with the data.
PAMKConfig object.
EDG
Kaufman L, Rousseeuw PJ (1990). Finding Groups in Data: An Introduction to Cluster Analysis. Wiley. doi:10.1002/9780470316801
pamk_config <- setup_PAMK(krange = 2:5) pamk_config setup_PAMK(krange = 2:5, criterion = setup_MultiASWCriterion(n_subsets = 20L))pamk_config <- setup_PAMK(krange = 2:5) pamk_config setup_PAMK(krange = 2:5, criterion = setup_MultiASWCriterion(n_subsets = 20L))
ParquetIngestConfig
Reading a Parquet file. It declares its own types, so there is nothing to tell the reader except which reader to be.
setup_ParquetIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE, reader = "arrow" )setup_ParquetIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE, reader = "arrow" )
columns |
Optional Named vector: Declared column types, keyed by column
name, in the |
character2factor |
Logical: If TRUE, read character columns as factors. |
clean_colnames |
Logical: If TRUE, normalize column names. |
remove_duplicates |
Logical: If TRUE, drop rows repeating an earlier row. |
reader |
Character {"arrow", "nanoparquet"}: Library used to read the file. |
ParquetIngestConfig object.
EDG
setup_ParquetIngest()setup_ParquetIngest()
Setup PCA config.
setup_PCA(k = 3L, center = TRUE, scale = TRUE, tol = NULL, features = NULL)setup_PCA(k = 3L, center = TRUE, scale = TRUE, tol = NULL, features = NULL)
k |
Integer [1, Inf): Number of components. (passed to |
center |
Logical: If TRUE, center the data. |
scale |
Logical: If TRUE, scale the data. |
tol |
Optional Numeric [0, Inf): Tolerance. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
PCAConfig object.
EDG
pca_config <- setup_PCA(k = 3L) pca_configpca_config <- setup_PCA(k = 3L) pca_config
Principal coordinates analysis, also called classical or Torgerson
multidimensional scaling: an eigendecomposition of the doubly centered
squared dissimilarities between cases, with stats::cmdscale(). With
dist_method = "euclidean" the components equal PCA scores of the centered,
unscaled data, up to sign; other dissimilarities are what PCoA is for.
setup_PCoA(k = 2L, dist_method = "euclidean", features = NULL)setup_PCoA(k = 2L, dist_method = "euclidean", features = NULL)
k |
Integer [1, Inf): Number of components. (passed to |
dist_method |
Character {"euclidean", "manhattan", "chord", "bray",
"canberra", "jaccard", "kulczynski", "hellinger"}: Dissimilarity between
cases, computed with |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
PCoA applies to new data with Gower's (1968) out-of-sample formula, from the dissimilarities between each new case and the training cases, so it can be used as the decomposition step in train. Applying a fit to its own training data reproduces the fitted components. Because those dissimilarities are needed, the fit keeps the training feature matrix, and its size grows with the number of training cases.
Dissimilarities other than "euclidean", "chord" and "hellinger" generally give some negative eigenvalues; only dimensions with positive eigenvalues are returned, and asking for more is an error that states how many there are. reconstruct does not apply.
PCoAConfig object.
EDG
pcoa_config <- setup_PCoA(k = 2L, dist_method = "bray") pcoa_configpcoa_config <- setup_PCoA(k = 2L, dist_method = "bray") pcoa_config
PredefinedPartitionConfig
A split already recorded in the data itself.
setup_PredefinedPartition( column = NULL, training_value = "train", test_value = "test" )setup_PredefinedPartition( column = NULL, training_value = "train", test_value = "test" )
column |
Optional Character: Name of the column holding each case's partition label. |
training_value |
Character: Value in |
test_value |
Character: Value in |
PredefinedPartitionConfig object.
EDG
setup_PredefinedPartition(column = "split")setup_PredefinedPartition(column = "split")
Creates a PreprocessorConfig object, which can be used in preprocess.
setup_Preprocessor( complete_cases = FALSE, remove_features_thres = NULL, remove_cases_thres = NULL, missingness = FALSE, impute = FALSE, impute_type = c("missRanger", "micePMM", "meanMode"), impute_missRanger_params = list(pmm.k = 3L, maxiter = 10L, num.trees = 500L), impute_numeric = c("mean", "median"), impute_categorical = "mode", impute_numeric_values = NULL, impute_level_values = NULL, integer2factor = FALSE, integer2numeric = FALSE, logical2factor = FALSE, logical2numeric = FALSE, numeric2factor = FALSE, numeric2factor_levels = NULL, numeric_cut_n = 0L, numeric_cut_labels = FALSE, numeric_quant_n = 0L, numeric_quant_NAonly = FALSE, unique_len2factor = 0L, character2factor = FALSE, factorNA2missing = FALSE, factorNA2missing_level = "missing", factor2integer = FALSE, factor2integer_startat0 = TRUE, factor2integer_levels = NULL, scale = FALSE, center = scale, scale_centers = NULL, scale_coefficients = NULL, remove_constants = FALSE, remove_constants_skip_missing = TRUE, remove_features = NULL, remove_duplicates = FALSE, one_hot = FALSE, one_hot_levels = NULL, add_date_features = FALSE, date_features = c("weekday", "month", "year"), add_holidays = FALSE, holidays = c("USLaborDay", "NewYearsDay", "ChristmasDay"), exclude = NULL )setup_Preprocessor( complete_cases = FALSE, remove_features_thres = NULL, remove_cases_thres = NULL, missingness = FALSE, impute = FALSE, impute_type = c("missRanger", "micePMM", "meanMode"), impute_missRanger_params = list(pmm.k = 3L, maxiter = 10L, num.trees = 500L), impute_numeric = c("mean", "median"), impute_categorical = "mode", impute_numeric_values = NULL, impute_level_values = NULL, integer2factor = FALSE, integer2numeric = FALSE, logical2factor = FALSE, logical2numeric = FALSE, numeric2factor = FALSE, numeric2factor_levels = NULL, numeric_cut_n = 0L, numeric_cut_labels = FALSE, numeric_quant_n = 0L, numeric_quant_NAonly = FALSE, unique_len2factor = 0L, character2factor = FALSE, factorNA2missing = FALSE, factorNA2missing_level = "missing", factor2integer = FALSE, factor2integer_startat0 = TRUE, factor2integer_levels = NULL, scale = FALSE, center = scale, scale_centers = NULL, scale_coefficients = NULL, remove_constants = FALSE, remove_constants_skip_missing = TRUE, remove_features = NULL, remove_duplicates = FALSE, one_hot = FALSE, one_hot_levels = NULL, add_date_features = FALSE, date_features = c("weekday", "month", "year"), add_holidays = FALSE, holidays = c("USLaborDay", "NewYearsDay", "ChristmasDay"), exclude = NULL )
complete_cases |
Logical: If TRUE, only retain complete cases (no missing data). Not available inside train: a fitted preprocessor is replayed at predict time, where dropping rows would return fewer predictions than rows. |
remove_features_thres |
Optional Numeric (0, 1]: Remove features with
missing values in >= to this fraction of cases. 1 removes only fully-missing
features. Not available inside train: each resample would learn its own set, so the folds would train on different features. Name the columns with |
remove_cases_thres |
Optional Numeric (0, 1]: Remove cases with >= to this fraction of missing features. 1 removes only fully-missing cases. Not available inside train: a fitted preprocessor is replayed at predict time, where dropping rows would return fewer predictions than rows. |
missingness |
Logical: If TRUE, generate new boolean columns for each feature with missing values, indicating which cases were missing data. |
impute |
Logical: If TRUE, impute missing cases. See |
impute_type |
Character {"missRanger", "micePMM", "meanMode"}:
Imputation method. "missRanger" fits one random forest per feature with
missing values, kept in the |
impute_missRanger_params |
List: Parameters passed to
|
impute_numeric |
Character {"mean", "median"}: Statistic imputed into
numeric and logical features for |
impute_categorical |
Character {"mode"}: Statistic imputed into factor
and character features for |
impute_numeric_values |
Optional Named vector: Value imputed into
numeric or logical features, keyed by feature name; a logical feature
takes 1 as TRUE and 0 as FALSE. Covers every such feature for
|
impute_level_values |
Optional Named vector: Value imputed into factor
or character features, keyed by feature name. Covers every such feature
for |
integer2factor |
Logical: If TRUE, convert all integers to factors. This includes
|
integer2numeric |
Logical: If TRUE, convert all integers to numeric
(will only work if |
logical2factor |
Logical: If TRUE, convert all logical variables to factors. |
logical2numeric |
Logical: If TRUE, convert all logical variables to numeric. |
numeric2factor |
Logical: If TRUE, convert all numeric variables to factors. |
numeric2factor_levels |
Optional Character vector: Will be passed to
|
numeric_cut_n |
Integer [0, Inf): If > 0, convert all numeric variables to factors by
binning using |
numeric_cut_labels |
Logical: The |
numeric_quant_n |
Integer [0, Inf): If > 0, convert all numeric
variables to factors by binning using |
numeric_quant_NAonly |
Logical: If TRUE, only bin numeric variables with missing values. |
unique_len2factor |
Integer [0, Inf): Convert all variables with less
than or equal to this number of unique values to factors. 0 and 1 both
disable it: a feature with one unique value is a constant, which
|
character2factor |
Logical: If TRUE, convert all character variables to factors. |
factorNA2missing |
Logical: If TRUE, make NA values in factors be of
level |
factorNA2missing_level |
Character: Name of level if
|
factor2integer |
Logical: If TRUE, convert all factors to integers. |
factor2integer_startat0 |
Logical: If TRUE, start integer coding at 0. |
factor2integer_levels |
Optional List: Named list of the form
"feature_name" = "levels". Used to code factors identically to the training
data when applying |
scale |
Logical: If TRUE, scale columns of |
center |
Logical: If TRUE, center columns of |
scale_centers |
Optional Named vector: Centering values for each feature. |
scale_coefficients |
Optional Named vector: Scaling values for each feature. |
remove_constants |
Logical: If TRUE, remove constant columns. |
remove_constants_skip_missing |
Logical: If TRUE, skip missing values, before checking if feature is constant. |
remove_features |
Optional Character vector: Features to remove. |
remove_duplicates |
Logical: If TRUE, remove duplicate cases. Not available inside train: a fitted preprocessor is replayed at predict time, where dropping rows would return fewer predictions than rows. |
one_hot |
Logical: If TRUE, convert all factors using one-hot encoding. |
one_hot_levels |
Optional List: Named list of the form "feature_name" = "levels". Used when applying
one-hot encoding to validation or test data using |
add_date_features |
Logical: If TRUE, extract date features from date columns. |
date_features |
Character {"weekday", "month", "year"} vector: Features to extract from dates. |
add_holidays |
Logical: If TRUE, extract holidays from date columns. |
holidays |
Character vector: Holidays to flag when |
exclude |
Optional Integer vector: Exclude these columns from preprocessing. |
PreprocessorConfig object.
"meanMode" stores one value per feature, computed on the data preprocess()
is given, and apply_preprocessor imputes new data with those values. Each
value has its feature's type: an integer feature receives an integer, a
logical feature a logical, and a factor one of its levels.
"missRanger" fits one random forest per feature with missing values and
keeps the forests, and a copy of the data predict() draws starting values
from, in the Preprocessor, which therefore grows with the data. The
forests are an R object: a config written to JSON carries the method and its
parameters, not the forests. A feature with no missing values in the data
has no forest and takes its impute_numeric or impute_categorical value
when it is missing in new data.
predict() stops on a factor level of an imputed feature that is absent
from the data the forests were fitted on.
"micePMM" imputes the data it is run on and fits no model for new data;
apply_preprocessor refuses a Preprocessor that uses it.
For preprocessing inside train, see the Imputation section of setup_SupervisedPreprocessor.
Steps run in this order, and the order is part of what each one does:
remove_constants runs before the quantile cut because a constant has no
quantiles, factorNA2missing before impute so that missing values in a
categorical feature become a level, and one_hot last
among the encoders so that it sees every factor the earlier steps created.
Feature creation precedes feature transformation: add_date_features and
add_holidays run ahead of the conversions, so the weekday, month and
holiday factors they derive are encoded and the year is scaled exactly as any
column of the input would be. They run after the case and feature filters,
which judge the data as it was given.
keep complete cases only
set aside excluded columns
remove named features
remove constants
remove duplicates
remove cases by missingness threshold
remove features by missingness threshold
add date features
add holidays
integer to factor
logical to factor
numeric to factor
character to factor
features with <= N unique values to factor
integer to numeric
logical to numeric
cut numeric to n bins
cut numeric to n quantiles
factor NA to named level
factor to integer
add missingness column
impute
scale and/or center
one-hot encoding
re-add excluded columns, after the preprocessed ones
EDG
preproc_config <- setup_Preprocessor(factorNA2missing = TRUE) preproc_configpreproc_config <- setup_Preprocessor(factorNA2missing = TRUE) preproc_config
Setup hyperparameters for RadialSVM training.
setup_RadialSVM(cost = 1, gamma = 0.01, ifw = FALSE)setup_RadialSVM(cost = 1, gamma = 0.01, ifw = FALSE)
cost |
(Tunable) Numeric (0, Inf): Cost of constraints violation. |
gamma |
(Tunable) Numeric (0, Inf): Kernel coefficient. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from e1071::svm.
RadialSVMHyperparameters object.
EDG
radial_svm_hyperparams <- setup_RadialSVM(cost = 10, gamma = 0.1, ifw = TRUE) radial_svm_hyperparamsradial_svm_hyperparams <- setup_RadialSVM(cost = 10, gamma = 0.1, ifw = TRUE) radial_svm_hyperparams
RandomPartitionConfig
A uniformly random split – the right default when nothing about row order or grouping is meaningful.
setup_RandomPartition(train_p = 0.75, seed = NULL)setup_RandomPartition(train_p = 0.75, seed = NULL)
train_p |
Numeric (0, 1): Training set fraction. |
seed |
Optional Integer [0, Inf): Random seed. |
RandomPartitionConfig object.
EDG
setup_RandomPartition(train_p = 0.8, seed = 2026L)setup_RandomPartition(train_p = 0.8, seed = 2026L)
Setup hyperparameters for Ranger Random Forest training.
setup_Ranger( num_trees = 500L, mtry = NULL, importance = "impurity", write_forest = TRUE, probability = FALSE, min_node_size = NULL, min_bucket = NULL, max_depth = NULL, replace = TRUE, sample_fraction = ifelse(replace, 1, 0.632), class_weights = NULL, splitrule = NULL, num_random_splits = 1L, alpha = 0.5, minprop = 0.1, poisson_tau = 1, split_select_weights = NULL, always_split_variables = NULL, respect_unordered_factors = NULL, scale_permutation_importance = FALSE, local_importance = FALSE, regularization_factor = 1, regularization_usedepth = FALSE, keep_inbag = FALSE, inbag = NULL, holdout = FALSE, quantreg = FALSE, time_interest = NULL, oob_error = TRUE, save_memory = FALSE, verbose = TRUE, node_stats = FALSE, seed = NULL, na_action = "na.learn", ifw = FALSE )setup_Ranger( num_trees = 500L, mtry = NULL, importance = "impurity", write_forest = TRUE, probability = FALSE, min_node_size = NULL, min_bucket = NULL, max_depth = NULL, replace = TRUE, sample_fraction = ifelse(replace, 1, 0.632), class_weights = NULL, splitrule = NULL, num_random_splits = 1L, alpha = 0.5, minprop = 0.1, poisson_tau = 1, split_select_weights = NULL, always_split_variables = NULL, respect_unordered_factors = NULL, scale_permutation_importance = FALSE, local_importance = FALSE, regularization_factor = 1, regularization_usedepth = FALSE, keep_inbag = FALSE, inbag = NULL, holdout = FALSE, quantreg = FALSE, time_interest = NULL, oob_error = TRUE, save_memory = FALSE, verbose = TRUE, node_stats = FALSE, seed = NULL, na_action = "na.learn", ifw = FALSE )
num_trees |
(Tunable) Integer [1, Inf): Number of trees. |
mtry |
(Tunable) Optional Integer [1, Inf): Number of features to consider at each split. |
importance |
Character {"none", "impurity", "impurity_corrected", "permutation"}: Variable importance mode. "impurity" is the Gini index for classification, the response variance for regression. |
write_forest |
Logical: If TRUE, save the forest object (required for prediction). Set to FALSE to reduce memory if no prediction is intended. |
probability |
Logical: If TRUE, grow a probability forest. Classification only. |
min_node_size |
(Tunable) Optional Integer [1, Inf): Minimal node size. If NULL, ranger uses 1 for classification, 5 for regression, 3 for survival, and 10 for probability. |
min_bucket |
Optional Integer [1, Inf): Fewest cases a terminal node may hold; no split creates a smaller node. Unset uses ranger's default of 1. |
max_depth |
(Tunable) Optional Integer [0, Inf): Maximal tree depth. NULL or 0 means unlimited depth, 1 means tree stumps. |
replace |
(Tunable) Logical: If TRUE, sample with replacement. |
sample_fraction |
(Tunable) Numeric (0, 1]: Fraction of observations to sample. Default is 1 with replacement and 0.632 without. |
class_weights |
Optional Numeric [0, Inf) vector: Per-class weights for classification. Length equal to the number of classes, named by class label. NULL weights every class equally. |
splitrule |
(Tunable) Optional Character: Splitting rule. Classification: "gini", "extratrees", "hellinger"; regression: "variance", "extratrees", "maxstat", "beta"; survival: "logrank", "extratrees", "C", "maxstat". |
num_random_splits |
(Tunable) Integer [1, Inf): Number of random splits per candidate variable, for the "extratrees" splitrule. |
alpha |
(Tunable) Numeric [0, 1]: Significance threshold to allow splitting, for the "maxstat" splitrule. |
minprop |
(Tunable) Numeric [0, 1]: Lower quantile of the covariate distribution considered for splitting, for the "maxstat" splitrule. |
poisson_tau |
Numeric (0, Inf): Tau parameter, for the "poisson" regression splitrule. |
split_select_weights |
Optional List: Per-feature probabilities of being selected for splitting, in [0, 1]. One vector applied to every tree, or a list of length |
always_split_variables |
Optional Character vector: Names of variables to always include as split candidates, in addition to the |
respect_unordered_factors |
Optional Character {"partition", "ignore", "order"}: Handling of unordered factors. "partition" considers all 2-partitions, "ignore" orders levels by first occurrence, "order" orders levels by mean response. |
scale_permutation_importance |
Logical: If TRUE, scale permutation importance by its standard error. Permutation importance only. |
local_importance |
Logical: If TRUE, compute local (per-observation) permutation importance. |
regularization_factor |
(Tunable) Numeric [0, Inf): Regularization factor penalizing variables with many split points. Requires |
regularization_usedepth |
Logical: If TRUE, apply the regularization factor with node depth. Requires |
keep_inbag |
Logical: If TRUE, record how often each observation is in-bag per tree. |
inbag |
Optional List: Manually set in-bag counts; a list of length |
holdout |
Logical: If TRUE, use hold-out mode: hold out samples with case weight 0 and use them for variable importance and prediction error. |
quantreg |
Logical: If TRUE, prepare quantile prediction (quantile regression forests). Regression only; set |
time_interest |
Optional Numeric vector: Time points of interest for survival prediction. Survival only. NULL uses the observed event times. |
oob_error |
Logical: If TRUE, compute the OOB prediction error. Set to FALSE to save time if only the forest is needed. |
save_memory |
Logical: If TRUE, use the memory-saving (slower) splitting mode. Use only if you encounter memory problems. |
verbose |
Logical: If TRUE, show computation status and estimated runtime. |
node_stats |
Logical: If TRUE, save additional node statistics (terminal nodes only). |
seed |
Optional Integer: Random seed. If NULL, the seed is generated from R. Set to 0 to ignore the R seed. |
na_action |
Character {"na.learn", "na.omit", "na.fail"}: How to handle missing values. "na.learn" uses observations with missing values in splitting, treating missing as a separate category. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Get more information from ranger::ranger.
RangerHyperparameters object.
EDG
ranger_hyperparams <- setup_Ranger(num_trees = 1000L, ifw = FALSE) ranger_hyperparamsranger_hyperparams <- setup_Ranger(num_trees = 1000L, ifw = FALSE) ranger_hyperparams
RDSIngestConfig
Reading an RDS file. R's own serialization carries its types, so the format has no settings of its own.
setup_RDSIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE )setup_RDSIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE )
columns |
Optional Named vector: Declared column types, keyed by column
name, in the |
character2factor |
Logical: If TRUE, read character columns as factors. |
clean_colnames |
Logical: If TRUE, normalize column names. |
remove_duplicates |
Logical: If TRUE, drop rows repeating an earlier row. |
RDSIngestConfig object.
EDG
setup_RDSIngest()setup_RDSIngest()
setup_Resampler() is deprecated. Use setup_KFold(), setup_StratSub(),
setup_StratBoot(), setup_Bootstrap(), setup_LOOCV(), or setup_Custom().
Only arguments relevant to the selected type are forwarded. Omitted arguments
retain the selected setup function's default resolution.
setup_Resampler( n_resamples = 10L, type = c("KFold", "StratSub", "StratBoot", "Bootstrap", "LOOCV", "Custom"), stratify_var = NULL, train_p = 0.75, strat_n_bins = 4L, target_length = NULL, id_strat = NULL, seed = NULL, verbosity = 1L, resamples = NULL )setup_Resampler( n_resamples = 10L, type = c("KFold", "StratSub", "StratBoot", "Bootstrap", "LOOCV", "Custom"), stratify_var = NULL, train_p = 0.75, strat_n_bins = 4L, target_length = NULL, id_strat = NULL, seed = NULL, verbosity = 1L, resamples = NULL )
n_resamples |
Integer [1, Inf): Number of resamples to make. |
type |
Character: Resampling method; matched without regard to case. |
stratify_var |
Optional Character: Variable to stratify by. |
train_p |
Numeric (0, 1): Training set percentage. |
strat_n_bins |
Integer [1, Inf): Number of bins to stratify by. |
target_length |
Optional Integer [1, Inf): Target length for stratified bootstraps. |
id_strat |
Optional Character: Name of the column holding per-case grouping IDs, e.g.
subject IDs when the dataset contains repeated measurements. Cases sharing an ID stay in the
same resample, so a case can only be present in the training or the test set, not both.
Requires that |
seed |
Optional Integer [0, Inf): Random seed. |
verbosity |
Integer: Console verbosity. The deprecation warning is always
signaled and can be handled with |
resamples |
Optional List: Resamples to use, one integer vector of training-case indices per resample. |
id_strat names a column in the input data; per-case ID vectors are not
accepted. Arguments that do not apply to the selected type are ignored.
A resampler configuration of the selected type.
config <- suppressWarnings(setup_Resampler(5L, "KFold", seed = 2026L)) configconfig <- suppressWarnings(setup_Resampler(5L, "KFold", seed = 2026L)) config
SerialExecutionConfig
Execution in the calling process: nothing is dispatched to a worker. Takes
no n_workers and no future_plan, neither of which a serial run can act
on.
setup_SerialExecution( n_workers_algorithm = NULL, device = NULL, on_error = c("continue", "stop", "stop_outer"), seed = NULL, shared_memory = c("auto", "none", "always") )setup_SerialExecution( n_workers_algorithm = NULL, device = NULL, on_error = c("continue", "stop", "stop_outer"), seed = NULL, shared_memory = c("auto", "none", "always") )
n_workers_algorithm |
Optional Integer [1, Inf): Threads for a self-parallelizing algorithm, overriding the automatic assignment. |
device |
Optional |
on_error |
Character {"continue", "stop", "stop_outer"}: Failure policy.
|
seed |
Optional Integer [0, Inf): Master seed for the run's computation RNG,
from which one independent substream per parallel task is derived. Left |
shared_memory |
Character {"none", "auto", "always"}: Whether to hand workers
the training data through OS shared memory instead of serializing a copy to each.
|
n_workers_algorithm still applies: it is threads within the calling
process, not worker processes, so a self-parallelizing algorithm runs
multi-threaded under a serial config.
See setup_FutureExecution for how the run's seed is resolved.
SerialExecutionConfig object.
EDG
setup_SerialExecution()setup_SerialExecution()
Configure per-case Shapley additive explanations for explain().
setup_SHAP( estimator = "auto", perturbation = NULL, scale = NULL, background_n = NULL, n_coalitions = NULL, approach = NULL, seed = NULL )setup_SHAP( estimator = "auto", perturbation = NULL, scale = NULL, background_n = NULL, n_coalitions = NULL, approach = NULL, seed = NULL )
estimator |
Character {"auto", "exact", "kernel"}: Which estimator to use. |
perturbation |
Optional Character {"interventional", "conditional"}: Value function. NULL uses the resolved estimator's documented default. |
scale |
Optional Character {"margin", "probability"}: Scale the contributions are additive on. NULL sets it from the outcome type. |
background_n |
Optional Integer [1, Inf): Cases to subsample from the background data. NULL uses all of it. |
n_coalitions |
Optional Integer [2, Inf): Most feature subsets the kernel estimator evaluates. NULL lets the backend decide. |
approach |
Optional Character {"empirical", "gaussian", "copula", "ctree", "vaeac", "categorical", "timeseries"}: Conditional-distribution estimator used by the kernel estimator. |
seed |
Optional Integer [0, Inf): Random seed. |
Three choices here define what is computed, and each is recorded on the returned explanation, so explanations computed differently are told apart.
perturbation is the question being asked. "interventional" breaks the
dependence between features, attributing to what the model uses: a feature
the model ignores gets zero even if it predicts the outcome perfectly.
"conditional" respects the joint distribution, attributing to what the
case's features tell you, so a correlated proxy for a used feature receives
credit. Neither is the correct one – debugging a model wants the first,
reasoning about a subject wants the second.
scale decides whether the contributions add up. They are additive on
the scale they are computed on. For regression that is the outcome and there
is nothing to choose. For classification the model's additive scale is the
margin, and probability is a nonlinear transform of it, so contributions on
the probability scale do not sum to the predicted probability.
estimator is normally best left alone. "auto" uses the exact
estimator wherever the algorithm has one and the model-agnostic kernel
estimator otherwise; explanation_methods() reports which applies where.
approach and n_coalitions apply only to the kernel estimator, and
approach only when perturbation is "conditional" – the interventional
answer is not one of several conditional estimators, it is the absence of
conditioning.
Setting either therefore requires estimator = "kernel" rather than
"auto", even for an algorithm "auto" would send to the kernel estimator
anyway. Tuning an estimator is a decision to use it, and the alternative –
accepting settings that a resolved exact estimator would then ignore –
would drop them silently.
SHAPConfig object.
EDG
setup_SHAP() setup_SHAP(perturbation = "conditional") setup_SHAP(estimator = "kernel", perturbation = "conditional", approach = "ctree")setup_SHAP() setup_SHAP(perturbation = "conditional") setup_SHAP(estimator = "kernel", perturbation = "conditional", approach = "ctree")
Setup a SpectralLaplaceConfig object for spectral clustering with an
exponential (Laplacian) kernel, via the 'kernlab' package. The exponential
kernel decays more slowly than the Gaussian of setup_SpectralRBF and so
keeps more weight on distant pairs.
setup_SpectralLaplace( k = 3L, sigma = NULL, iterations = 200L, nystrom = NULL, features = NULL )setup_SpectralLaplace( k = 3L, sigma = NULL, iterations = 200L, nystrom = NULL, features = NULL )
k |
Integer [2, Inf): Number of clusters. Must be no more than the number of cases. |
sigma |
Optional Numeric (0, Inf): Inverse kernel width. Unset uses 1. |
iterations |
Integer [1, Inf): Maximum number of k-means iterations run on the spectral embedding. |
nystrom |
Optional |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
Argument names are rtemis' own. They map to kernlab::specc() as: k ->
centers, sigma -> kpar = list(sigma) with kernel = "laplacedot",
nystrom -> nystrom.red and nystrom.sample; iterations keeps its
name.
SpectralLaplaceConfig object.
EDG
Ng AY, Jordan MI, Weiss Y (2001). On Spectral Clustering: Analysis and an Algorithm. Advances in Neural Information Processing Systems, 14, 849-856.
setup_SpectralLaplace(k = 3L, sigma = 0.5)setup_SpectralLaplace(k = 3L, sigma = 0.5)
Setup a SpectralLocalConfig object for spectral clustering with a locally
scaled Gaussian kernel, via the 'kernlab' package. Each case's kernel width
is taken from the distance to its seventh nearest neighbor, which lets one
clustering hold groups of differing density. The per-case widths need every
pairwise distance, so this variant has no Nystrom approximation.
setup_SpectralLocal(k = 3L, iterations = 200L, features = NULL)setup_SpectralLocal(k = 3L, iterations = 200L, features = NULL)
k |
Integer [2, Inf): Number of clusters. Must be no more than the number of cases. |
iterations |
Integer [1, Inf): Maximum number of k-means iterations run on the spectral embedding. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
Argument names are rtemis' own. They map to kernlab::specc() as: k ->
centers, with kpar = "local"; iterations keeps its name.
SpectralLocalConfig object.
EDG
Zelnik-Manor L, Perona P (2004). Self-Tuning Spectral Clustering. Advances in Neural Information Processing Systems, 17, 1601-1608.
setup_SpectralLocal(k = 3L)setup_SpectralLocal(k = 3L)
Setup a SpectralRBFConfig object for spectral clustering with a Gaussian
(radial basis function) kernel, via the 'kernlab' package.
setup_SpectralRBF( k = 3L, sigma = NULL, sigma_sample_fraction = NULL, iterations = 200L, nystrom = NULL, features = NULL )setup_SpectralRBF( k = 3L, sigma = NULL, sigma_sample_fraction = NULL, iterations = 200L, nystrom = NULL, features = NULL )
k |
Integer [2, Inf): Number of clusters. Must be no more than the number of cases. |
sigma |
Optional Numeric (0, Inf): Inverse kernel width. Unset estimates it from the data. |
sigma_sample_fraction |
Optional Numeric (0, 1]: Fraction of the cases the kernel width is estimated from when |
iterations |
Integer [1, Inf): Maximum number of k-means iterations run on the spectral embedding. |
nystrom |
Optional |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to cluster on. |
Spectral clustering builds a similarity graph over the cases, embeds them in the leading eigenvectors of that graph's normalized Laplacian, and runs k-means there. Groups that are connected but not compact – concentric rings, elongated bands – separate in that embedding while k-means on the raw features cannot find them. This variant measures similarity with a Gaussian kernel whose width is shared by every case; see setup_SpectralLocal for a per-case width and setup_SpectralLaplace for an exponential kernel.
The cost is cubic in the number of cases, since the whole affinity matrix
is decomposed. Pass nystrom to approximate the decomposition from a
sample instead.
Argument names are rtemis' own. They map to kernlab::specc() as: k ->
centers, sigma -> kpar = list(sigma) with kernel = "rbfdot",
sigma_sample_fraction -> mod.sample (with kpar = "automatic" when
sigma is unset), nystrom -> nystrom.red and nystrom.sample;
iterations keeps its name.
SpectralRBFConfig object.
EDG
Ng AY, Jordan MI, Weiss Y (2001). On Spectral Clustering: Analysis and an Algorithm. Advances in Neural Information Processing Systems, 14, 849-856.
spectral_config <- setup_SpectralRBF(k = 3L) spectral_config setup_SpectralRBF(k = 3L, nystrom = setup_Nystrom(sample = 100L))spectral_config <- setup_SpectralRBF(k = 3L) spectral_config setup_SpectralRBF(k = 3L, nystrom = setup_Nystrom(sample = 100L))
Configure split conformal prediction for conformal.
setup_SplitConformal(alpha = 0.1, score = NULL, seed = NULL)setup_SplitConformal(alpha = 0.1, score = NULL, seed = NULL)
alpha |
Numeric (0, 1): Miscoverage rate. The region covers with
probability at least |
score |
Optional Character {"absolute", "LAC", "APS"}: Nonconformity score. NULL resolves to "absolute" for a regression and "APS" for a classification. |
seed |
Optional Integer [0, Inf): Random seed for the APS draw. NULL draws one and records it. |
The reference construction: score every calibration case, take q to be the
score at rank ceiling((n + 1) * (1 - alpha)) from the bottom, and return
every outcome whose score would not exceed it. Coverage is at least
1 - alpha, and needs only that the calibration cases and the test case be
exchangeable.
alpha has a floor set by the calibration count. A finite region needs
ceiling((n + 1) * (1 - alpha)) <= n, so alpha = 0.05 needs at least 19
calibration cases and alpha = 0.01 at least 99. conformal() aborts naming
the count.
score is the real choice, and only for a classification. A regression
has one score, abs(y - yhat), which is what NULL resolves to.
"APS", the default, accumulates the predicted probabilities from the most
probable class down to the true one. Larger sets, markedly better coverage
on the hard cases – which is the reason to want a set at all.
"LAC" scores 1 - p(y). It produces the smallest sets attaining valid
marginal coverage, and it buys them by under-covering exactly the cases
where the model is unsure. Choose it when small sets are the point and the
trade is understood.
APS is randomized (Romano, Sesia and Candes, 2020): the true label's own
probability enters its score multiplied by a uniform draw, one per case. That
is not a refinement. Without it, every case whose true label ranks last
scores exactly 1, so a model erring on more than alpha of its cases puts
the threshold at 1 and every set holds every label – valid coverage carrying
no information. seed keeps the draw reproducible: left NULL, one is drawn
and recorded on the returned config, so an unseeded region can still be
reproduced from what it reports. "LAC" draws nothing and ignores it.
SplitConformalConfig object.
EDG
setup_SplitConformal() setup_SplitConformal(alpha = 0.05) setup_SplitConformal(score = "LAC")setup_SplitConformal() setup_SplitConformal(alpha = 0.05) setup_SplitConformal(score = "LAC")
Setup hyperparameters for Sparse Partial Least Squares training.
setup_SPLS( k = 2L, eta = 0.5, kappa = 0.5, select = "pls2", fit = "simpls", classifier = "lda", scale_x = TRUE, scale_y = FALSE, eps = 1e-04, maxstep = 100L, ifw = FALSE )setup_SPLS( k = 2L, eta = 0.5, kappa = 0.5, select = "pls2", fit = "simpls", classifier = "lda", scale_x = TRUE, scale_y = FALSE, eps = 1e-04, maxstep = 100L, ifw = FALSE )
k |
(Tunable) Integer [1, Inf): Number of latent components. |
eta |
(Tunable) Numeric [0, 1): Sparsity threshold. Higher values select fewer features. |
kappa |
(Tunable) Numeric [0, 0.5]: Concavity of the surrogate direction vector problem. |
select |
Character {"pls2", "simpls"}: Feature selection algorithm (regression only). |
fit |
Character {"kernelpls", "widekernelpls", "simpls", "oscorespls"}: PLS algorithm used for model fitting (regression only). |
classifier |
Character {"lda", "logistic"}: Classifier fit on the latent components (classification only). |
scale_x |
Logical: If TRUE, scale features to unit variance. |
scale_y |
Logical: If TRUE, scale the outcome to unit variance (regression only). |
eps |
Numeric (0, Inf): Convergence tolerance (regression only). |
maxstep |
Integer [1, Inf): Maximum number of iterations per component (regression only). |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Regression is fit with spls::spls and classification with spls::splsda, chosen from the outcome type. Parameters marked "regression only" or "classification only" are passed to the backend that accepts them and ignored by the other.
spls provides no case weights, so ifw cannot be honored: enabling it
makes training abort.
SPLSHyperparameters object.
EDG
spls_hyperparams <- setup_SPLS(k = 3L, eta = 0.7) spls_hyperparamsspls_hyperparams <- setup_SPLS(k = 3L, eta = 0.7) spls_hyperparams
Setup StratBoot Resampler
setup_StratBoot( n_resamples = 10L, stratify_var = NULL, train_p = 0.75, strat_n_bins = 4L, target_length = NULL, id_strat = NULL, seed = NULL )setup_StratBoot( n_resamples = 10L, stratify_var = NULL, train_p = 0.75, strat_n_bins = 4L, target_length = NULL, id_strat = NULL, seed = NULL )
n_resamples |
Integer [1, Inf): Number of resamples to make. |
stratify_var |
Optional Character: Variable to stratify by. |
train_p |
Numeric (0, 1): Training set percentage. |
strat_n_bins |
Integer [1, Inf): Number of bins to stratify by. |
target_length |
Optional Integer [1, Inf): Target length for stratified bootstraps. |
id_strat |
Optional Character: Name of the column holding per-case grouping IDs, e.g.
subject IDs when the dataset contains repeated measurements. Cases sharing an ID stay in the
same resample, so a case can only be present in the training or the test set, not both.
Requires that |
seed |
Optional Integer [0, Inf): Random seed. |
StratBootConfig object.
EDG
strat_boot_resampler <- setup_StratBoot(n_resamples = 10L, seed = 2026L) strat_boot_resamplerstrat_boot_resampler <- setup_StratBoot(n_resamples = 10L, seed = 2026L) strat_boot_resampler
Setup StratSub Resampler
setup_StratSub( n_resamples = 10L, train_p = 0.75, stratify_var = NULL, strat_n_bins = 4L, id_strat = NULL, seed = NULL )setup_StratSub( n_resamples = 10L, train_p = 0.75, stratify_var = NULL, strat_n_bins = 4L, id_strat = NULL, seed = NULL )
n_resamples |
Integer [1, Inf): Number of resamples to make. |
train_p |
Numeric (0, 1): Training set percentage. |
stratify_var |
Optional Character: Variable to stratify by. |
strat_n_bins |
Integer [1, Inf): Number of bins to stratify by. |
id_strat |
Optional Character: Name of the column holding per-case grouping IDs, e.g.
subject IDs when the dataset contains repeated measurements. Cases sharing an ID stay in the
same resample, so a case can only be present in the training or the test set, not both.
Requires that |
seed |
Optional Integer [0, Inf): Random seed. |
StratSubConfig object.
EDG
strat_sub_resampler <- setup_StratSub(n_resamples = 10L, seed = 2026L) strat_sub_resamplerstrat_sub_resampler <- setup_StratSub(n_resamples = 10L, seed = 2026L) strat_sub_resampler
Setup SuperConfig object. SuperConfig is a portable, data-agnostic recipe:
dat_training_path is optional, so the same config can be validated, shared,
or described without data and have a path bound later (e.g. by the rtemis
CLI) before train.
setup_SuperConfig( dat_training_path = NULL, dat_validation_path = NULL, dat_test_path = NULL, character2factor = TRUE, outcome = NULL, features = NULL, weights = NULL, positive_class = NULL, preprocessor_config = NULL, decomposition_config = NULL, hyperparameters = NULL, tuner_config = NULL, outer_resampling_config = NULL, execution_config = setup_FutureExecution(), question = NULL, outdir = "results/", verbosity = 1L )setup_SuperConfig( dat_training_path = NULL, dat_validation_path = NULL, dat_test_path = NULL, character2factor = TRUE, outcome = NULL, features = NULL, weights = NULL, positive_class = NULL, preprocessor_config = NULL, decomposition_config = NULL, hyperparameters = NULL, tuner_config = NULL, outer_resampling_config = NULL, execution_config = setup_FutureExecution(), question = NULL, outdir = "results/", verbosity = 1L )
dat_training_path |
Character or NULL: Path to training data file. NULL leaves the recipe unbound; set it (or supply data) before train. |
dat_validation_path |
Optional Character: Path to validation data file. |
dat_test_path |
Optional Character: Path to test data file. |
character2factor |
Logical: If TRUE, read character columns as factors. A delimited file carries no type information, so this is what decides whether a column of labels is a categorical predictor or an unusable string one. Applied to all three datasets. |
outcome |
Optional Character: Name of the outcome column; |
features |
Optional Character vector: Names of the predictor columns;
|
weights |
Optional Character: Column name in training data to use as observation weights. If NULL, no weights are used. |
positive_class |
Character or NULL: For binary classification, the outcome level to treat as positive. NULL keeps the existing factor level order. |
preprocessor_config |
Optional |
decomposition_config |
Optional |
hyperparameters |
Optional |
tuner_config |
Optional |
outer_resampling_config |
Optional |
execution_config |
|
question |
Optional Character: Question to answer with the supervised learning analysis. |
outdir |
Optional Character: Output directory for results; |
verbosity |
Integer [0, Inf): Verbosity level. |
SuperConfigPaths object.
EDG
## Not run: # requires local data file sc <- setup_SuperConfig( dat_training_path = "train.csv", preprocessor_config = setup_SupervisedPreprocessor(scale = TRUE), hyperparameters = setup_LightRF(), tuner_config = setup_GridSearch(), outer_resampling_config = setup_KFold(), execution_config = setup_FutureExecution(), question = "Can we tell iris species apart given their measurements?", outdir = "models/" ) ## End(Not run)## Not run: # requires local data file sc <- setup_SuperConfig( dat_training_path = "train.csv", preprocessor_config = setup_SupervisedPreprocessor(scale = TRUE), hyperparameters = setup_LightRF(), tuner_config = setup_GridSearch(), outer_resampling_config = setup_KFold(), execution_config = setup_FutureExecution(), question = "Can we tell iris species apart given their measurements?", outdir = "models/" ) ## End(Not run)
Build a SuperConfigTabular – same shape as setup_SuperConfig but with
in-memory tabular data instead of file paths.
setup_SuperConfigLive( dat_training, dat_validation = NULL, dat_test = NULL, outcome = NULL, features = NULL, weights = NULL, positive_class = NULL, preprocessor_config = NULL, decomposition_config = NULL, hyperparameters = NULL, tuner_config = NULL, outer_resampling_config = NULL, execution_config = setup_FutureExecution(), question = NULL, outdir = NULL, verbosity = 1L )setup_SuperConfigLive( dat_training, dat_validation = NULL, dat_test = NULL, outcome = NULL, features = NULL, weights = NULL, positive_class = NULL, preprocessor_config = NULL, decomposition_config = NULL, hyperparameters = NULL, tuner_config = NULL, outer_resampling_config = NULL, execution_config = setup_FutureExecution(), question = NULL, outdir = NULL, verbosity = 1L )
dat_training |
data.frame or data.table. Training data. |
dat_validation |
data.frame, data.table, or |
dat_test |
data.frame, data.table, or |
outcome |
Optional Character: Name of the outcome column; |
features |
Optional Character vector: Names of the predictor
columns; |
weights |
Optional Character: Column name in |
positive_class |
Optional Character: For binary classification, the
outcome level to treat as positive; forwarded to train which reorders
the outcome factor via set_positive_class. |
preprocessor_config, hyperparameters, tuner_config, outer_resampling_config, execution_config, question, verbosity
|
See setup_SuperConfig. |
decomposition_config |
Optional |
outdir |
Optional Character: Output directory; |
SuperConfigTabular object.
EDG
scl <- setup_SuperConfigLive( dat_training = iris, hyperparameters = setup_LightGBM(), outer_resampling_config = setup_KFold(), question = "Can we tell iris species apart given their measurements?" )scl <- setup_SuperConfigLive( dat_training = iris, hyperparameters = setup_LightGBM(), outer_resampling_config = setup_KFold(), question = "Can we tell iris species apart given their measurements?" )
Setup hyperparameters for a SuperLearner: the cross-validated stacked ensemble of van der Laan, Polley & Hubbard (2007).
setup_SuperLearner( base_learners = list(setup_GLM(), setup_GLMNET(), setup_Ranger()), meta_learner = setup_NNLS(), inner_resampling_config = setup_KFold(n_resamples = 10L), discrete = FALSE, expand_search_spaces = TRUE, ifw = FALSE )setup_SuperLearner( base_learners = list(setup_GLM(), setup_GLMNET(), setup_Ranger()), meta_learner = setup_NNLS(), inner_resampling_config = setup_KFold(n_resamples = 10L), discrete = FALSE, expand_search_spaces = TRUE, ifw = FALSE )
base_learners |
List of |
meta_learner |
|
inner_resampling_config |
|
discrete |
(Tunable) Logical: If TRUE, keep the single lowest-risk library entry rather than the weighted combination (the discrete SuperLearner). |
expand_search_spaces |
Logical: If TRUE, expand a base learner's search space into one library entry per combination. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
Each base learner is fitted on every training fold of inner_resampling_config
and predicts that fold's held-out cases, producing one cross-validated
prediction per case per learner. The meta learner is fitted on those
predictions against the outcome, and its coefficients are the ensemble
weights. Every base learner is then refitted on the whole training set, so a
prediction is the meta learner applied to the base learners' predictions.
Search spaces become library entries. A base learner holding more than one
value for a tunable hyperparameter is expanded into one library entry per
combination, and the ensemble weights choose between them – the ensemble's
own cross-validation is the model selection, so no inner tuning is needed.
Set expand_search_spaces = FALSE to tune each such learner by inner
resampling within every fold instead, which is far more expensive. A learner
that tunes itself (GLMNET choosing lambda by cv.glmnet) is unaffected
either way.
The cross-validated predictions and the resampler are kept on the fitted model, which is what a cross-fitting estimator needs from it.
Supports regression and binary classification.
SuperLearnerHyperparameters object.
EDG
superlearner_hyperparams <- setup_SuperLearner( base_learners = list(setup_GLM(), setup_CART()) ) superlearner_hyperparamssuperlearner_hyperparams <- setup_SuperLearner( base_learners = list(setup_GLM(), setup_CART()) ) superlearner_hyperparams
Creates a SupervisedPreprocessorConfig object: the preprocessing a train
run can fit, which is setup_Preprocessor without the four operations a
fitted preprocessor cannot carry.
setup_SupervisedPreprocessor( missingness = FALSE, impute = FALSE, impute_type = c("meanMode", "missRanger"), impute_missRanger_params = list(pmm.k = 3L, maxiter = 10L, num.trees = 500L), impute_numeric = c("mean", "median"), impute_categorical = "mode", impute_numeric_values = NULL, impute_level_values = NULL, integer2factor = FALSE, integer2numeric = FALSE, logical2factor = FALSE, logical2numeric = FALSE, numeric2factor = FALSE, numeric2factor_levels = NULL, numeric_cut_n = 0L, numeric_cut_labels = FALSE, numeric_quant_n = 0L, numeric_quant_NAonly = FALSE, unique_len2factor = 0L, character2factor = FALSE, factorNA2missing = FALSE, factorNA2missing_level = "missing", factor2integer = FALSE, factor2integer_startat0 = TRUE, factor2integer_levels = NULL, scale = FALSE, center = scale, scale_centers = NULL, scale_coefficients = NULL, remove_constants = FALSE, remove_constants_skip_missing = TRUE, remove_features = NULL, one_hot = FALSE, one_hot_levels = NULL, add_date_features = FALSE, date_features = c("weekday", "month", "year"), add_holidays = FALSE, holidays = c("USLaborDay", "NewYearsDay", "ChristmasDay"), exclude = NULL )setup_SupervisedPreprocessor( missingness = FALSE, impute = FALSE, impute_type = c("meanMode", "missRanger"), impute_missRanger_params = list(pmm.k = 3L, maxiter = 10L, num.trees = 500L), impute_numeric = c("mean", "median"), impute_categorical = "mode", impute_numeric_values = NULL, impute_level_values = NULL, integer2factor = FALSE, integer2numeric = FALSE, logical2factor = FALSE, logical2numeric = FALSE, numeric2factor = FALSE, numeric2factor_levels = NULL, numeric_cut_n = 0L, numeric_cut_labels = FALSE, numeric_quant_n = 0L, numeric_quant_NAonly = FALSE, unique_len2factor = 0L, character2factor = FALSE, factorNA2missing = FALSE, factorNA2missing_level = "missing", factor2integer = FALSE, factor2integer_startat0 = TRUE, factor2integer_levels = NULL, scale = FALSE, center = scale, scale_centers = NULL, scale_coefficients = NULL, remove_constants = FALSE, remove_constants_skip_missing = TRUE, remove_features = NULL, one_hot = FALSE, one_hot_levels = NULL, add_date_features = FALSE, date_features = c("weekday", "month", "year"), add_holidays = FALSE, holidays = c("USLaborDay", "NewYearsDay", "ChristmasDay"), exclude = NULL )
missingness |
Logical: If TRUE, generate new boolean columns for each feature with missing values, indicating which cases were missing data. |
impute |
Logical: If TRUE, impute missing cases. See |
impute_type |
Character {"meanMode", "missRanger"}: Imputation
method. "meanMode" imputes the values that |
impute_missRanger_params |
List: Parameters passed to
|
impute_numeric |
Character {"mean", "median"}: Statistic imputed into
numeric and logical features for |
impute_categorical |
Character {"mode"}: Statistic imputed into factor
and character features for |
impute_numeric_values |
Optional Named vector: Value imputed into
numeric or logical features, keyed by feature name; a logical feature
takes 1 as TRUE and 0 as FALSE. Covers every such feature for
|
impute_level_values |
Optional Named vector: Value imputed into factor
or character features, keyed by feature name. Covers every such feature
for |
integer2factor |
Logical: If TRUE, convert all integers to factors. This includes
|
integer2numeric |
Logical: If TRUE, convert all integers to numeric
(will only work if |
logical2factor |
Logical: If TRUE, convert all logical variables to factors. |
logical2numeric |
Logical: If TRUE, convert all logical variables to numeric. |
numeric2factor |
Logical: If TRUE, convert all numeric variables to factors. |
numeric2factor_levels |
Optional Character vector: Will be passed to
|
numeric_cut_n |
Integer [0, Inf): If > 0, convert all numeric variables to factors by
binning using |
numeric_cut_labels |
Logical: The |
numeric_quant_n |
Integer [0, Inf): If > 0, convert all numeric
variables to factors by binning using |
numeric_quant_NAonly |
Logical: If TRUE, only bin numeric variables with missing values. |
unique_len2factor |
Integer [0, Inf): Convert all variables with less
than or equal to this number of unique values to factors. 0 and 1 both
disable it: a feature with one unique value is a constant, which
|
character2factor |
Logical: If TRUE, convert all character variables to factors. |
factorNA2missing |
Logical: If TRUE, make NA values in factors be of
level |
factorNA2missing_level |
Character: Name of level if
|
factor2integer |
Logical: If TRUE, convert all factors to integers. |
factor2integer_startat0 |
Logical: If TRUE, start integer coding at 0. |
factor2integer_levels |
Optional List: Named list of the form
"feature_name" = "levels". Used to code factors identically to the training
data when applying |
scale |
Logical: If TRUE, scale columns of |
center |
Logical: If TRUE, center columns of |
scale_centers |
Optional Named vector: Centering values for each feature. |
scale_coefficients |
Optional Named vector: Scaling values for each feature. |
remove_constants |
Logical: If TRUE, remove constant columns. |
remove_constants_skip_missing |
Logical: If TRUE, skip missing values, before checking if feature is constant. |
remove_features |
Optional Character vector: Features to remove. |
one_hot |
Logical: If TRUE, convert all factors using one-hot encoding. |
one_hot_levels |
Optional List: Named list of the form "feature_name" = "levels". Used when applying
one-hot encoding to validation or test data using |
add_date_features |
Logical: If TRUE, extract date features from date columns. |
date_features |
Character {"weekday", "month", "year"} vector: Features to extract from dates. |
add_holidays |
Logical: If TRUE, extract holidays from date columns. |
holidays |
Character vector: Holidays to flag when |
exclude |
Optional Integer vector: Exclude these columns from preprocessing. |
complete_cases, remove_duplicates and remove_cases_thres drop cases. A
preprocessor fitted by train is replayed on validation, test and whatever
stats::predict() is handed, and a prediction call has nothing it may drop:
asked for n rows it must return n predictions.
remove_features_thres decides which columns to drop from the data in front
of it. Under resampling each fold would learn that set from its own training
subset, so the folds would train over different feature spaces and their
metrics would not average into an estimate of one model. Name the columns
with remove_features instead, which drops the same ones in every fold.
impute_type = "micePMM" imputes only the data 'mice' is run on, so a
fitted preprocessor cannot apply it to validation, test or new data.
The default impute_type is "meanMode"; see the Imputation section.
All four operations and micePMM imputation are available in setup_Preprocessor, for preprocess on a dataset in hand, where the outcome is still attached and what was dropped is visible.
SupervisedPreprocessorConfig object.
The preferred way to handle missing values is an algorithm that accepts
them, which needs no imputation: the tree-based CART, LightCART, LightGBM,
LightRF, LightRuleFit and Ranger. For an algorithm that requires complete
data, such as GLM or GLMNET, use impute_type = "meanMode", the default: it
stores one value per feature, computed on the training data, and adds
little memory or computation.
impute_type = "missRanger" fits one random forest per feature with missing
values. train fits the preprocessor on every training set it uses: once
per outer resample, and, when hyperparameters are tuned, once per tuning
resample and hyperparameter combination as well. For example, 10 outer
resamples with 5-fold tuning over 20 combinations fit missRanger
10 x (5 x 20 + 1) = 1010 times. Each fitted model, one per outer resample,
keeps its forests and a copy of its training data, which predict() draws
starting values from. Choose it only where a multivariate imputation is
needed, and reduce num.trees and maxiter in impute_missRanger_params
for large data.
A fitted missRanger imputer has three further properties:
It is an R object, held by the fitted model. A config or record written to JSON carries the method and its parameters, not the forests, so a model rebuilt from JSON cannot impute new data with them.
It has a forest only for features with missing values in the training
data. Other features take their impute_numeric or impute_categorical
value, computed on the training data, when they are missing in new data.
predict() stops on a factor level of an imputed feature that is absent
from the training data.
impute_type = "micePMM" imputes only the data 'mice' is run on and is
available in setup_Preprocessor only.
EDG
preproc_config <- setup_SupervisedPreprocessor(impute = TRUE) preproc_configpreproc_config <- setup_SupervisedPreprocessor(impute = TRUE) preproc_config
Setup hyperparameters for TabNet training.
setup_TabNet( batch_size = 500L, penalty = 0.001, clip_value = NULL, loss = "auto", epochs = 50L, drop_last = FALSE, decision_width = NULL, attention_width = NULL, num_steps = 3L, feature_reusage = 1.3, mask_type = "sparsemax", virtual_batch_size = 65536L, valid_split = 0, learn_rate = 0.02, optimizer = "adam", lr_scheduler = NULL, lr_decay = 0.1, step_size = 30L, checkpoint_epochs = 10L, cat_emb_dim = 1L, num_independent = 2L, num_shared = 2L, num_independent_decoder = 1L, num_shared_decoder = 1L, momentum = 0.02, pretraining_ratio = 0.5, device = NULL, importance_sample_size = NULL, early_stopping_monitor = "auto", early_stopping_tolerance = 0, early_stopping_patience = 0L, num_workers = 0L, skip_importance = FALSE, ifw = FALSE )setup_TabNet( batch_size = 500L, penalty = 0.001, clip_value = NULL, loss = "auto", epochs = 50L, drop_last = FALSE, decision_width = NULL, attention_width = NULL, num_steps = 3L, feature_reusage = 1.3, mask_type = "sparsemax", virtual_batch_size = 65536L, valid_split = 0, learn_rate = 0.02, optimizer = "adam", lr_scheduler = NULL, lr_decay = 0.1, step_size = 30L, checkpoint_epochs = 10L, cat_emb_dim = 1L, num_independent = 2L, num_shared = 2L, num_independent_decoder = 1L, num_shared_decoder = 1L, momentum = 0.02, pretraining_ratio = 0.5, device = NULL, importance_sample_size = NULL, early_stopping_monitor = "auto", early_stopping_tolerance = 0, early_stopping_patience = 0L, num_workers = 0L, skip_importance = FALSE, ifw = FALSE )
batch_size |
(Tunable) Integer [1, Inf): Batch size. |
penalty |
(Tunable) Numeric [0, Inf): Regularization penalty. |
clip_value |
(Tunable) Optional Numeric: Gradient clip value. NULL clips no gradients. |
loss |
(Tunable) Character: Loss function. |
epochs |
(Tunable) Integer [1, Inf): Number of epochs. |
drop_last |
(Tunable) Logical: If TRUE, drop last batch. |
decision_width |
(Tunable) Optional Integer [1, Inf): Decision prediction layer width. NULL uses |
attention_width |
(Tunable) Optional Integer [1, Inf): Attention embedding width. NULL uses |
num_steps |
(Tunable) Integer [1, Inf): Number of steps. |
feature_reusage |
(Tunable) Numeric [0, Inf): Feature reusage. |
mask_type |
(Tunable) Character {"sparsemax", "entmax"}: Mask type. |
virtual_batch_size |
(Tunable) Integer [1, Inf): Virtual batch size. |
valid_split |
(Tunable) Numeric [0, 1): Validation split. |
learn_rate |
(Tunable) Numeric (0, Inf): Learning rate. |
optimizer |
Character: Optimizer name, resolved by the tabnet backend. |
lr_scheduler |
Optional Character {"step", "reduce_on_plateau"}: Learning-rate scheduler. |
lr_decay |
(Tunable) Numeric [0, 1]: Learning rate decay. |
step_size |
(Tunable) Integer [1, Inf): Step size. |
checkpoint_epochs |
(Tunable) Integer [1, Inf): Checkpoint epochs. |
cat_emb_dim |
(Tunable) Integer [1, Inf): Categorical embedding dimension. |
num_independent |
(Tunable) Integer [1, Inf): Number of independent Gated Linear Units (GLU) at each step of the encoder. |
num_shared |
(Tunable) Integer [1, Inf): Number of shared Gated Linear Units (GLU) at each step of the encoder. |
num_independent_decoder |
(Tunable) Integer [1, Inf): Number of independent GLU layers for pretraining. |
num_shared_decoder |
(Tunable) Integer [1, Inf): Number of shared GLU layers for pretraining. |
momentum |
(Tunable) Numeric [0, Inf): Momentum. |
pretraining_ratio |
(Tunable) Numeric [0, 1]: Pretraining ratio. |
device |
Optional Character: Deprecated and ignored. Set the compute device in the
|
importance_sample_size |
(Tunable) Optional Integer [1, Inf): Cases drawn, with replacement, from the training cases left after the validation split to compute feature importance. Unset draws as many as there are such cases, at most 100,000. Applies only when |
early_stopping_monitor |
(Tunable) Character {"auto", "valid_loss", "train_loss"}: Early stopping monitor. |
early_stopping_tolerance |
(Tunable) Numeric [0, Inf): Minimum relative improvement to reset the patience counter. |
early_stopping_patience |
(Tunable) Integer [0, Inf): Number of epochs without improving before stopping. |
num_workers |
Integer [0, Inf): Number of subprocesses for data loading. |
skip_importance |
Logical: If TRUE, skip importance calculation. |
ifw |
(Tunable) Logical: If TRUE, use Inverse Frequency Weighting in classification. |
TabNetHyperparameters object.
EDG
tabnet_hyperparams <- setup_TabNet(epochs = 100L, learn_rate = 0.01) tabnet_hyperparamstabnet_hyperparams <- setup_TabNet(epochs = 100L, learn_rate = 0.01) tabnet_hyperparams
TimePartitionConfig
A split by time order: the earliest-ordered cases train, the latest-ordered are held out.
setup_TimePartition(column = NULL, train_p = 0.75)setup_TimePartition(column = NULL, train_p = 0.75)
column |
Optional Character: Name of the column to order cases by before splitting. |
train_p |
Numeric (0, 1): Fraction of the earliest-ordered cases assigned to training. |
TimePartitionConfig object.
EDG
setup_TimePartition(column = "visit_date", train_p = 0.8)setup_TimePartition(column = "visit_date", train_p = 0.8)
Setup tSNE config.
setup_tSNE( k = 2L, initial_dims = 50L, perplexity = 30, theta = 0.5, check_duplicates = TRUE, pca = TRUE, partial_pca = FALSE, max_iter = 1000L, verbose = getOption("verbose", FALSE), is_distance = FALSE, Y_init = NULL, pca_center = TRUE, pca_scale = FALSE, normalize = TRUE, stop_lying_iter = if (is.null(Y_init)) 250L else 0L, mom_switch_iter = if (is.null(Y_init)) 250L else 0L, momentum = 0.5, final_momentum = 0.8, eta = 200, exaggeration_factor = 12, num_threads = NULL, features = NULL )setup_tSNE( k = 2L, initial_dims = 50L, perplexity = 30, theta = 0.5, check_duplicates = TRUE, pca = TRUE, partial_pca = FALSE, max_iter = 1000L, verbose = getOption("verbose", FALSE), is_distance = FALSE, Y_init = NULL, pca_center = TRUE, pca_scale = FALSE, normalize = TRUE, stop_lying_iter = if (is.null(Y_init)) 250L else 0L, mom_switch_iter = if (is.null(Y_init)) 250L else 0L, momentum = 0.5, final_momentum = 0.8, eta = 200, exaggeration_factor = 12, num_threads = NULL, features = NULL )
k |
Integer [1, Inf): Number of components. |
initial_dims |
Integer [1, Inf): Initial dimensions. |
perplexity |
Numeric [0, Inf): Perplexity. |
theta |
Numeric [0, 1]: Speed/accuracy trade-off. |
check_duplicates |
Logical: If TRUE, check for duplicates. |
pca |
Logical: If TRUE, perform PCA. |
partial_pca |
Logical: If TRUE, perform partial PCA. |
max_iter |
Integer [1, Inf): Maximum number of iterations. |
verbose |
Logical: If TRUE, print messages. |
is_distance |
Logical: If TRUE, |
Y_init |
Optional Matrix: Initial Y matrix. |
pca_center |
Logical: If TRUE, center PCA. |
pca_scale |
Logical: If TRUE, scale PCA. |
normalize |
Logical: If TRUE, normalize. |
stop_lying_iter |
Integer [0, Inf): Stop lying iterations. |
mom_switch_iter |
Integer [0, Inf): Momentum switch iterations. |
momentum |
Numeric: Momentum. |
final_momentum |
Numeric: Final momentum. |
eta |
Numeric: Eta. |
exaggeration_factor |
Numeric: Exaggeration factor. |
num_threads |
Optional Integer: Deprecated and ignored. Threads come
from the execution config: set |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
Get more information on the config by running ?Rtsne::Rtsne.
tSNEConfig object.
EDG
tSNE_config <- setup_tSNE(k = 3L) tSNE_configtSNE_config <- setup_tSNE(k = 3L) tSNE_config
Setup UMAP config.
setup_UMAP( k = 2L, n_neighbors = 15L, init = "spectral", metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = TRUE, features = NULL )setup_UMAP( k = 2L, n_neighbors = 15L, init = "spectral", metric = "euclidean", n_epochs = NULL, learning_rate = 1, scale = TRUE, features = NULL )
k |
Integer [1, Inf): Number of components. |
n_neighbors |
Integer [1, Inf): Number of neighbors. |
init |
Character: Initialization type. See |
metric |
Character {"euclidean", "cosine", "manhattan", "hamming", "categorical"}: Distance metric. |
n_epochs |
Optional Integer [1, Inf): Number of epochs. |
learning_rate |
Numeric [0, Inf): Learning rate. |
scale |
Logical: If TRUE, scale input data before doing UMAP. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
A high n_neighbors value may give error in some systems:
"Error in irlba::irlba(L, nv = n, nu = 0, maxit = iters) :
function 'as_cholmod_sparse' not provided by package 'Matrix'"
UMAPConfig object.
EDG
umap_config <- setup_UMAP(k = 3L) umap_configumap_config <- setup_UMAP(k = 3L) umap_config
A fully connected variational autoencoder built and trained with torch:
the encoder maps each case to a normal distribution over k latent
dimensions, and the decoder maps a draw from it back to the features.
setup_VariationalAutoencoder( k = 2L, hidden_units = NULL, activation = "relu", norm = NULL, dropout = 0, input_dropout = 0, weight_decay = 0, input_noise = 0, loss = "mse", optimizer = "adamw", lr = 0.001, beta1 = NULL, beta2 = NULL, eps = NULL, momentum = NULL, lr_scheduler = NULL, batch_size = NULL, max_epochs = 100L, patience = 10L, max_grad_norm = NULL, validation_fraction = 0.1, beta = 1, features = NULL )setup_VariationalAutoencoder( k = 2L, hidden_units = NULL, activation = "relu", norm = NULL, dropout = 0, input_dropout = 0, weight_decay = 0, input_noise = 0, loss = "mse", optimizer = "adamw", lr = 0.001, beta1 = NULL, beta2 = NULL, eps = NULL, momentum = NULL, lr_scheduler = NULL, batch_size = NULL, max_epochs = 100L, patience = 10L, max_grad_norm = NULL, validation_fraction = 0.1, beta = 1, features = NULL )
k |
Integer [1, Inf): Number of components, the width of the latent layer. |
|
Optional Integer [1, Inf) vector: Units in each hidden layer of the encoder, input side first. |
|
activation |
Character {"relu", "gelu", "silu", "elu", "selu", "leaky_relu", "tanh"}: Activation applied after every hidden layer. |
norm |
Optional Character {"batch_norm", "layer_norm"}: Normalization applied in every hidden layer. NULL applies none. |
dropout |
Numeric [0, 1): Dropout probability applied after every hidden layer. |
input_dropout |
Numeric [0, 1): Probability of zeroing each standardized input during training. |
weight_decay |
Numeric [0, Inf): L2 penalty, decoupled from the gradient under the adamw optimizer. |
input_noise |
Numeric [0, Inf): Standard deviation of the Gaussian noise added to the standardized inputs during training. |
loss |
Character {"mse", "l1", "smooth_l1"}: Reconstruction loss. |
optimizer |
Character {"adamw", "adam", "sgd", "rmsprop"}: Optimization algorithm. |
lr |
Numeric (0, Inf): Learning rate. |
beta1 |
Optional Numeric [0, 1): Exponential decay rate of the first moment estimate. Applies to the adam and adamw optimizers. |
beta2 |
Optional Numeric [0, 1): Exponential decay rate of the second moment estimate. Applies to the adam and adamw optimizers. |
eps |
Optional Numeric (0, Inf): Term added to the denominator for numerical stability. Applies to the adam, adamw and rmsprop optimizers. |
momentum |
Optional Numeric [0, Inf): Momentum factor. Applies to the sgd and rmsprop optimizers. |
lr_scheduler |
Optional Character {"step", "cosine_annealing", "one_cycle", "reduce_on_plateau"}: Learning-rate schedule. NULL holds the learning rate fixed. |
batch_size |
Optional Integer [1, Inf): Cases per optimization step. |
max_epochs |
Integer [1, Inf): Largest number of passes over the training cases. |
patience |
Integer [1, Inf): Epochs without improvement of the held-out loss before stopping early. |
max_grad_norm |
Optional Numeric (0, Inf): Clip the gradient norm to this value before each step. NULL does not clip. |
validation_fraction |
Numeric [0, 1): Fraction of the cases held out for early stopping. |
beta |
Numeric [0, Inf): Weight of the KL divergence from the prior. |
features |
Optional Character vector: Names of at least 2 distinct
feature columns to decompose. |
Objective. For each case, the reconstruction loss summed over features
plus beta times the KL divergence of the case's latent distribution from
the standard normal, summed over the k dimensions; the mean over cases is
minimized. beta = 1 is the standard variational autoencoder (with
loss = "mse", up to constants, the negative evidence lower bound of a
unit-variance Gaussian decoder); beta > 1 is a beta-VAE, trading
reconstruction for components closer to independent; beta = 0 drops the
prior and leaves a noisy autoencoder.
Components are the means of the latent distributions, so decomp, apply_decomp and reconstruct are deterministic: sampling happens only in training. reconstruct decodes the means.
Architecture, input standardization, denoising, early stopping, and the execution config's seed, threads and device work as in setup_Autoencoder. The loss reported during training and for early stopping is the full objective, so it is not on the scale of setup_Autoencoder's, which averages the reconstruction loss over features.
VariationalAutoencoderConfig object.
EDG
vae_config <- setup_VariationalAutoencoder(k = 2L, beta = 4) vae_configvae_config <- setup_VariationalAutoencoder(k = 2L, beta = 4) vae_config
XLSXIngestConfig
Reading a spreadsheet. A workbook holds several tables, so which one is the only thing that must be said.
setup_XLSXIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE, sheet = 1L, na_strings = "" )setup_XLSXIngest( columns = NULL, character2factor = TRUE, clean_colnames = TRUE, remove_duplicates = FALSE, sheet = 1L, na_strings = "" )
columns |
Optional Named vector: Declared column types, keyed by column
name, in the |
character2factor |
Logical: If TRUE, read character columns as factors. |
clean_colnames |
Logical: If TRUE, normalize column names. |
remove_duplicates |
Logical: If TRUE, drop rows repeating an earlier row. |
sheet |
Integer [1, Inf): Sheet number to read. |
na_strings |
Character vector: Strings to read as missing. |
XLSXIngestConfig object.
EDG
setup_XLSXIngest(sheet = 2L)setup_XLSXIngest(sheet = 2L)
What a per-feature contribution hides once it is averaged across cases: that one level of a diagnosis drives the prediction and the others do nothing.
shap_by_level(x, newdata, features = NULL)shap_by_level(x, newdata, features = NULL)
x |
|
newdata |
tabular data: The cases |
features |
Optional Character: Features to summarize. NULL takes every
categorical feature in |
This is the right tool for "which level matters", and per-level contributions are not. A case has exactly one level, so its per-feature contribution is the contribution of the level it has – there is nothing to split. What averaging loses is only that cases at different levels were averaged together, and grouping them is what restores it.
Splitting a contribution across the columns of an encoding answers a different and worse question. Those values include a term for every level the case does not have; they depend on the encoding, since a contrast-coded factor's reference level has no column at all and so cannot appear; and for a linear model they are identical for every case at the same level. Grouping has none of those problems and shows the reference level like any other.
newdata must be the data the explanation was computed on, which is checked
against its fingerprint: contributions lined up against other rows would
produce a plausible but meaningless table.
data.table with columns class, feature, level, n, mean,
sd, and mean_abs.
EDG
x <- data.frame( age = rnorm(100), dx = factor(sample(c("none", "diabetes"), 100, TRUE)) ) x[["y"]] <- x[["age"]] + 3 * (x[["dx"]] == "diabetes") + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) contributions <- explain( mod, x[, c("age", "dx")], background = x[, c("age", "dx")], verbosity = 0L ) shap_by_level(contributions, x[, c("age", "dx")])x <- data.frame( age = rnorm(100), dx = factor(sample(c("none", "diabetes"), 100, TRUE)) ) x[["y"]] <- x[["age"]] + 3 * (x[["dx"]] == "diabetes") + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) contributions <- explain( mod, x[, c("age", "dx")], background = x[, c("age", "dx")], verbosity = 0L ) shap_by_level(contributions, x[, c("age", "dx")])
The three things a per-case explanation is: where the prediction would have started, what each feature did to it, and where it ended.
shap_case(x, newdata, case = 1L, class = NULL)shap_case(x, newdata, case = 1L, class = NULL)
x |
|
newdata |
tabular data: The cases |
case |
Integer or Character: Which case, by position or row name. |
class |
Optional Character: Which class's contributions. NULL takes the first, which is the only one for a regression or binary outcome. |
Shaped here, following session_timeline(): the
table is the shared input for rtemis.draw's chart and for rtemislive, so both
show the same thing, and it is useful on its own without either.
Features are ordered by the magnitude of their contribution, which is the order a waterfall reads in, and each carries the value it took for this case so the row reads "age = 62, +0.4".
List with steps (a data.table of feature, value and
contribution), baseline, predicted, case and class.
EDG
x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) contributions <- explain( mod, x[, c("age", "bmi")], background = x[, c("age", "bmi")], verbosity = 0L ) shap_case(contributions, x[, c("age", "bmi")], case = 1L)x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) contributions <- explain( mod, x[, c("age", "bmi")], background = x[, c("age", "bmi")], verbosity = 0L ) shap_case(contributions, x[, c("age", "bmi")], case = 1L)
The long form a beeswarm reads: a point per case per feature, positioned by its contribution and colored by the value the feature took.
shap_long(x, newdata, class = NULL)shap_long(x, newdata, class = NULL)
x |
|
newdata |
tabular data: The cases |
class |
Optional Character: Which class's contributions. NULL takes the first. |
Shaped here, for the reason shap_case() gives.
data.table with columns case, feature, value, numeric_value
and contribution. numeric_value is NA for a feature that is not numeric,
which is what a color scale needs to skip it.
EDG
x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) contributions <- explain( mod, x[, c("age", "bmi")], background = x[, c("age", "bmi")], verbosity = 0L ) head(shap_long(contributions, x[, c("age", "bmi")]))x <- data.frame(age = rnorm(100), bmi = rnorm(100)) x[["y"]] <- x[["age"]] * 2 + rnorm(100, sd = 0.3) mod <- train(x, hyperparameters = setup_GLM(), verbosity = 0L) contributions <- explain( mod, x[, c("age", "bmi")], background = x[, c("age", "bmi")], verbosity = 0L ) head(shap_long(contributions, x[, c("age", "bmi")]))
Show rtemis color key
show_color_key()show_color_key()
Used for side-effects: prints color key to console. Returns invisible NULL.
EDG
show_color_key()show_color_key()
Returns the size of an object
size(x, verbosity = 1L)size(x, verbosity = 1L)
x |
any object with |
verbosity |
Integer: Verbosity level. If > 0, print size to console |
If dim(x) is NULL, returns length(x).
Integer vector with length equal to the number of dimensions of x, invisibly.
EDG
x <- rnorm(20) size(x) # 20 x <- matrix(rnorm(100), 20, 5) size(x) # 20 5x <- rnorm(20) size(x) # 20 x <- matrix(rnorm(100), 20, 5) size(x) # 20 5
Tabulate column attributes
table_column_attr(x, attr = "source", useNA = "always")table_column_attr(x, attr = "source", useNA = "always")
x |
tabular data: Input data set. |
attr |
Character: Attribute to get |
useNA |
Character: Passed to |
table.
EDG
library(data.table) x <- data.table( id = 1:5, sbp = rnorm(5, 120, 15), dbp = rnorm(5, 80, 10), paO2 = rnorm(5, 90, 10), paCO2 = rnorm(5, 40, 5) ) setattr(x[["sbp"]], "source", "outpatient") setattr(x[["dbp"]], "source", "outpatient") setattr(x[["paO2"]], "source", "icu") setattr(x[["paCO2"]], "source", "icu") table_column_attr(x, "source")library(data.table) x <- data.table( id = 1:5, sbp = rnorm(5, 120, 15), dbp = rnorm(5, 80, 10), paO2 = rnorm(5, 90, 10), paCO2 = rnorm(5, 40, 5) ) setattr(x[["sbp"]], "source", "outpatient") setattr(x[["dbp"]], "source", "outpatient") setattr(x[["paO2"]], "source", "icu") setattr(x[["paCO2"]], "source", "icu") table_column_attr(x, "source")
Preprocess, tune, train, and test supervised learning models using nested resampling in a single call.
train( x, dat_validation = NULL, dat_test = NULL, weights = NULL, preprocessor_config = NULL, decomposition_config = NULL, hyperparameters = NULL, tuner_config = NULL, outer_resampling_config = NULL, execution_config = setup_FutureExecution(), question = NULL, outdir = NULL, preflight = FALSE, verbosity = 1L, ... )train( x, dat_validation = NULL, dat_test = NULL, weights = NULL, preprocessor_config = NULL, decomposition_config = NULL, hyperparameters = NULL, tuner_config = NULL, outer_resampling_config = NULL, execution_config = setup_FutureExecution(), question = NULL, outdir = NULL, preflight = FALSE, verbosity = 1L, ... )
x |
Tabular data, i.e. data.frame, data.table, or tbl_df (tibble): Training set data. |
dat_validation |
Tabular data: Validation set data. |
dat_test |
Tabular data: Test set data. |
weights |
Optional vector of case weights. |
preprocessor_config |
Optional SupervisedPreprocessorConfig object: Setup using setup_SupervisedPreprocessor. |
decomposition_config |
Optional DecompositionConfig object: Setup using a decomposition
|
hyperparameters |
|
tuner_config |
TunerConfig object: Setup using setup_GridSearch. |
outer_resampling_config |
Optional ResamplerConfig object: Setup using
one of the |
execution_config |
|
question |
Optional character string defining the question that the model is trying to answer. |
outdir |
Character, optional: String defining the output directory. The
fitted model is saved there as |
preflight |
Logical: If TRUE, check the configuration against |
verbosity |
Integer: Verbosity level. |
... |
Not used. |
Online book & documentation
See docs.rtemis.org/r for detailed documentation.
Preprocessing
There are many different stages at which preprocessing could be applied, when running a
supervised learning pipeline with nested resampling. Some operations are best done before
passing data to train():
Duplicate rows should be removed before resampling, so that duplicates don't end up in different resamples, e.g. one in training and one in test.
Constant columns should be removed before resampling. A column may appear constant in a small resample, even if it is not constant in the full dataset. Removing it inconsistently will throw an error during prediction.
All data-dependent preprocessing steps need to be performed on training data only and applied on validation and test data, e.g. scaling, centering, imputation.
User-defined preprocessing through preprocessor_config is applied on training set data,
the learned parameters are stored in the returned Supervised or SupervisedRes object, and the
preprocessing is applied on validation and test data.
For missing values, prefer an algorithm that accepts them, such as LightGBM, LightRF, Ranger
or CART. For an algorithm that requires complete data, impute with
setup_SupervisedPreprocessor(impute = TRUE), which uses mean and mode imputation by
default. missRanger imputation is fitted on every training set, including every tuning
resample, and multiplies the memory and computation of a run; see the Imputation section of
setup_SupervisedPreprocessor.
Binary Classification
For binary classification, the outcome should be a factor where the 2nd level corresponds to the positive class.
Resampling
Note that you should not use an outer resampling method with replacement if you will also be using an inner resampling (for tuning). The duplicated cases from the outer resampling may appear both in the training and test sets of the inner resamples, leading to underestimated test error.
Reproducibility
If using outer resampling, you can set a seed when defining outer_resampling_config, e.g.
outer_resampling_config = setup_KFold(n_resamples = 10L, seed = 2026L)
If using tuning with inner resampling, you can set a seed when defining tuner_config,
e.g.
tuner_config = setup_GridSearch( resampler_config = setup_KFold(n_resamples = 5L, seed = 2027L) )
Parallelization
There are three levels of parallelization that may be used during training:
Algorithm training (e.g. a parallelized learner like LightGBM)
Tuning (where the full hyperparameter combination x inner resample cross product is processed in parallel, not just the resamples)
Outer resampling (where multiple outer resamples can be processed in parallel)
train() assigns all workers to exactly one of these levels, so that no two levels
compete for the same cores. The level is chosen by the first of these that applies:
the algorithm parallelizes itself, tuning is needed, outer resampling is set. A run
that needs none of them is sequential.
The workers, backend, and future plan all come from execution_config; see
setup_FutureExecution.
Reproducibility under parallelization
execution_config carries the master seed for the run's computation RNG, from which
one independent substream per outer resample is derived and assigned by fold index.
Results therefore do not depend on the backend, the number of workers, or the order
folds happened to finish in: a parallel run reproduces its sequential counterpart
exactly.
Object of class Regression(Supervised), RegressionRes(SupervisedRes),
Classification(Supervised), or ClassificationRes(SupervisedRes).
EDG
iris_c_lightRF <- train( iris, hyperparameters = setup_LightRF(), outer_resampling_config = setup_KFold(n_resamples = 3L) )iris_c_lightRF <- train( iris, hyperparameters = setup_LightRF(), outer_resampling_config = setup_KFold(n_resamples = 3L) )
Declares that a hyperparameter is searched over. It is the only way to express a search space: a bare vector is always a value, so nothing has to be inferred from how many elements it happens to have.
tune_over(...)tune_over(...)
... |
The candidates to search over: one per argument, or a single list or vector read against the type the hyperparameter declares. |
Give it the candidates. Several arguments are one candidate each; a single argument holding several values is the candidates, so a grid you computed can be passed straight in:
setup_LightRF(max_depth = tune_over(3L, 4L, 5L)) setup_LightRF(lambda_l2 = tune_over(10^seq(-4, 0, length.out = 5))) setup_MLP(hidden_units = tune_over(c(12L, 6L, 2L), c(14L, 12L, 6L, 2L)))
For a vector-valued hyperparameter one candidate is itself a vector, so
pass the candidates as separate arguments or as a list –
tune_over(list(c(12L, 6L), c(24L, 12L))). A single bare vector there would
be one architecture, and is an error saying so.
Passing it to a hyperparameter that is not tunable is an error: that hyperparameter accepts a value only.
HyperparameterCandidates object.
EDG
hp <- setup_LightRF(max_depth = tune_over(3L, 4L, 5L)) hp@max_depth # A bare vector is a value, never a search space. setup_LightRF(max_depth = 3L)@max_depthhp <- setup_LightRF(max_depth = tune_over(3L, 4L, 5L)) hp@max_depth # A bare vector is a value, never a search space. setup_LightRF(max_depth = 3L)@max_depth
The set of hyperparameter combinations a grid search would fit, one per row.
Derived from the object, so it can be inspected before train() is called.
tuning_grid(x)tuning_grid(x)
x |
|
The grid is the cross product of the search values, reduced by two rules:
A hyperparameter that declares it applies only under certain values of
another is set to NA – meaning "left unset for this fit" – in the rows
that do not meet them. reduce_basis applies only at smoothness_orders
of 0, so a search over both drops it from the higher-order rows.
Rows that become identical once that is done are collapsed, so a combination is never fit, scored, and ranked twice.
tune_GridSearch() fits exactly these rows, so what this prints is what will
run.
data.frame with one row per combination and one column per searched hyperparameter, or NULL if nothing needs tuning.
EDG
# reduce_basis applies only at smoothness order 0, so the six combinations # of the cross product reduce to four. tuning_grid( setup_HAL( smoothness_orders = tune_over(0L, 1L, 2L), reduce_basis = tune_over(0.1, 0.5) ) )# reduce_basis applies only at smoothness order 0, so the six combinations # of the cross product reduce to four. tuning_grid( setup_HAL( smoothness_orders = tune_over(0L, 1L, 2L), reduce_basis = tune_over(0.1, 0.5) ) )
Checks a config document – as parsed from JSON, or already resolved – and
reports what is wrong with it. With no data, only the schema is checked:
whether the document reconstructs into a valid rtemis config object. With
data, the config is additionally checked against the dataset it would run
on, catching the errors a schema cannot see: an outcome column that is not
there, more folds than the rarer class has cases, predictors that never vary.
validate_config(config, data = NULL, outcome = NULL, step = NULL)validate_config(config, data = NULL, outcome = NULL, step = NULL)
config |
Named list parsed from a config document (carrying its
|
data |
Optional tabular data: The dataset the config would run on. NULL checks the schema only. |
outcome |
Optional Character: Name of the outcome column in |
step |
Optional Integer [1, Inf): Position of this config in the plan it came from, recorded on every finding. NULL when the config stands alone. |
Nothing is thrown. Every finding is a Diagnostic carrying a stable code,
a severity, a technical message, a plain-language plain text, the
evidence behind it, and – where a deterministic one exists – a fix, an
RFC 6902 JSON Patch that resolves it. An empty result means the config is
clean.
Each data check runs only when the config carries the part it is about: the resampling checks need a resampler, the outcome checks need an outcome. A config carrying neither is checked for what it does declare and reports nothing about what it does not, so a preprocessing step and a training step each get the checks that apply to them.
Diagnostics object. Empty when nothing is wrong.
EDG
# A config that does not reconstruct: one finding, and no data checks. bad <- list( `$schema` = "https://schema.rtemis.org/supervised/r/v1/schema.json", n_foldz = 10L ) validate_config(bad) # A resolved config with nothing wrong: an empty Diagnostics. validate_config(setup_SuperConfig(hyperparameters = setup_LightRF()))# A config that does not reconstruct: one finding, and no data checks. bad <- list( `$schema` = "https://schema.rtemis.org/supervised/r/v1/schema.json", n_foldz = 10L ) validate_config(bad) # A resolved config with nothing wrong: an empty Diagnostics. validate_config(setup_SuperConfig(hyperparameters = setup_LightRF()))
Combine the variable importance measures of a model into one table: one row per predictor or model term and one column per measure.
varimp_table(x)varimp_table(x)
x |
|
Columns follow the order of the measures. A predictor a measure does not
cover is NA in that measure's column: some backends report only the
predictors used in a split. A measure named variable or fold, or one
repeating an earlier column, is labeled "<name> (measure)", since those
column names carry the table's structure.
The table holds the values only. What each measure quantifies, the cases it
was computed on, and how it ranks predictors are on the measure itself:
get_varimp(model)@measures[["<name>"]].
data.frame with a variable column and one numeric column per
measure.
EDG
mod <- train(iris, hyperparameters = setup_CART(), verbosity = 0L) varimp_table(get_varimp(mod))mod <- train(iris, hyperparameters = setup_CART(), verbosity = 0L) varimp_table(get_varimp(mod))
Write a config object to a schema.rtemis.org JSON file that can be read back
with read_config and consumed by rtemislive and the rtemis CLI. The
emitted JSON carries a $schema field identifying the config family, so the
reader can dispatch to the right object:
write_config(x, file, overwrite = FALSE, verbosity = 1L)write_config(x, file, overwrite = FALSE, verbosity = 1L)
x |
A |
file |
Character: Path to output JSON file. |
overwrite |
Logical: If TRUE, overwrite an existing file. |
verbosity |
Integer: Verbosity level. |
SuperConfig (from setup_SuperConfig) -> supervised schema.
DecomposeConfig (from setup_DecomposeConfig) -> decompose schema.
ClusterConfig (from setup_ClusterConfig) -> cluster schema.
DecompositionConfig (from setup_PCA(), setup_ICA(), ...) ->
decomposition schema.
ClusteringConfig (from setup_KMeans(), setup_DBSCAN(), ...) ->
clustering schema.
PreprocessorConfig (from setup_Preprocessor) -> preprocessor schema.
A config is an input: what a run is being asked to do. Fields it omits
fall back to their setup_* defaults when read, so a config stays valid as
those defaults improve. That is the opposite of a record, which states
what one run actually did, with every value resolved – see write_record.
The two are separate functions, so a caller names the artifact they want.
x, invisibly.
EDG
x <- setup_SuperConfig( dat_training_path = "~/Data/iris.csv", hyperparameters = setup_LightRF(), outer_resampling_config = setup_KFold(), question = "Can we tell iris species apart given their measurements?", outdir = "models/" ) tmpfile <- file.path(tempdir(), "rtemis.json") write_config(x, tmpfile, overwrite = TRUE)x <- setup_SuperConfig( dat_training_path = "~/Data/iris.csv", hyperparameters = setup_LightRF(), outer_resampling_config = setup_KFold(), question = "Can we tell iris species apart given their measurements?", outdir = "models/" ) tmpfile <- file.path(tempdir(), "rtemis.json") write_config(x, tmpfile, overwrite = TRUE)
A record states what a run actually did: every value resolved, where each one came from, and what produced it. A separate function from write_config, since the two artifacts answer different questions.
write_record(x, file, overwrite = FALSE, verbosity = 1L)write_record(x, file, overwrite = FALSE, verbosity = 1L)
x |
Fitted model object, or a record list from record. |
file |
Character: Path to write to. |
overwrite |
Logical: If TRUE, overwrite an existing file. |
verbosity |
Integer: Verbosity level. |
Three things distinguish a record from the config it came from:
Every field is present and resolved. A config omits what the user did
not set, so a reader applies defaults; a record leaves nothing to them, and
writes an unset field as an explicit null.
Each value says where it came from, in a parallel origin map:
user, default, derived (computed from the data), tuned, or unset
for a field a failed run never reached.
provenance records the rtemis and R versions, platform, timing,
outcome, and a fingerprint of the data.
For a supervised run the top level is what was asked for and folds is
what ran, one entry per model fitted – outer resampling resolves different
values in each fold, so a single resolved value at the top level would state
something no fold did.
A supervised record also states what the run scored. metrics holds each
sample's headline row as a flat metric-to-value map, averaged across outer
resamples, with metrics_sd beside it for the spread (null for a single
fit, which has none). The full metrics – the confusion matrix, the per-class
rows – are in each fold's own metrics. The flat block exists so that "was
this model any good?" is one lookup in one file, with no averaging and no R,
which is what makes a directory of records rankable.
train, decomp and cluster call this automatically when given an
outdir. A record is not a config: feeding one to read_config is an error,
since its resolved values would silently pin settings the new call should
decide for itself.
Unlike a config, a record is not compacted: an unset field is written as
an explicit null, so nothing in it falls back to a reader's defaults.
x, invisibly.
EDG
## Not run: mod <- train(iris, hyperparameters = setup_CART()) write_record(mod, "train_CART.record.json") ## End(Not run)## Not run: mod <- train(iris, hyperparameters = setup_CART()) write_record(mod, "train_CART.record.json") ## End(Not run)
Eligible outcomes, predictions, probabilities and resampling indices can stay inline or reference compressed Parquet files beside the JSON document. The outer resample structure remains in JSON. Fitted runtime objects are excluded. Move the JSON file and its accompanying directory together.
write_result( x, file, storage = c("auto", "inline", "parquet"), inline_max_bytes = 65536, base_dir = dirname(file), overwrite = FALSE )write_result( x, file, storage = c("auto", "inline", "parquet"), inline_max_bytes = 65536, base_dir = dirname(file), overwrite = FALSE )
x |
Published S7 report object. |
file |
Character: Output JSON path. |
storage |
Character: |
inline_max_bytes |
Numeric: In auto mode, maximum estimated uncompressed payload bytes kept inline: eight per numeric value or categorical code, one per Boolean, or UTF-8 string bytes plus eight per string. |
base_dir |
Character: Directory resolving existing DataRef paths. Defaults to the output directory. |
overwrite |
Logical: Replace an existing JSON file. |
x, invisibly.
result <- resample(1:6, setup_KFold(n_resamples = 2L), verbosity = 0L) directory <- tempfile("result-") dir.create(directory) write_result(result, file.path(directory, "result.json"), storage = "parquet") unlink(directory, recursive = TRUE)result <- resample(1:6, setup_KFold(n_resamples = 2L), verbosity = 0L) directory <- tempfile("result-") dir.create(directory) write_result(result, file.path(directory, "result.json"), storage = "parquet") unlink(directory, recursive = TRUE)
Write the human-readable rendering of a writeup, review or AI review to a file: the text print shows, laid out for a document. write_result writes the same objects as JSON documents for programs to read.
write_text(x, file, format = NULL, overwrite = FALSE, verbosity = 1L, ...)write_text(x, file, format = NULL, overwrite = FALSE, verbosity = 1L, ...)
x |
|
file |
Character: Path of the file to write. |
format |
Optional Character {"markdown"}: Output format. NULL selects
the format from the extension of |
overwrite |
Logical: If TRUE, replace an existing file. |
verbosity |
Integer: Verbosity level. |
... |
Not used. |
Markdown output starts at ## headings and uses pipe tables, ready to
convert with Pandoc or Quarto or to paste into a manuscript.
The path of the file written, invisibly.
EDG
idx <- c(1:40, 51:90, 101:140) mod <- train( iris[idx, ], dat_test = iris[-idx, ], hyperparameters = setup_CART(), verbosity = 0L ) write_text(writeup(mod), file.path(tempdir(), "writeup.md")) write_text(review(mod), file.path(tempdir(), "review.md"))idx <- c(1:40, 51:90, 101:140) mod <- train( iris[idx, ], dat_test = iris[-idx, ], hyperparameters = setup_CART(), verbosity = 0L ) write_text(writeup(mod), file.path(tempdir(), "writeup.md")) write_text(review(mod), file.path(tempdir(), "review.md"))
Describe a trained supervised model as the Methods and Results sections of a paper: the data, preprocessing, algorithm and settings, tuning, evaluation design, performance measures and statistical methods, and software, then the sample, performance with its uncertainty, the comparison with a baseline, and the hyperparameters tuning selected.
Two tables report the hyperparameters. The main table lists the algorithm's
primary hyperparameters, every hyperparameter that was tuned or specified,
and the values selected during fitting (such as a number of boosting rounds
chosen by early stopping); the supplementary table lists every
hyperparameter that applied to the fit, its value, how it was chosen and the
values tuning evaluated. A hyperparameter left unset is reported with what
that means for the fit. @hyperparameters holds the rows of both tables.
writeup(x, confidence_level = NULL, include_hyperparameters = NULL, ...)writeup(x, confidence_level = NULL, include_hyperparameters = NULL, ...)
x |
|
confidence_level |
Optional Numeric (0, 1): Confidence level of the intervals of a single-split model. NULL uses 0.95. |
include_hyperparameters |
Optional Character: Hyperparameters the main
hyperparameter table lists in place of the algorithm's primary
hyperparameters, beside those that were tuned or specified and the values
selected during fitting. NULL uses the primary hyperparameters;
|
... |
Not used. |
The text is assembled from the model and its review, so it states only
what rtemis recorded. Every number in the text is read from the model or
the review: the returned object holds each one in @values with the path of
the field it came from, and the paragraphs in @sections are templates in
which each number is a {key} token naming a row of @values. Statistical
methods are those review() used, cited in @references together with R,
rtemis and the packages that fitted the model, at the versions recorded
when the model was trained.
A Methods section also states the source of the data, the study design,
how the outcome and predictors were measured, and anything done to the data
before it was passed to rtemis. The model does not record these, so the
writeup lists them in @not_reported for the author to add.
Print the result to read it; write_text writes it as Markdown.
SupervisedWriteup object.
EDG
Clopper CJ, Pearson ES (1934). The use of confidence or fiducial limits illustrated in the case of the binomial. Biometrika, 26(4), 404-413.
DeLong ER, DeLong DM, Clarke-Pearson DL (1988). Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach. Biometrics, 44(3), 837-845.
McNemar Q (1947). Note on the sampling error of the difference between correlated proportions or percentages. Psychometrika, 12(2), 153-157.
idx <- c(1:40, 51:90, 101:140) mod <- train( iris[idx, ], dat_test = iris[-idx, ], hyperparameters = setup_CART(), verbosity = 0L ) writeup(mod) # Resampled mod_res <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(5L), verbosity = 0L ) writeup(mod_res)idx <- c(1:40, 51:90, 101:140) mod <- train( iris[idx, ], dat_test = iris[-idx, ], hyperparameters = setup_CART(), verbosity = 0L ) writeup(mod) # Resampled mod_res <- train( iris, hyperparameters = setup_CART(), outer_resampling_config = setup_KFold(5L), verbosity = 0L ) writeup(mod_res)