Package 'flexySelect'

Title: Select Predictors and Test Selectors Against a Planted Truth
Description: Selects predictors from a candidate set with any of 45 methods behind one interface, and tests the methods on data where the true predictors are known. Simulated data can have correlated predictors, non-linear and interacting effects, hidden confounders, random intercepts and slopes, and causal graphs with confounders, instruments, mediators and colliders. Published causal examples come with the exact bias of every adjustment set. Within a mixed model fitted with 'flexyBayes', it selects candidate fixed effects with a penalised path or a Bayesian reference model fitted with 'brms' and projected with 'projpred', cross-validated on whole sites, with a record of what was scored.
Authors: Max Moldovan [aut, cre] (ORCID: <https://orcid.org/0000-0001-9680-8474>), Emi Tanaka [ctb] (ORCID: <https://orcid.org/0000-0002-1455-259X>), Francis K.C. Hui [ctb] (ORCID: <https://orcid.org/0000-0003-0765-3533>), Anabel Forte Deltell [aut] (ORCID: <https://orcid.org/0000-0001-9534-1817>), Grains Research and Development Corporation [fnd, cph] (GRDC Project CUR2210-005OPX (AAGI-CU), UOA2301-005OPX (AAGI-AU), ROR: <https://ror.org/02xwr1996>)
Maintainer: Max Moldovan <[email protected]>
License: MIT + file LICENSE
Version: 0.3.1
Built: 2026-12-05 11:03:40 UTC
Source: https://github.com/max578/flexySelect

Help Index


Write a selection result as an orchestraManifest object

Description

The method of orchestraManifest::as_orchestra_manifest() for an fs_select() result, available when the suggested package 'orchestraManifest' is installed. It records which candidate terms were chosen, by which method and under which tuning. Whoever reads it can check with orchestraManifest::verify_manifest() that the payload has not changed since it was written.

The manifest has inferential_target = "parameters". Its params table holds one row per candidate term: index (the column of the problem's x), term (its name), selected, score and estimate (NA where the method returns none). The summary carries the headline, the number of candidates and of selected terms, the selected term names, the score type and whether the backend reported convergence.

A result with status "declined" or "error" is emitted with an empty params table and a summary marked abstained, whose abstain_reason is the registered reason code of the refusal, or "error". A consumer that gates on the summary therefore stops on it.

The grounding token in metadata$grounding is always the unverified one: a selection on data in hand is not checked against a known truth by being emitted. Scoring against an implanted truth is fs_score().

Arguments

x

An fs_result returned by fs_select().

...

Not used.

run_id

Optional single string naming the run. When NULL, an identifier is derived from the payload hash, so two identical results carry the same identifier.

Value

An orchestraManifest::orchestra_manifest.

See Also

fs_select(); orchestraManifest::verify_manifest() and orchestraManifest::consume_manifest() on the consuming side.

Examples

if (requireNamespace("orchestraManifest", quietly = TRUE)) {
  sim <- fs_design(n = 200L, p = 20L, n_true = 3L, r2 = 0.5, seed = 1L)
  res <- fs_select(sim, "marginal_bh", q = 0.05)
  m <- orchestraManifest::as_orchestra_manifest(res)
  m
  orchestraManifest::verify_manifest(m)$ok
}

Out-of-fold results from a selection

Description

Out-of-fold results from a selection

Usage

## S3 method for class 'fb_select'
augment(
  x,
  data = NULL,
  type = c("unit_scores", "assessment_predictions", "value_rows", "value_units"),
  against = NULL,
  ...
)

Arguments

x

An fb_select object.

data

Ignored; the out-of-fold results are the ones the folds computed and cannot be recomputed on other rows.

type

"unit_scores" (the default retained for compatibility), "assessment_predictions", "value_rows" or "value_units". "assessment_predictions" returns the optimiser decision's row-level assessment predictions, with original row positions, repeat and fold identifiers, scoring units, selected tuning coordinates and the verified score-contract hash. Observed and predicted values are on the modelled response scale, after any Gaussian offset has been subtracted. The last two return the valuation refit = list(method = "bayes") computed: one row per assessment row, with the refit's predictive mean and standard deviation, the log predictive density lpd, how the unseen cluster was integrated (method) and the value-contract hash; or one row per repeat and held-out unit, with its fold, row count and summed log predictive density elpd.

against

NULL, or, with type = "value_units", a second fb_select object on the same value contract: the table then carries elpd_against and the paired difference.

...

Ignored.

Value

A data.frame of per-unit out-of-fold scores, row-level assessment predictions, or the valuation's rows or units, according to type. A zero-row frame with the stable schema is returned where that result did not run. These are stored assessment results, not a prediction method for caller-supplied rows.


Declare how a selection decision is made

Description

The decision layer of fb_select(): which quantity is optimised, how a submodel size is chosen from it, and how the search over submodels is run. Validated at construction, so a rule that is missing the number it needs refuses before anything is fitted.

Usage

fb_decision(
  method = c("auto", "projection", "full", "posterior_threshold"),
  metric = c("elpd", "rmse", "nlpd"),
  rule = c("one_se", "min", "tolerance"),
  tolerance = NULL,
  search = c("forward", "L1"),
  nterms_max = NULL,
  validate_search = TRUE,
  threshold = 0.5,
  effect_size = NULL,
  stability_subsamples = 0L,
  stability_cutoff = 0.75,
  stability_unit = NULL,
  n_lambda = 20L,
  lambda_min_ratio = 0.001
)

Arguments

method

"auto" (default), "projection", "full" or "posterior_threshold". "auto" resolves to "projection" where the structure gate is green and to "full" where it is red.

metric

"elpd" (default), "rmse" or "nlpd". The projection decision is on elpd in this release; the other two are scored by the out-of-fold path.

rule

"one_se" (default), "min" or "tolerance".

tolerance

Nats per unit. Required by, and only used by, rule = "tolerance".

search

"forward", the only search this release executes. "L1" refuses with projection_search_unsupported: this module forces the protected and random terms into every submodel through a search_terms block written for a forward search, and no gate has run an L1 path against that block and read the ranking back, so whether the forced terms survive it is unmeasured.

nterms_max

Largest submodel the search considers. NULL (the default) uses every eligible term.

validate_search

Whether the search itself is cross-validated. TRUE (the default) is the assessment that is not optimistic; FALSE is a fast exploratory mode and is labelled optimistic on the result, in its print method and on the certificate.

threshold

Posterior probability cut, in (0, 1). Used by, and only by, method = "posterior_threshold".

effect_size

The practical effect size on the scientific scale, at or below which a coefficient is not of interest. Required by, and only used by, method = "posterior_threshold".

stability_subsamples

The number B of stability subsamples, a whole number. 0 (the default) draws none.

stability_cutoff

The frequency at or above which a column is stable, in (0.5, 1]. Read only when stability_subsamples is positive.

stability_unit

The units a subsample draws half of, as a one-sided formula or a character vector. NULL (the default) takes the resampling unit of fb_resamples(), and rows where that has none.

n_lambda

The number of points on the penalised optimiser's path, a whole number of at least 2. Read by the penalised optimiser workflow, the benchmark = TRUE arm, their stability subsamples and the ablation.

lambda_min_ratio

The smallest point of that path as a fraction of each fold's lambda_max, in (0, 1). The path runs from s = 1 down to this value on a log scale. Ridge and the exclusive lasso have no finite lambda_max; their path spans two decades either side of the declared penalty, and this setting is not read.

Details

"auto", the default, is resolved by fb_select() against the projection structure gate: "projection" where the reference model's structure is one the provider can project, and "full" where it is not. The resolution is recorded on the result and on its certificate, so a reader can see which decision ran and why. Most of what this package fits – known-covariance genomic and pedigree terms, unstructured and factor-analytic covariances, autoregressive fields, smooths – is red at that gate, and a default of "projection" meant those models refused only after a reference model had been sampled. Naming "projection" explicitly on a red gate still refuses, by name, with the feature that failed.

The three methods themselves answer three different questions.

"projection" projects the reference posterior onto each submodel and the submodel's expected log predictive density is assessed on the same folds the rest of the selection uses, with the standard error aggregated at the resampling unit rather than at the row. Protected terms and the base model's random terms are forced into every submodel.

"full" returns the reference posterior with no selection, for a user who wants shrinkage without a decision.

"posterior_threshold" marks a candidate retained when the posterior probability that the magnitude of its coefficient exceeds effect_size is above threshold. It is a decision rule and nothing more: a continuous shrinkage prior puts no mass at zero, so the quantity thresholded is not a posterior inclusion probability and must not be read as one. effect_size is on the scientific scale of the candidate column and has no default – what counts as a practically important effect is a property of the science, not of the software.

The three rules operate on the elpd curve by submodel size. "min" takes the best size. "one_se" takes the smallest size whose paired loss against the best is within one standard error of that paired difference. "tolerance" takes the smallest size losing less than tolerance nats per unit against the reference model.

The three stability_ settings ask for subsample stability of the penalised optimiser's support (Meinshausen and Buhlmann 2010, doi:10.1111/j.1467-9868.2010.00740.x). Each of stability_subsamples subsamples holds half of the units of stability_unit, drawn without replacement after set.seed(seed), and the penalised path is walked on it over the same s = lambda / lambda_max grid as the cross-validated path. A column's frequency at a point is the share of the subsamples whose solution holds it there, and the column is stable when its largest frequency at or above the chosen tuning point reaches stability_cutoff. Under the exchangeability condition of their Theorem 1, the expected number of falsely stable columns is at most ⁠q^2 / ((2 cutoff - 1) p)⁠, where q is the average number of columns a subsample selects in that region and p the number of penalised columns; the result reports both. The stable set is a read-out beside the optimiser's chosen support and does not replace it. It runs wherever the penalised optimiser runs, as the workflow or as the benchmark arm of benchmark = TRUE, and costs stability_subsamples penalised paths, which plan = TRUE states.

Value

An object of class fb_decision: a validated list carrying method, requested_method, metric, rule, tolerance, search, nterms_max, validate_search, threshold, effect_size, stability_subsamples, stability_cutoff, stability_unit, n_lambda and lambda_min_ratio.

See Also

fb_select(), which takes this object; fb_resamples() for the folds the decision is assessed on.

Examples

fb_decision()
fb_decision(rule = "tolerance", tolerance = 0.1)
fb_decision(method = "posterior_threshold", effect_size = 0.2)
fb_decision(stability_subsamples = 100L, stability_unit = ~ site)
fb_decision(n_lambda = 50L, lambda_min_ratio = 1e-4)

Declare a joint shrinkage prior over candidate fixed effects

Description

fb_penalty() writes the shrinkage half of a selection model: which candidate terms carry which prior, at what resolution, and on what scale. It is the second argument of fb_select(), and it validates at construction so a malformed specification is refused where it was written rather than inside a Stan program.

Usage

fb_penalty(
  ...,
  resolution = c("term", "coefficient"),
  scaling = c("train_fold_standardize", "none")
)

Arguments

...

One or more two-sided formulas, target ~ family(...), resolved in the order written.

resolution

"term" (the default) resolves targets to whole model terms; "coefficient" resolves them to single design columns. A coordinate-wise family aimed at one contrast column of a multi-column term is refused at "coefficient", because the support would move under a relevel that changes no model.

scaling

"train_fold_standardize" (the default) learns each candidate column's centre and scale inside the training rows of every fold and states the prior on the standardised column; "none" states it on the column as supplied.

Details

Each argument is a two-sided formula, target ~ family(...), and the constructors on both sides are parsed symbolically: they are the grammar's vocabulary, not exported functions.

Value

An fb_penalty object: a list carrying ⁠$specs⁠ (the parsed target and family of each formula), ⁠$resolution⁠ and ⁠$scaling⁠.

Targets

Targets are resolved by the typed term resolver against the model matrix's assignment map, never by string matching on coefficient names. A numeric main effect is one term and one column; a factor is one term and all of its contrast columns; an interaction is one term and every column it generates.

  • term(everything()) – every candidate term

  • term(x1, x2) – named terms, as bare symbols

  • term(c("x1", "x2")) – named terms, as a character vector

  • term(matches("^SLGA_")) – a regular expression on the term labels

starts_with() and the rest of the tidyselect vocabulary are not supported: a hidden evaluation environment for one selector is not worth the dependency, and matches() covers the use.

Later specifications override earlier ones for the coordinates they name, so term(everything()) ~ ridge(scale = 1) followed by term(x1) ~ laplace(scale = 0.5) is the ordinary idiom. Two selectors of equal breadth naming one coordinate leave no order and are refused. term(...) ~ none() marks a candidate explicitly unpenalised.

Families

Family Arguments Hyperparameters
ridge(scale) scale > 0, prior sd on the standardised scale fixed
laplace(scale) scale > 0 fixed
elastic_net(lambda, alpha) lambda > 0, alpha in (0, 1] fixed
regularized_horseshoe(p0, slab_scale, slab_df, df, df_global, scope) p0 in [1, p - 1] global and local scales learned
r2d2(mean_R2, prec_R2, cons_D2, scope) the explained-variance grammar learned

horseshoe() is an alias of regularized_horseshoe(). lasso() is an alias of laplace(), and announces once per session that the posterior mean of a Laplace prior is not a lasso estimate – the draws contain no exact zeros, so "selected" is always a named decision and never a property of the posterior.

elastic_net(lambda, alpha = 1) is the lasso corner of the elastic-net path: lambda_l2 is exactly zero there, and it fits and certifies on the glmnet provider, graded by glmnet's own Karush-Kuhn-Tucker conditions at the point it returns. Its Bayesian counterpart is laplace() (the lasso() alias above), and the two are named side by side: the posterior mean of a Laplace prior is not a lasso estimate, for exactly the reason lasso() already announces – the draws carry no exact zeros. alpha = 0 stays refused; that corner is ridge(), which already has its own name and its own row above.

The lambda of elastic_net() is used as the prior's rate on the Bayesian route (workflow = "bayes"). It does not set the chosen point on the penalised optimiser (workflow = "penalized_optimizer", and the glmnet arm of benchmark = TRUE). That point is tuned on the path that fb_decision() sets with n_lambda and lambda_min_ratio. There, lambda sets only the one declared point the optimiser also fits for comparison, and the top of a fold's path when that fold's lambda_max is zero.

A ridge or laplace prior has a mode identity with the corresponding penalised objective only with the covariance plugged in and the residual scale held fixed. The Bayesian route does neither: it integrates the covariance and samples sigma, so the prior's own scale is not a multiple of sigma and the identity does not hold at the posterior it returns. It holds on the fixed-covariance, fixed-sigma substrate the exact-limit bridges test, and it is that substrate the equivalence level map_exact_fixed_covariance names. elastic_net carries the same caveat and one more: relative to a Gaussian likelihood its effective penalty is multiplied by sigma, which the optimiser it is compared against does not have.

regularized_horseshoe() and r2d2() are class-wide in brms: they apply to every population-level coefficient except the intercept, and brms refuses a coefficient-specific row alongside them. A model with protected fixed effects beyond the intercept therefore refuses, and names both ways forward: a family that targets blocks exactly, or scope = "all_fixed", under which the protected coefficients also sit under the global-local prior and the certificate records the approximation.

scope = "block" keeps the protected coefficients outside the prior. The reference model is written as the brms non-linear formula y ~ a + b, where part a holds the intercept, the protected fixed effects and the random terms under the base model's own priors, and part ⁠b ~ 0 + <candidates>⁠ holds the candidate block under the class-wide prior. The block must hold every candidate, and no other block can be declared beside it. The intercept of part a is not centred, so a prior brms would put on the centred intercept is not carried; the base's declared priors are. The projection decision refuses on this scope, because the projection provider does not project a non-linear model, so decision = "auto" resolves to "full". Coefficients are reported under their own names, without the part prefix brms writes.

Grouped families

Four families read a grouping of the candidate columns. They are fitted by the penalised optimiser (workflow = "penalized_optimizer") and have no brms form, so asking for one on the Bayesian route refuses by name rather than substituting the nearest prior.

  • group_lasso(scale, group, alpha), with scale > 0 and alpha in (0, 1]: a group enters or leaves as a whole.

  • sparse_group_lasso(scale, alpha, group), with alpha in (0, 1): a group enters as a whole, and thins inside.

  • exclusive_lasso(scale, group), with scale > 0: members of a group compete.

  • group_exclusive(group_scale, exclusive_scale, group), with both scales > 0: both at once.

group declares how the columns are grouped, and it is never inferred from the data. "term" makes each model term one group, so a factor's non-reference contrast columns move together and a numeric main effect is a group of one. Under ordinary treatment contrasts the reference level has no design column and is therefore not inserted into the penalised group; its meaning remains in the intercept and the other protected terms. "block" makes the specification's own target set one group, which is how a cluster of correlated measurements is declared to be a set of competitors. group_lasso(), sparse_group_lasso() and group_exclusive() default to "term"; exclusive_lasso() defaults to "block". The rule and the resolved groups are recorded on the certificate. A grouping in which every group has one column refuses, since a group lasso would then be a lasso and an exclusive lasso a ridge.

group_lasso() charges ⁠(alpha / scale) * sum_g sqrt(p_g) ||beta_g||_2⁠, where p_g is the number of columns in group g. With alpha below one (default 1) it is a group elastic net and also charges ⁠((1 - alpha) / (2 * scale)) * ||beta||_2^2⁠; a group still enters or leaves as a whole.

The exclusive penalty adds ⁠sum_g (sum_j |beta_j|)^2 / 2⁠ over groups, which encourages competition inside a group and suits a declared set of correlated alternatives, for example one soil property measured at several depths. It does not guarantee that exactly one member is non-zero, and on a group of one it is exactly ridge() at the same scale.

adaptive() remains withdrawn and refuses by name. An adaptive penalty needs a first-stage estimate and a rule for turning that estimate into weights, and this release ships neither.

Examples

fb_penalty(term(everything()) ~ ridge(scale = 1))

fb_penalty(
  term(everything()) ~ ridge(scale = 1),
  term(x1) ~ laplace(scale = 0.5),
  term(matches("^z")) ~ none()
)

fb_penalty(term(everything()) ~ regularized_horseshoe(p0 = 3))

Declare the resampling scheme for a selection

Description

The folds a selection is scored on, as a validated object rather than as a scattering of arguments to fb_select(). Folds fall on the original observational units before any transformation, factor levels are frozen inside the training fold, and an assessment fold carrying a level the training fold never saw refuses by name rather than being dropped.

Usage

fb_resamples(
  unit = NULL,
  v = 10L,
  repeats = 1L,
  fold_id = NULL,
  strata = NULL,
  weights_by = NULL
)

Arguments

unit

Columns whose rows must stay together in a fold, as a one-sided formula (~ site) or a character vector. NULL (the default) splits rows.

v

Number of folds, at least 2.

repeats

Number of repetitions of the whole partition, at least 1. Repeats are scored as repeated measurements of the same units, never as independent evidence.

fold_id

An explicit partition, one entry per row of the data. Given together with v, or with repeats > 1, it refuses: an explicit partition and a scheme that would build one are two answers to the same question.

strata

Columns to stratify the fold assignment on, as a one-sided formula or a character vector. A stratifier that varies inside a unit refuses.

weights_by

Columns naming the groups whose observation weights are re-estimated in each fold, as a one-sided formula (~ trial) or a character vector. In each fold the base is refitted without weights on the training rows; s2 of a group is the mean squared residual of its training rows, random effects included; and the group's weight is median(s2) / s2. Held-out rows get weight 1. The base must have been fitted with weights. NULL (the default) keeps the base's weights in every fold.

Details

A unit alone is not a specification. It says what may not be split across a fold boundary, not how the splitting is done, so naming one without also naming v, repeats or an explicit fold_id refuses with selection_resamples_underspecified. The defaults of v and repeats are the unit-free defaults and do not silently supply a scheme to a grouped design.

Value

An object of class fb_resamples: a list carrying unit, v, repeats, fold_id, strata, weights_by and the resolved scheme ("v_fold" or "explicit").

See Also

fb_select(), which takes this object; fb_decision() for the decision rule scored on these folds.

Examples

fb_resamples()
fb_resamples(unit = ~ site, v = 5L)

Bayesian selection over a fitted flexyBayes model

Description

Fits a Bayesian reference model in which a declared block of candidate fixed effects carries a joint shrinkage prior and the covariance structure is integrated over rather than plugged in; selects a parsimonious submodel by projection predictive inference where the structure permits it, and refuses by name where it does not; and, on request, compares the result with an external penalised optimiser on the same folds.

Usage

fb_select(
  base,
  candidates,
  penalty = NULL,
  workflow = c("bayes", "penalized_optimizer", "unpenalized_benchmark"),
  fallback = c("none", "glmnet"),
  benchmark = FALSE,
  resamples = fb_resamples(),
  prediction = c("new_cluster", "known_cluster"),
  decision = fb_decision(),
  engine = NULL,
  seed = NULL,
  budget = NULL,
  plan = FALSE,
  covariance = c("reml_plugin", "base_model"),
  refit = NULL,
  ablation = FALSE,
  protected_alias = c("refuse", "drop"),
  keep_fold_data = FALSE,
  ...
)

Arguments

base

A fitted flexyBayes model. Its fixed effects are the protected block and are never penalised. A base fitted with weights is selected with residual variance sigma^2 / w on each training row and sigma^2 on each held-out row, whose weight the training rows do not give. Each fold refit is fitted with the weights of its rows. The projection decision refuses a weighted base with selection_weights_not_carried. On the benchmark and optimiser workflows, rows with a missing response, such as the cells fb_complete_grid() adds, are not fitted or scored in any fold, and an AR1 x AR1 field keeps its full grid.

candidates

A one-sided formula over columns of the base fit's data. A transform whose value on a row depends on other rows, in the candidates or in the base's fixed part, is learned inside each fold or refused: the benchmark workflows learn scale(), poly(), splines::ns() and splines::bs() on each fold's training rows and refuse any other such transform, and the Bayesian route's fold refits refuse every one, with selection_formula_transform_not_fold_local.

penalty

NULL (every candidate protected) or an fb_penalty() declaring the joint shrinkage prior over the candidate block.

workflow

"bayes" (default), "penalized_optimizer" or "unpenalized_benchmark". The third asks for the closed-form generalised-least-squares arm on its own – the same computation benchmark = TRUE adds beside a Bayesian answer – for a caller who wants the plugged-in-covariance comparison and not the posterior. It is never labelled Bayesian, on the object, in the print method or on the certificate.

fallback

"none" (default) or "glmnet". Fires only when the Bayesian provider is absent, never after a failure.

benchmark

TRUE also runs the unpenalised generalised-least-squares arm and, where a penalty was given, the penalised-optimiser arm on the same folds (glmnet for ridge, Laplace and elastic net; prox for grouped penalties) – and scores the reference model itself out of fold, so the arms have one loss at one unit to be placed beside. That last part is what the certificate's reference_predictive and decision_predictive tables report – the full-design models at one stage, the chosen models at the other, each written only when every arm shares one score contract, which identifies the folds, the response and every design column by their values – and what the equivalence level posterior_predictive_comparable requires; without it the certificate says so by name rather than claiming a comparison nobody made. It costs one reference refit per fold per model, and each fold's preprocessing and prior are learned on that fold's analysis rows. A projection's submodel is scored with terms searched again on each fold's reference fit, at the size the whole-sample decision chose. The optimiser arm's tuning point is reported as s = lambda / lambda_max, each fold's lambda_max read on its training rows, beside the lambda that point is on each fold. Its support at a point is the set of non-zero penalised coefficients after one rule: at s >= 1 every one is zero, the exact solution there; elsewhere a coefficient is set to zero when removing it moves its own gradient coordinate by at most the path's KKT threshold, and the point without it still meets that threshold. The threshold is 1e-6 for ridge, Laplace and elastic net. For the grouped families it is 1e-6 times the largest absolute entry of ⁠A'z⁠, the gradient of the least-squares part at zero on the fold's whitened, protected-residualised payload ⁠(A, z)⁠. Every path point is solved to its threshold, and group lasso and group elastic net points are solved by block coordinate descent.

resamples

An fb_resamples() specification.

prediction

"new_cluster" (default) or "known_cluster". A held-out cluster's own effect is not estimable from the training rows, so scoring it conditionally would reward the model for a random effect it was handed. Under "new_cluster" every column a random term's effect is indexed by is relabelled on the assessment rows; a vm(), ped() or autoregressive term cannot take a new level and refuses with selection_new_cluster_not_representable. Each assessment row's level L becomes L::fb_heldout, checked row by row before any fold is fitted; a fold in which a training row already carries such a label refuses with the same code.

decision

An fb_decision(): the method, metric, rule and search.

engine

NULL, or a named list setting chains, n_samples, warmup and adapt_delta for the brms reference fit. Deprecated fb_engine() objects remain accepted during the compatibility period.

seed

Required. The sampler, the posterior predictive check and the projection search all consume the random-number stream, and a default seed is an unreproducible run that looks reproducible.

budget

Seconds. The route refuses before the first fit when the estimated cost exceeds it.

plan

TRUE returns the resolved axes, the prior blocks, the projection structure gate and a cost estimate without fitting anything.

covariance

The source of the fold covariance V that the benchmark and optimiser workflows whiten by and plug in. "reml_plugin", the default, estimates V by restricted maximum likelihood on each fold's training rows, for random intercepts and two-way interactions. "base_model" refits the base model on each fold's training rows with its own formula, random and residual structure, priors and engine, and takes each variance at its posterior mean; it also builds uncorrelated random slopes, diag(f):g, an ar1(row):ar1(col) field on one trial, id(trial):ar1(row):ar1(col) (one field per trial with shared parameters) and vm() or ped() known covariances, at the cost of one refit per fold. The Bayesian workflow integrates the covariance, so the argument applies to it only with benchmark = TRUE. V is formed as a dense matrix only while one n by n matrix over the data fits within options(flexyBayes.selection_dense_gb = ), 0.5 GiB (8,192 rows) by default. Above that, a V that is block-diagonal over a grouping of its random terms is factored block by block, and any other V refuses with selection_dense_covariance_too_large. A V with one field per trial is factored by trial at any size. The argument's earlier form, an estimand string ("plugin_mean_covariance" and two others), is deprecated and runs the default.

refit

NULL (the default), or list(method = "bayes") to refit each fold's frozen support as a Bayesian model and score its held-out rows; see "Bayesian refit of the frozen support". Optional fields: block, a one-sided formula over terms of the base's fixed part or of candidates, the block whose share of between-trial variance is reported (default: every candidate); group, the grouping column of the random intercept whose variance is the between-trial variance (default: the base's only random intercept); n_draws, the posterior draws per fold (default 4000).

ablation

FALSE (the default), or TRUE to drop each declared block of the penalised path in turn and report the change in held-out loss; see "Grouped ablation". It needs workflow = "penalized_optimizer", and refuses with selection_ablation_route_undefined elsewhere, before any fit.

protected_alias

"refuse" (the default) or "drop": what a fold does with a protected column its training rows do not identify. See "Aliased protected columns". "drop" needs workflow = "penalized_optimizer" or "unpenalized_benchmark".

keep_fold_data

FALSE (the default), or TRUE to keep each fold's whitened data on the result, for fb_select_fold_data(), fb_select_path() and fb_select_refit(). It needs workflow = "penalized_optimizer" or "unpenalized_benchmark". The kept data holds the fold's design and Cholesky factor, so its size grows with the folds times the square of the training rows.

...

Reserved. metric is accepted here for one release with a deprecation notice; it now lives in fb_decision().

Details

Every result records four independent fields rather than one engine argument, because conflating the inferential workflow with the software that ran it is how a penalised-likelihood mode comes to be reported under a Bayesian label:

workflow

"bayes", "penalized_optimizer" or "unpenalized_benchmark".

provider

"brms", "inla", "glmnet", "prox", "gls_reml_plugin" or "gls_base_model"; "prox" is the package's deterministic proximal solver for grouped penalties, and the last two name the source of the benchmark's fold covariance.

prior

the joint prior, or "none".

decision

"full", "projection", "posterior_threshold" or "optimizer_support".

Posterior draws under a continuous shrinkage prior contain no exact zeros, so "selected" is always a named decision and never a property of the draws, and a posterior-threshold retention is not an inclusion probability. Every comparison against an external optimiser carries one of three equivalence levels – map_exact_fixed_covariance, posterior_predictive_comparable or no_identity_expected – and none of them licenses the sentence "the same as glmnet". The mode identity a ridge or Laplace prior has with a penalised objective holds only with the covariance plugged in and the residual scale held fixed; the Bayesian route integrates the covariance and samples sigma, so no arm of it reaches map_exact_fixed_covariance.

Where the decision is "projection", the search and the predictive evaluation run on CLUSTERED DRAWS rather than on the whole posterior – 20 clusters for the search, 100 for the evaluation. Projecting a multilevel submodel is a fit per draw, so projecting every draw at every search step inside every fold does not finish on a problem of the size this verb is for. Both counts are recorded on the result and on its certificate and printed on the object's first line, so a reader can see what the elpd column was computed from.

penalty = NULL keeps its earlier meaning: every candidate is protected and the fit is the extended base model. Under workflow = "bayes" it refits the base's own engine inside every assessment fold and scores held-out clusters by posterior predictive draws, which is the genuinely Bayesian no-penalty reference and the correct baseline for every shrinkage family. The closed-form generalised-least-squares route on a plugged-in fold covariance remains available through benchmark = TRUE and is labelled unpenalized_benchmark wherever it appears.

Fold refits run one at a time by default. options(flexyBayes.selection_workers = n) runs n of them at once, each in a separate R process started through callr (in Suggests; without it the request refuses with isolation_requires_callr), and divides the OpenMP threads between the workers so that workers times threads does not exceed the machine; an INLA fold runs at option flexyBayes.inla_threads, one thread by default (see flexybayes()). Nothing the run records changes: the fold allocation, each fold's candidate space, the score contract, the certificate and the selected support are identical to the serial run's, and the worker count is deliberately absent from the certificate, which describes the estimate while the worker count describes the machine that produced it. Engine numbers move as they move between any two repeated runs on an engine whose posterior sampler is not bit-reproducible. Set n against MEMORY: every concurrent fold holds its own rows and its own engine process at the same time, so the count a machine supports follows from its memory, and usually sits well below its core count. Measured on the package's synthetic selection fixture with INLA, penalty = NULL and four folds, the whole call held at its peak 1.7 GB with one worker and 3.0, 4.1 and 4.6 GB with two, three and four at 2,000 rows and 20 candidates; 2.4 GB with one worker and 3.8, 5.3 and 5.5 GB at 5,000 rows and 40 candidates; and, with three folds, 4.3 GB with one worker and 7.9 and 11.5 GB with two and three at 10,890 rows and 82 candidates (forked workers). A fold whose process ends before it returns refuses with isolated_process_died, naming the fold and the exit status or signal, this session carries on, and the aggregation keeps every fold or none.

options(flexyBayes.isolation = "fork") forks the workers from this session instead, on a platform that forks. A forked worker reports no exit status, and one that ends without returning refuses with selection_parallel_worker_failed.

options(flexyBayes.isolation = "process") also runs the folds in a separate R process when they run one at a time (see flexybayes()). Each fold in a separate process pays for starting R and reading its inputs: about 2 seconds a fold on the closed-form route, and 2.3 to 2.4 seconds a fit for flexybayes() at 96 and 5,000 rows. At 2,000 rows and 20 candidates the call held 2.1 GB with one fold at a time and 3.8 GB with three at once.

fallback = "none" is the default. A Bayesian request whose provider is absent refuses with selection_provider_absent, naming the package and the install line. fallback = "glmnet" is a deliberate choice; when it fires, workflow becomes penalized_optimizer, the object prints the substitution on its first line, and the certificate records fallback_fired = TRUE. There is no configuration that produces a penalised-likelihood answer under a Bayesian label.

Each fold's candidate space is fixed from the covariates on its training rows before any fold is fitted. The protected columns, then the candidate columns in the order candidates writes them, are factorised by qr() with tolerance 1e-7, every column but the intercept centred on the training rows. A protected column aliased there refuses with selection_fold_protected_unidentified, unless protected_alias = "drop" (see "Aliased protected columns"), and a factor level present only in a fold's assessment rows refuses with selection_fold_level_absent, both before any engine runs. A candidate column aliased there is dropped for that fold, as when a fold's training trials leave fewer degrees of freedom than its trial-level candidates need: the fold's fits and scores use the columns it keeps, every coefficient it reports keeps the declared columns in order with NA for a dropped one, and the certificate's design$candidate_space names each drop with its reason and counts, for each candidate column, the folds in which it was estimable. The glmnet arm's selection$candidate_availability places that count beside the number of folds whose support holds the column at the chosen point. The Bayesian route drops whole terms and refuses a term aliased only in part, and the penalised reference's out-of-fold score refuses any drop, both with selection_fold_candidate_drop_not_representable.

Value

An object of class fb_select carrying the four resolved axes, the reference fit, the column map, the decision, the out-of-fold scores, the increment over the protected model, the diagnostics, any benchmark arms, the folds and the certificate. With ablation = TRUE, its element ablation holds one row per block (blocks), the paired unit table (units), each ablated path's per-row predictions (rows, with the log predictive density lpd where the refit ran), chosen supports (supports) and tuning curves (paths), the density's paired unit table (value_units) and the columns each ablated refit held (value_supports), and the contract. With plan = TRUE, an object of class fb_select_plan, whose selection$ablation counts the ablation's fits.

Aliased protected columns

In an unbalanced multi-trial design some cells of a protected interaction VARIETY:NAPPLIED:SEEDRATE are never sown, so some of its columns are linear combinations of others, on all rows or on a fold's training rows. With protected_alias = "refuse" a fold like that refuses with selection_fold_protected_unidentified. With protected_alias = "drop" each fold drops them as ASReml 4.2 does: the protected columns are taken term by term, and within a term in descending order of their factor levels, the term's first factor varying slowest, and a column that is a linear combination of the columns before it on the training rows is dropped. These are the columns asreml reports as aliased, less the first-level columns that the treatment contrasts leave out.

A held-out row whose protected row is not a linear combination of the training rows' protected rows has no estimable prediction: its cell was never sown on the training rows, and predict() on the asreml fit returns NA for it. Such a row is not scored. The certificate's design$candidate_space lists each fold's dropped protected columns in protected_dropped and, in not_estimable, each fold's held-out rows and how many of them were not estimable, and the printed certificate gives the totals. A fold with no estimable held-out row refuses. The Bayesian workflow writes the protected part as formula text, which cannot leave out one column of a term, and refuses "drop". With refit = list(method = "bayes"), each fold's refit holds the protected columns that fold kept, entered as numeric columns as the support is, and value$not_estimable counts each fold's held-out rows left out of the log predictive density. With covariance = "base_model" the fold's variance components come from a refit of the base model with the fold's aliased protected columns fixed at zero (flexybayes(fixed_alias = "drop")).

A whole-data base with aliased fixed-effect columns is fitted with flexybayes(fixed_alias = "drop"); by default flexybayes() refuses it.

Bayesian refit of the frozen support

With workflow = "penalized_optimizer" and a penalty that selects, refit = list(method = "bayes") takes the support the optimiser chose on each fold at its chosen tuning point, freezes it, and refits the base model on that fold's training rows with the base's own engine (INLA or brms), random terms and priors, the support columns added to the protected fixed part. Nothing is selected again. Each support column enters as a numeric design column learned on the fold's training rows, so a fold that keeps one column of a factor and drops another is refitted on exactly the columns it kept.

Each assessment row is scored by its log predictive density, ⁠log((1/D) sum_d p(y_i | theta_d))⁠ over the refit's D posterior draws. Under prediction = "new_cluster", where every random term is an independent intercept, the unseen levels' effects are integrated in closed form: each draw's predictive is Gaussian with the fixed part's mean and the residual variance plus the random-intercept variances. Otherwise the engine's draws of the linear predictor are used. The per-unit sums, their total over held-out units and its standard error sqrt(U) * sd(elpd_u) are reported by glance.fb_select() and augment.fb_select(), with the hash of a value contract that identifies the folds, the scoring unit, the prediction target and the response values. Two runs on the same contract pair unit by unit: glance(x, against = y).

The block share follows the Bayesian R-squared of Gelman, Goodrich, Gabry and Vehtari (2019, doi:10.1080/00031305.2018.1549100). For each posterior draw of each fold's refit, with m_t the mean over the training rows of level t of group of the block's contribution ⁠sum_j x_ij beta_j⁠, the share is V_t(m_t) / (V_t(m_t) + sigma^2): the numerator is the sample variance of m_t over the fold's T training levels (divisor T - 1) and sigma^2 is the variance of the group random intercept. The draws of every fold are pooled, and the posterior median and 95% interval reported.

Grouped ablation

Under shrinkage a coefficient's size is not a column's importance. With workflow = "penalized_optimizer", ablation = TRUE drops each declared block of penalised columns in turn – the groups tidy(x, level = "group") reports: the grouping of a grouped penalty, and otherwise each penalty specification – and walks the path again on the same folds, with the same fold covariance, over the same grid of s = lambda / lambda_max, tuned by the same rule. Each held-out unit's loss, at the metric the path was tuned on and averaged over repeats, is paired with its loss under the full path. tidy(x, level = "group") reports the mean over units of the difference, the unit's loss without the block minus with it, so positive means the block lowers the held-out loss, and its standard error sd(d_u) / sqrt(U) over the U units. A block whose removal leaves no penalised column leaves the protected columns, fitted by generalised least squares on each fold. A block whose remaining penalty the path refuses is reported with the refusal and no difference. With refit = list(method = "bayes"), each ablated path's frozen supports are refitted as well, and the held-out log predictive density difference, elpd with the block minus without it, is reported beside the loss with the valuation's standard error.

Every path is scored under one contract, which identifies the fold of every row, the scoring unit, the target, the response and the metric, and its hash is on the result. The read-out is not nested: each path's tuning point is chosen on the out-of-fold scores of all folds, including the fold whose units are then scored, and the full and ablated paths share that reuse. On the package's synthetic two-block fixture (eight data seeds, both rules), choosing the point on inner folds of each training fold instead moved a signal block's difference by a median of 0.14 standard errors and changed none of 32 verdicts. A block that carries no signal is not read as important there, but its difference can be negative beyond one standard error: without it the path is tuned to less shrinkage.

See Also

fb_penalty() for the prior, fb_resamples() for the folds, fb_decision() for the rule.

Examples

if (requireNamespace("INLA", quietly = TRUE) &&
  requireNamespace("brms", quietly = TRUE)) {
  set.seed(1)
  d <- data.frame(
    site = factor(rep(1:8, each = 10)),
    x1 = rnorm(80),
    x2 = rnorm(80)
  )
  d$y <- 1 + 0.5 * d$x1 + rnorm(8)[d$site] + rnorm(80)
  base <- flexyBayes::flexybayes(y ~ 1 + (1 | site), data = d,
    backend = "inla", verbose = FALSE)
  # The plan resolves the axes, the prior blocks and the structure gate,
  # and estimates the cost, without fitting the reference model.
  fb_select(
    base,
    candidates = ~ x1 + x2,
    penalty = fb_penalty(term(everything()) ~ laplace(scale = 1)),
    seed = 1L,
    plan = TRUE
  )
}

Whitened data of each fold of a selection run

Description

Returns, for each fold of an fb_select() run kept with keep_fold_data = TRUE, the data its generalised least squares and its penalised path were computed from.

Usage

fb_select_fold_data(x, folds = NULL)

Arguments

x

An fb_select object from fb_select(keep_fold_data = TRUE).

folds

Fold labels to return, or NULL (the default) for every fold.

Details

Write ⁠V_TT = L L'⁠ for the fold's training covariance, built from the variance components in components. Then whitened holds ⁠L^-1 y⁠, ⁠L^-1 X0⁠ and ⁠L^-1 X⁠ on the training rows, and ordinary least squares on it is generalised least squares on the original rows. reduced holds the whitened response and penalised candidates with the protected block projected out: with Q0 an orthonormal basis of the column space of ⁠L^-1 X0⁠, ⁠y - Q0 Q0' y⁠ and ⁠X - Q0 Q0' X⁠. This is the data the penalised optimiser is given. Candidate columns are centred and scaled on each fold's training rows (centre, scale), and a Gaussian offset is already subtracted from response.

Value

A named list with one element per fold. Each element is a list with fold, train_rows and assess_rows (row numbers of the base's data), response (every row), x_protected and x_candidate (every row), centre and scale, whitened (a list of y, x_protected and x_candidate over the training rows), reduced (a list of y and x over the training rows), v_assess (the covariance of the held-out rows given the training rows) and components (the residual variance, each random term's variance, and any correlation parameters).

See Also

fb_select_path(), fb_select_refit().

Other selection fold data: fb_select_path(), fb_select_refit()

Examples

if (requireNamespace("INLA", quietly = TRUE)) {
  set.seed(1)
  d <- data.frame(site = factor(rep(1:6, each = 5)), x1 = rnorm(30),
                  x2 = rnorm(30))
  d$y <- 1 + 0.5 * d$x1 + rnorm(6)[d$site] + rnorm(30)
  base <- flexyBayes::flexybayes(y ~ 1, random = ~site, data = d,
    backend = "inla", verbose = FALSE)
  sel <- fb_select(base, ~ x1 + x2, workflow = "unpenalized_benchmark",
                   resamples = fb_resamples(unit = ~site, v = 3L),
                   seed = 1L, keep_fold_data = TRUE)
  fold <- fb_select_fold_data(sel, folds = "1")[["1"]]
  dim(fold$whitened$x_candidate)
}

Penalised path of a selection run at another alpha

Description

Solves the penalised path of an fb_select() run again on its kept fold data, at the run's own elastic-net mixing alpha or at another, and returns each fold's support at each point of the path. No model is refitted: the folds' covariances and standardisation are the run's.

Usage

fb_select_path(
  x,
  alpha = NULL,
  n_lambda = NULL,
  lambda_min_ratio = NULL,
  folds = NULL
)

Arguments

x

An fb_select object from fb_select(workflow = "penalized_optimizer", keep_fold_data = TRUE).

alpha

The elastic-net mixing parameter, a single number in ⁠(0, 1]⁠, or NULL (the default) for the run's own.

n_lambda, lambda_min_ratio

The grid, or NULL (the default) for the run's own.

folds

Fold labels to solve, or NULL (the default) for every fold.

Details

The grid is the run's: n_lambda points of s = lambda / lambda_max from 1 down to lambda_min_ratio, each fold's lambda_max read from its own training rows. At the run's alpha, the supports equal those the run reported. A different alpha needs every penalty block to be elastic_net(); a grouped penalty is solved by the package's own proximal solver and is not re-solved here.

Value

A data frame with one row per fold and path point: fold, lambda_index, s, lambda (the canonical lambda), n_support and support, the selected candidate columns sorted and joined by ";". Attribute alpha holds the alpha solved at.

See Also

fb_select_fold_data(), fb_select_refit().

Other selection fold data: fb_select_fold_data(), fb_select_refit()

Examples

if (requireNamespace("INLA", quietly = TRUE) &&
  requireNamespace("glmnet", quietly = TRUE)) {
  set.seed(1)
  d <- data.frame(site = factor(rep(1:6, each = 5)), x1 = rnorm(30),
                  x2 = rnorm(30))
  d$y <- 1 + 0.5 * d$x1 + rnorm(6)[d$site] + rnorm(30)
  base <- flexyBayes::flexybayes(y ~ 1, random = ~site, data = d,
    backend = "inla", verbose = FALSE)
  sel <- fb_select(
    base, ~ x1 + x2,
    penalty = fb_penalty(term(everything()) ~
                           elastic_net(lambda = 1, alpha = 1)),
    workflow = "penalized_optimizer",
    resamples = fb_resamples(unit = ~site, v = 3L),
    seed = 1L, keep_fold_data = TRUE
  )
  head(fb_select_path(sel, alpha = 0.5))
}

Refit a named column set on the folds of a selection run

Description

Refits the protected model plus a named set of candidate columns, without a penalty, on each fold of an fb_select() run kept with keep_fold_data = TRUE, and scores each held-out cluster.

Usage

fb_select_refit(x, columns, folds = NULL)

Arguments

x

An fb_select object from fb_select(keep_fold_data = TRUE).

columns

Candidate column names, as in the columns of fb_select_fold_data(x)[[1]]$x_candidate. character(0) refits the protected model.

folds

Fold labels to refit, or NULL (the default) for every fold.

Details

On each fold the coefficients are the generalised least squares estimate ⁠(X_S' V_TT^-1 X_S)^-1 X_S' V_TT^-1 y_T⁠, where X_S holds the protected columns and the named candidates on the training rows and V_TT is the fold's training covariance. A column the training rows leave aliased with the columns before it is reported with an NA coefficient and listed in not_identified. The held-out prediction is the one the run used (prediction in fb_select()). Each cluster's score is its mean squared error, root mean squared error and negative log predictive density per row under the covariance of its rows given the training rows.

Value

A list with three data frames: scores (fold, repeat_id, cluster, n, mse, rmse, nlpd), coefficients (fold, role, term, estimate, on each fold's standardised candidate scale) and not_identified (fold, term).

See Also

fb_select_fold_data(), fb_select_path().

Other selection fold data: fb_select_fold_data(), fb_select_path()

Examples

if (requireNamespace("INLA", quietly = TRUE)) {
  set.seed(1)
  d <- data.frame(site = factor(rep(1:6, each = 5)), x1 = rnorm(30),
                  x2 = rnorm(30))
  d$y <- 1 + 0.5 * d$x1 + rnorm(6)[d$site] + rnorm(30)
  base <- flexyBayes::flexybayes(y ~ 1, random = ~site, data = d,
    backend = "inla", verbose = FALSE)
  sel <- fb_select(base, ~ x1 + x2, workflow = "unpenalized_benchmark",
                   resamples = fb_resamples(unit = ~site, v = 3L),
                   seed = 1L, keep_fold_data = TRUE)
  fb_select_refit(sel, "x1")$scores
}

Accept or reject a clone against the real data

Description

Compares a clone with the real data on statistics of the predictors (layer 1) and of the outcome (layer 2), and accepts the clone when every statistic falls within its threshold.

Usage

fs_accept(real, clone, level = 0.05, n_null = 200L, seed)

Arguments

real

The real data: an fs_problem(), an fs_sim, or a numeric matrix or data frame of predictors (layer 1 only).

clone

The clone, in the same form and with the same columns.

level

The level α\alpha.

n_null

Number of splits of the real data.

seed

Integer seed for the splits. The caller's random-number state is put back.

Details

Layer 1, the predictors:

  • margin: the largest two-sample Kolmogorov-Smirnov distance over the columns;

  • moments: the largest, over the columns, of the absolute difference in means over the pooled standard deviation and the absolute log ratio of the standard deviations;

  • correlation: the largest absolute difference between the two correlation matrices;

  • spectrum: the largest absolute difference between the leading eigenvalues (up to ten) of the two correlation matrices.

Layer 2, the outcome, when both sides carry one:

  • outcome_margin: the Kolmogorov-Smirnov distance between the outcomes;

  • outcome_moments: the statistic of moments for the outcomes;

  • outcome_fit: the difference in the share of variance a linear fit on all predictors explains;

  • residual_shape: the Kolmogorov-Smirnov distance between the standardised residuals of those fits;

  • group_share: when both sides have groups, the difference in the share of outcome variance between groups, from the one-way analysis-of-variance estimator.

Each distance is multiplied by n1n2/(n1+n2)\sqrt{n_1 n_2 / (n_1 + n_2)}, the scale on which a two-sample distance between samples of one law does not depend on their sizes. The null distribution of each statistic is drawn from n_null splits of the real data into two halves, by whole groups when the real data have groups. A statistic's threshold is the 1−α/k1 - \alpha / k quantile of its null distribution, for level α\alpha and kk statistics, so the chance of rejecting a clone drawn from the real data's law is at most about α\alpha. The fits of layer 2 need more rows in each half than predictors plus one, and are left out otherwise.

The size-free scale holds as the number of units grows. With few groups a half holds too few units to stand in for the whole, and the rejection rate of a clone drawn from the real law exceeds α\alpha: over 100 clones of 300 rows at level 0.05 it was 0.01 without groups, 0.03 with 60 groups and 0.14 with 20 groups.

A clone made by masque is passed as an fs_problem() built from its table. Privacy is masque's to audit, and fs_accept() makes no claim about it.

Value

An object of class fs_accept: a list with accepted (logical), table (one row per statistic: layer, statistic, value, threshold, pass), null (the null draws, one column per statistic), level and n_null.

See Also

fs_implant() plants truth into an accepted clone.

Examples

real <- fs_design(n = 200L, p = 6L, n_true = 2L, predictors = "ar1",
  rho = 0.5, seed = 1L)
good <- fs_design(n = 200L, p = 6L, n_true = 2L, predictors = "ar1",
  rho = 0.5, seed = 2L)
fs_accept(real, good, n_null = 50L, seed = 1L)

Lay out a benchmark under the ADEMP headings

Description

Collects what a benchmark of selection methods did and found under the five headings of Morris, White and Crowther (2019): aims, data-generating mechanisms, estimands and other targets, methods, and performance measures, each measure with its Monte Carlo standard error.

Usage

fs_ademp(bench, aims, sims, mechanism = NULL)

Arguments

bench

An fs_benchmark from fs_benchmark().

aims

A character vector stating the aims of the study.

sims

The simulations the benchmark ran, in the same order: an fs_sim or a list of them. A benchmark does not keep them.

mechanism

Optional character vector naming the mechanism of each simulation. NULL groups simulations by their stored design.

Details

Data-generating mechanisms. Simulations whose stored design (truth$spec, less its seed and generator kind) is the same form one mechanism, unless mechanism names them. Each mechanism is described by its number of simulations, rows and columns, family and the design's settings.

Targets. The target is the true support of each simulation, scored under the definitions of a true positive the benchmark was scored with (read from its score table, "exact" when it has none). A weak tail is left out of every count, as in fs_score(). When a simulation holds a hidden confounder, a selected proxy counts as a false positive.

Performance. For each method and mechanism, over the cells where the method selected:

  • tpr, the true-positive rate, and fdr, the mean false-discovery proportion, under each definition of a true positive;

  • exact_support, the share of cells whose selection equals the true support (weak tail aside);

  • model_size, the mean number of columns selected.

Means carry the Monte Carlo standard error of Table 6 of Morris et al. for a mean, ∑i(θ^i−θˉ)2/(nsim(nsim−1))\sqrt{\sum_i (\hat\theta_i - \bar\theta)^2 / (n_{sim}(n_{sim} - 1))}, and the share carries that of a proportion, P(1−P)/nsim\sqrt{P(1 - P) / n_{sim}}. Cells that declined or failed have no selection to score: they are counted in cells for every method and mechanism, so a measure over fewer cells than were run shows as such.

Value

An object of class fs_ademp: a list with aims (the text given), data (one row per mechanism), estimands (one row per mechanism and definition of a true positive, with the mean and range of the support size), methods (one row per method: its backend versions and its tuning), cells (one row per method and mechanism: the counts of cells run, selected, declined and failed, and of cells whose backend reported a fit that did not converge, which are also counted as selected and scored) and performance (one row per method, mechanism, definition and measure: estimate, mcse and n, the number of cells behind it).

References

Morris, T. P., White, I. R. and Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. doi:10.1002/sim.8086

See Also

fs_benchmark() runs the cells, fs_score() scores them.

Examples

sims <- lapply(1:4, function(r) {
  fs_design(n = 120L, p = 15L, n_true = 3L, r2 = 0.5, seed = r)
})
bm <- fs_benchmark(sims, c("marginal_bh", "forward_stepwise"), seed = 1L)
fs_ademp(bm, "How often does each method find the support?", sims)

The population cost of each adjustment set in a regime

Description

For every set of observed controls of a regime, or for the sets given, returns the population coefficient of the treatment when the outcome is regressed on the treatment and the set, its bias against the estimand, whether the set is a valid adjustment set, and the variance of the least-squares estimate. The valid set with the smallest variance is marked as optimal.

Usage

fs_adjustment(regime, sets = NULL, n = NULL, max_controls = 10L)

Arguments

regime

An fs_regime, or the name of a preset of fs_regimes().

sets

NULL, or a list of character vectors, each a set of observed controls.

n

Optional sample size. With it, se and rmse are the standard error and the root mean squared error at that size.

max_controls

The largest number of controls for which every subset is tried.

Details

Variance. Every node of a regime is Gaussian, so the least-squares coefficient of the treatment XX from nn rows, in the regression of the outcome YY on XX, a set SS and an intercept, has variance

σY⋅XS2(n−∣S∣−3) σX⋅S2,\frac{\sigma^2_{Y \cdot XS}}{(n - |S| - 3)\, \sigma^2_{X \cdot S}},

where σA⋅B2\sigma^2_{A \cdot B} is the residual variance of AA given BB in the implied covariance. The ratio without the sample size, avar, is the asymptotic variance of Henckel et al. (2022, proposition 1 and eq. 3, p.585). The finite-sample factor n−∣S∣−3n - |S| - 3 is the mean of the inverse of a Wishart matrix on n−1n - 1 degrees of freedom, so se is exact at every n>∣S∣+3n > |S| + 3, not only in the limit. rmse adds the squared bias.

Validity. A set is valid when dagitty::isAdjustmentSet() accepts it for the total effect. Validity is not assessed for a direct effect, and valid and optimal are then NA. A node on which the regime's sample is selected is in every fit, as it is in fs_effect(). Selecting rows on a regressor leaves the least-squares coefficients of that regression unchanged, so the costs stay those of the population.

The optimal set. Among the valid sets, the one with the smallest asymptotic variance. When the graph's optimal set O(X,Y)=pa(cn)∖forbO(X, Y) = \mathrm{pa}(\mathrm{cn}) \setminus \mathrm{forb} (Henckel et al. 2022, definition 1 and theorem 3, p.590) holds observed nodes only, it is that set, and it is the optimal set whatever the coefficients. With hidden nodes the best set can depend on the coefficients (their example 5, p.597). Otherwise, and whenever a selection node is in every fit, it is found by trying every valid set of at most max_controls controls. A regime whose estimand is not identified has no optimal set.

Sets. With sets = NULL, every subset of the observed controls when there are at most max_controls of them; otherwise the empty set, all controls, the adjustment sets dagitty returns and the optimal set.

Value

A data frame with one row per set: set (a label such as "{Z, W}"), controls (a list column with the set), size, valid, optimal, slope, bias, avar, and with n also se and rmse. The attribute "optimal" holds the optimal set, or NULL.

References

Henckel, L., Perkovic, E., & Maathuis, M. H. (2022). Graphical criteria for efficient total effect estimation via adjustment in causal linear models. Journal of the Royal Statistical Society Series B: Statistical Methodology, 84(2), 579–599. doi:10.1111/rssb.12451

See Also

fs_regime() for the regime, fs_effect() for the estimates these costs describe.

Examples

if (requireNamespace("dagitty", quietly = TRUE)) {
  # An instrument costs variance only; with a hidden confounder it also
  # amplifies the bias.
  fs_adjustment("cinelli_9", n = 200L)
  fs_adjustment("cinelli_10", n = 200L)
}

Run selection methods over simulations

Description

Runs every method on every simulation and returns one status row per method-by-simulation cell, including the cells where a method failed or declined. The cells that selected are scored against the truth with fs_score().

Usage

fs_benchmark(sims, methods, seed, truth_def = NULL)

Arguments

sims

An fs_sim from fs_design(), or a list of them.

methods

A list of fs_method() objects or registry identifiers, one fs_method(), or a character vector of identifiers.

seed

Integer seed for the cells.

truth_def

Passed to fs_score().

Details

Each cell runs under its own seed, drawn from seed, so a benchmark repeats exactly and the caller's random-number state is left as it was. A cell's status is "selected", "declined" (with the reason code) or "error" (with the error's message). Warnings raised in a cell are counted in its row and kept with its result. A cell whose backend reports a fit that did not converge keeps the status "selected" and is flagged in the converged column, so it is scored and counted.

Value

An object of class fs_benchmark: a list with status, a data frame with one row per cell (replicate, method, status, reason_code, message, n_selected, n_warnings, converged, runtime); results, the cells' fs_result objects in the same order, each with its warnings; and score, the summary of fs_score() for each method over the replicates where it selected, with a method column.

See Also

fs_select() runs one method on one problem.

Examples

sims <- lapply(1:3, function(r) {
  fs_design(n = 150L, p = 20L, n_true = 3L, r2 = 0.5, seed = r)
})
bm <- fs_benchmark(sims, "marginal_bh", seed = 1L)
bm$status

Simulate a selection problem with known truth

Description

Draws a dataset in which the true predictors, their effects, any interacting pairs and the share of variance each part explains are fixed in advance, and returns it together with that truth.

Usage

fs_design(
  n,
  p,
  predictors = c("independent", "ar1", "block", "factor", "banded", "user"),
  rho = 0,
  block_size = 10L,
  n_factors = 2L,
  bandwidth = 2L,
  sigma = NULL,
  markers = FALSE,
  maf = c(0.05, 0.5),
  n_true = 5L,
  support = c("random", "one_per_block", "within_block", "spaced", "first"),
  effects = c("equal", "gaussian", "decreasing"),
  signs = c("random", "positive"),
  tail = 0,
  r2 = 0.5,
  n_pairs = 0L,
  heredity = c("strong", "weak", "none"),
  pair_form = c("product", "threshold", "xor"),
  r2_pair = 0,
  family = c("gaussian", "binomial", "poisson", "negbin"),
  n_groups = 0L,
  r2_group = 0,
  slope = NULL,
  r2_slope = 0,
  relmat = NULL,
  r2_relmat = 0,
  intercept = 0,
  count_mean = 5,
  theta = 2,
  seed
)

Arguments

n

Number of rows.

p

Number of candidate predictors.

predictors

Law of the predictors: "independent", "ar1", "block", "factor", "banded" or "user".

rho

Correlation between neighbouring columns ("ar1", between -1 and 1), within a block ("block", in [0, 1)), the share of each column's variance from the common factors ("factor", in [0, 1)), or the correlation of neighbours scaled by the band ("banded", in [0, 1]). Ignored by the other laws.

block_size

Number of consecutive columns in a block.

n_factors

Number of common factors under "factor".

bandwidth

Largest distance between correlated columns under "banded".

sigma

A p by p positive-definite correlation matrix, used when predictors = "user".

markers

If TRUE, predictors are 0/1/2 marker counts.

maf

Lower and upper bound of the minor-allele frequencies, each between 0 and 0.5.

n_true

Number of true predictors. Zero gives a design with no main effects and needs r2 = 0.

support

Placement of the true predictors: "random", "one_per_block", "within_block", "spaced" or "first".

effects

Effect sizes before scaling: "equal", "gaussian" or "decreasing".

signs

Signs of the effects: "random" or "positive".

tail

Rate of the weak geometric tail after the support, in [0, 1). Above zero it needs support = "first".

r2

Share of latent variance explained by the main effects.

n_pairs

Number of interacting pairs.

heredity

How many members of each pair are true predictors: "strong" (both), "weak" (one) or "none".

pair_form

Form of each pair's term: "product", "threshold" or "xor".

r2_pair

Share of latent variance explained by the pair terms. Above zero exactly when n_pairs is.

family

Response family: "gaussian", "binomial" (logit link), "poisson" or "negbin" (log link).

n_groups

Number of groups for a random intercept. Zero for none.

r2_group

Share of latent variance explained by the group intercepts. Must be zero when n_groups is zero.

slope

Column index or name of the predictor whose slope varies across the groups, or NULL for none.

r2_slope

Share of latent variance explained by the random slope. Above zero exactly when slope is given.

relmat

NULL, "linear", or an n by n positive semi-definite relationship matrix for a background random effect.

r2_relmat

Share of latent variance explained by the background. Above zero exactly when relmat is given.

intercept

Intercept of the linear predictor for the Gaussian and binomial families, at the mean of the fixed part.

count_mean

Approximate mean count for the Poisson and negative binomial families.

theta

Size parameter of the negative binomial, whose variance is μ+μ2/θ\mu + \mu^2 / \theta.

seed

Integer seed for the draw.

Details

Predictors. Six laws are offered.

  • "independent": standard normal columns.

  • "ar1": a first-order autoregression along the column order, with correlation rho between neighbours.

  • "block": exchangeable blocks of block_size columns, with correlation rho within a block and zero between blocks.

  • "factor": column jj has unit-length loadings λj\lambda_j on n_factors common factors and correlation ρλj⊤λk\rho \lambda_j^\top \lambda_k with column kk.

  • "banded": correlation ρ(b+1−d)/(b+1)\rho (b + 1 - d) / (b + 1) at distance d≤bd \le b, where bb is bandwidth, and zero beyond.

  • "user": the correlation matrix sigma.

With markers = TRUE each predictor becomes a 0/1/2 count: two latent copies are drawn under the same law and each is cut at the normal quantile of its allele frequency, drawn uniformly between the two values of maf.

Support and effects. Columns are grouped into consecutive blocks of block_size under every law. support places the n_true true predictors at random, one in each of n_true blocks, all in one block, at roughly equally spaced columns from the first to the last ("spaced"), or in the first n_true columns ("first"). Effects before scaling are equal, absolute standard normal, or equally spaced from 10 down to 0.5 ("decreasing"), with random or positive signs. A tail above zero gives every column after the support the weak effect taili−stail^{i - s}, as in beta-type 5 of Hastie, Tibshirani and Tibshirani (2020). Those columns are returned as weak, apart from the support. Their beta-types 1, 2, 3 and 5 are support = "spaced", "first", "first" with effects = "decreasing", and "first" with tail = 0.5, each with signs = "positive". Their paper leaves out beta-type 4 of Bertsimas, King and Mazumder (2016), and so does this function.

Interacting pairs. n_pairs pairs of columns each add one term to the linear predictor. Under heredity = "strong" both members of a pair are true predictors, under "weak" exactly one is, and under "none" neither is. The term is the product of the centred members ("product"), the indicator that both exceed their medians ("threshold"), or the indicator that exactly one does ("xor"). Each term is standardised over the drawn rows. A product or exclusive-or pair whose members are not true predictors carries no marginal signal, so the two columns are invisible one at a time and strong together.

Signal. Signal is stated as shares of latent variance. With latent residual variance σe2\sigma^2_e for the family, the total is T=σe2/(1−r2−rpair2−rg2−rslope2−rrel2)T = \sigma^2_e / (1 - r^2 - r^2_{pair} - r^2_g - r^2_{slope} - r^2_{rel}). The main effects and the pair terms are scaled together so that their sum has variance (r2+rpair2)T(r^2 + r^2_{pair}) T over the drawn rows, split between them in the ratio of the two shares. When the two parts are correlated over the drawn rows, as a threshold pair is with its members, each part's own variance moves away from its nominal share and the total stays exact. The same r2 therefore means the same share of latent variance in every family. For count families the intercept gives a mean count of about count_mean.

Random structure. Group intercepts have population variance rg2Tr^2_g T. A random slope on column slope across the same groups has population variance rslope2Tr^2_{slope} T, given the drawn values of that column. A relationship background is drawn from a normal distribution with covariance proportional to relmat, scaled to give variance rrel2Tr^2_{rel} T at the mean of its diagonal. With relmat = "linear" the matrix is the cross-product of the centred candidate columns, which for marker columns is the genomic relationship of VanRaden (2008) up to scale. That background is a dense combination of every candidate column. It is returned as a random effect, and beta holds the sparse effects only.

The draw is made under seed and the caller's random-number state is put back as it was found.

Value

An object of class fs_sim: a list holding problem, an fs_problem(), and truth, an object of class fs_truth with

  • support: column indices of the true predictors;

  • weak: column indices of the weak tail (empty without one);

  • beta: main effects on the linear-predictor scale, zero off the support and the tail;

  • pairs: one row per pair with the member columns j and k, the form, the cut points or centres of the members, the centre, scale and coefficient coef of the term, and the shares of latent variance explained by each member alone (r2_marginal_j, r2_marginal_k) and by the pair's own terms together (r2_joint);

  • intercept, and eta, the linear predictor of every row;

  • variance: the requested fixed, pair, group, slope, relationship and residual variance on the linear-predictor scale;

  • random: the drawn group intercepts and slopes (one per group) and the relationship background (one per row);

  • law: the factor loadings under "factor";

  • spec: the arguments of the call, with the seed and the random-number kind.

References

Hastie, T., Tibshirani, R. and Tibshirani, R. (2020). Best subset, forward stepwise or lasso? Analysis and recommendations based on extensive comparisons. Statistical Science, 35(4), 579–592. doi:10.1214/19-STS733

Nakagawa, S., Johnson, P. C. D. and Schielzeth, H. (2017). The coefficient of determination R2 and intra-class correlation coefficient from generalized linear mixed-effects models revisited and expanded. Journal of the Royal Society Interface, 14(134), 20170213. doi:10.1098/rsif.2017.0213

VanRaden, P. M. (2008). Efficient methods to compute genomic predictions. Journal of Dairy Science, 91(11), 4414–4423. doi:10.3168/jds.2007-0980

Examples

sim <- fs_design(n = 200L, p = 50L, predictors = "ar1", rho = 0.5,
  n_true = 5L, r2 = 0.4, seed = 1L)
sim
sim$truth$support

# Two weak predictors that are strong together
syn <- fs_design(n = 500L, p = 20L, n_true = 2L, r2 = 0.1, n_pairs = 1L,
  heredity = "none", pair_form = "xor", r2_pair = 0.4, seed = 2L)
syn$truth$pairs

Estimate a planted treatment effect

Description

Fits each outcome of each simulation from fs_plant() on the treatment, the covariates an adjustment names and, when the problem has groups, a random intercept, and returns the estimated contrast of every treatment level against the lowest beside its planted value.

Usage

fs_effect(
  sims,
  adjust = c("none", "all", "selected", "valid"),
  selections = NULL,
  rows = c("all", "complete"),
  level = 0.95
)

Arguments

sims

An fs_sim from fs_plant(), or a list of them.

adjust

"none", "all", "selected" or "valid".

selections

With adjust = "selected", a list with one element per simulation: the selected columns.

rows

"all", or "complete" for the complete cases recorded by fs_from_clone().

level

Confidence level of the intervals.

Details

The treatment enters as a factor, so every level has its own contrast whatever the planted shape. The continuous treatment of a generated regime (see fs_regime()) enters as a number, and its one estimate is the slope, at level "slope", against the regime's estimand. The reference fit is stats::lm(), or lme4::lmer() (REML) with a random intercept for the groups. Intervals are tt intervals for lm() and Wald intervals for lmer(). The global test of no treatment effect is the Wald test on all contrasts together: an FF test for lm(), χ2\chi^2 for lmer().

adjust chooses the covariates: "none", "all" the columns of x, "selected" those in selections, one element per simulation, as column indices or names (for example the selected of fs_select()), or, for a generated regime, "valid", the first adjustment set of dagitty::adjustmentSets(). A regime whose estimand has no valid set is declined under "valid". A node on which a regime's sample is selected is adjusted for under every choice. rows = "complete" fits on the clone's complete cases only, for the sensitivity analysis of imputed covariates.

With two outcomes, the correlation of their fitted residuals in each simulation is returned in the attribute "resid_cor".

Value

A data frame with one row per simulation, outcome and treatment level other than the lowest: sim, outcome, level, truth, estimate, se, lower, upper, p_global, n, adjust, rows and estimator.

References

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. doi:10.1002/sim.8086

Examples

x <- matrix(stats::rnorm(400L), ncol = 2L)
trt <- rep(c("a", "b"), 100L)
sims <- lapply(1:20, function(s) fs_plant(x, trt, effect = 0.3, seed = s))
est <- fs_effect(sims, adjust = "all")
fs_effect_ademp(est)

Performance of a planted-effect estimator over replicates

Description

Summarises the estimates of fs_effect() for each outcome, treatment level, adjustment and row set: bias, empirical SE, mean squared error, coverage of the intervals and the rejection rate of the global test, each with its Monte Carlo SE.

Usage

fs_effect_ademp(effects, alpha = 0.05)

Arguments

effects

A data frame from fs_effect().

alpha

Level of the global test for the rejection rate.

Details

With θ^i\hat\theta_i the estimate in replicate ii of nsimn_{sim}, θ\theta the planted value and θˉ\bar\theta the mean estimate, the Monte Carlo SEs are those of Morris, White and Crowther (2019, Table 6): for the bias ∑(θ^i−θˉ)2/(nsim(nsim−1))\sqrt{\sum(\hat\theta_i - \bar\theta)^2 / (n_{sim}(n_{sim} - 1))}, for the empirical SE EmpSE^/2(nsim−1)\widehat{EmpSE} / \sqrt{2(n_{sim} - 1)}, for the MSE ∑[(θ^i−θ)2−MSE^]2/(nsim(nsim−1))\sqrt{\sum[(\hat\theta_i - \theta)^2 - \widehat{MSE}]^2 / (n_{sim}(n_{sim} - 1))}, and for coverage and rejection p^(1−p^)/nsim\sqrt{\hat p(1 - \hat p) / n_{sim}}. The rejection rate is of the global test at alpha, so it is the same on every level of an outcome.

The RMSE is MSE^\sqrt{\widehat{MSE}}. Table 6 gives no Monte Carlo SE for it, so its SE is the first-order delta-method value SE^(MSE^)/(2MSE^)\widehat{SE}(\widehat{MSE}) / (2\sqrt{\widehat{MSE}}), reported as NA when MSE^\widehat{MSE} is less than twice its own Monte Carlo SE, where that approximation fails. The square root of a mean underestimates the true RMSE slightly, by about Var(MSE^)/(8 MSE3/2)\mathrm{Var}(\widehat{MSE}) / (8\,MSE^{3/2}). With normal errors and no bias that is a relative 1/(4nsim)1/(4 n_{sim}), 0.125% at 200 replicates.

When effects carries residual correlations, rows with level "residual correlation" give their mean, bias and empirical SE.

Value

A data frame with one row per outcome, level, adjustment and row set: outcome, level, adjust, rows, n_sim, truth, bias, bias_mcse, emp_se, emp_se_mcse, mse, mse_mcse, rmse, rmse_mcse, coverage, coverage_mcse, rejection and rejection_mcse.

References

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. doi:10.1002/sim.8086

Examples

x <- matrix(stats::rnorm(400L), ncol = 2L)
trt <- rep(c("a", "b"), 100L)
sims <- lapply(1:20, function(s) fs_plant(x, trt, effect = 0.3, seed = s))
est <- fs_effect(sims, adjust = "all")
fs_effect_ademp(est)

Read a masque null clone for planting a causal truth

Description

Turns a null clone made by masque::mask() into the parts a planted outcome needs: a numeric matrix of predictors, the treatment column and, optionally, the groups of a random intercept. The clone's columns are read as they are.

Usage

fs_from_clone(clone, treatment, groups = NULL, covariates = NULL)

Arguments

clone

A masque object made by masque::mask() with mode = "null".

treatment

Name of the treatment column, a single string.

groups

Name of the column whose levels are the groups, or NULL for a problem without groups.

covariates

Names of the numeric columns to keep as predictors. NULL keeps every numeric column whose role in the clone is "covariate", other than treatment and groups.

Details

Only a clone made in "null" mode is read: in that mode no value of the real table survives, so whatever is planted on the clone is the whole truth.

Missing values. A null clone keeps the missing-value pattern of the real table. A missing predictor value is replaced by the median of its column, and complete marks the rows in which no value was replaced. Fitting an effect on all rows and again on the complete rows gives the imputed and the complete-case estimates, and both are reported. A row with a missing treatment or group is dropped, since neither can be imputed without changing what is planted, and the number dropped is returned.

Treatment. In null mode masque codes a treatment by a random permutation, so a numeric dose arrives as unordered codes unless it was given the role design with the action keep in masque, which null mode leaves as it is. The treatment is returned as the clone holds it.

Value

A list of class fs_clone_data:

x

Numeric matrix of the predictors, missing values imputed.

complete

Logical, one per row of x: TRUE where no value was imputed.

imputed

Integer, named by column: the values imputed.

treatment

The treatment column.

groups

Factor of the groups, or NULL.

rows

Integer: the rows of the clone kept.

dropped

Integer: the rows dropped for a missing treatment or group.

References

Cinelli, C., Forney, A., & Pearl, J. (2024). A crash course in good and bad controls. Sociological Methods & Research, 53(3), 1071-1104. doi:10.1177/00491241221099552

Examples

d <- agridat::besag.met
roles <- masque::propose_roles(d, mode = "null")
roles <- masque::set_role(roles, c("row", "col"), role = "covariate")
clone <- masque::mask(d, roles, mode = "null", seed = 1, quiet = TRUE)
cd <- fs_from_clone(clone, treatment = "gen", groups = "county")
dim(cd$x)
table(cd$complete)

Cross the factors of a data source into mechanisms

Description

Builds the data-generating mechanisms of a study from one source and the values of its arguments. An argument of length one is fixed; a longer one is crossed with every other crossed argument. The result is read by fs_study().

Usage

fs_grid(source, ...)

Arguments

source

A preset name or names, an fs_regime, or one of the generator functions fs_design, fs_implant and fs_plant.

...

Named arguments of the source, each a value or a vector of values to cross.

Details

Sources. A regime source is the name of a preset of fs_regimes(), a vector of such names (crossed like any other factor), or an fs_regime. Its mechanisms are drawn by fs_plant() and need the sample size n. An argument named by an edge ("Z->Y") sets that coefficient of the regime; protect goes to fs_plant(), so protect = c(TRUE, FALSE) runs every cell with the treatment in and out of the selection problem; other arguments go to fs_regime() as the parameters of the preset "hahn_ric". A regime given as an object takes edge arguments only when it was built from a preset other than "hahn_ric".

A generator source is fs_design, fs_implant or fs_plant itself, and its arguments are those of the generator. The seed is not among them: it belongs to the study. Mechanisms of fs_plant drawn from a regime come from a regime source.

Fixed and crossed. I() keeps a vector as one value. A list of length above one is crossed element by element, so a factor whose levels are vectors is written list(c(1, 2), c(3, 4)). Data are always one value: a matrix, a data frame or another classed object, and the vectors given as y, groups, block or treatment, or as maf. Several data sets are crossed by giving them as a list.

The grid is a data frame with one row per mechanism. Its rows and the mechanisms fs_study() reads are built together, so fs_study() refuses a grid whose rows were subset; a smaller study takes a new grid.

Value

An object of class fs_grid: a data frame with columns mechanism (a readable label), source and one column per crossed argument. The attribute "mechanisms" holds each mechanism's full argument list, and for a regime source the regime itself.

See Also

fs_study() to state a study over one or more grids.

Examples

if (requireNamespace("dagitty", quietly = TRUE)) {
  fs_grid("near_instrument", n = c(100L, 500L), "Z->Y" = c(0, 0.1))
}
fs_grid(fs_design, n = c(100L, 400L), p = 50L, rho = c(0, 0.5))

Plant a known truth into real or cloned data

Description

Builds a selection problem with a known truth from a table of predictors, real or cloned, so selectors can be scored on data shaped like the data in hand.

Usage

fs_implant(
  x,
  y = NULL,
  mode = c("simulate", "spike", "null", "decoys"),
  family = c("gaussian", "binomial", "poisson"),
  groups = NULL,
  outcome = c("sparse", "dense"),
  n_true = 5L,
  support = c("random", "one_per_block", "within_block", "spaced", "first"),
  block = NULL,
  effects = c("equal", "gaussian", "decreasing"),
  signs = c("random", "positive"),
  r2 = 0.3,
  r2_group = 0,
  n_decoys = NULL,
  resample = FALSE,
  n_pairs = 0L,
  heredity = c("strong", "weak", "none"),
  pair_form = c("product", "threshold", "xor"),
  r2_pair = 0,
  n_nonlinear = 0L,
  shape = c("quadratic", "sine", "threshold"),
  r2_confounder = 0,
  n_proxies = 2L,
  confound = 1L,
  slope = NULL,
  r2_slope = 0,
  seed
)

Arguments

x

Numeric matrix or data frame of the predictors.

y

The real outcome, one value per row of x. Needed by every mode except "simulate", which uses it for calibration when given.

mode

"simulate", "spike", "null" or "decoys".

family

Response family of the planted outcome in "simulate", and of y otherwise: "gaussian", "binomial" or "poisson". "spike" takes "gaussian" only.

groups

Optional grouping of the rows, one value per row.

outcome

"sparse" or "dense".

n_true

Number of true predictors under "sparse".

support

Placement of the true predictors, as in fs_design().

block

Optional integer block of each column, used by support and by grouped selectors. Each column is its own block when NULL.

effects

"equal", "gaussian" or "decreasing", as in fs_design().

signs

"random" or "positive".

r2

Share of variance the planted signal explains.

r2_group

Share of variance of the group intercepts in "simulate" when it is not calibrated from y.

n_decoys

Number of decoy columns in "decoys", by default the number of columns of x.

resample

Whether to draw the rows by whole groups first.

n_pairs

Number of interacting pairs.

heredity

"strong", "weak" or "none", as in fs_design().

pair_form

"product", "threshold" or "xor", as in fs_design().

r2_pair

Share of variance of the pair terms. Above zero exactly when n_pairs is.

n_nonlinear

Number of true columns entering through shape.

shape

"quadratic", "sine" or "threshold".

r2_confounder

Share of variance of the hidden confounder.

n_proxies

Number of proxy columns of the confounder.

confound

Number of true columns the confounder is tied to.

slope

Column of x, as an index or a name, whose slope varies across groups.

r2_slope

Share of variance of the random slope. Above zero exactly when slope is given.

seed

Integer seed. The caller's random-number state is put back.

Details

Four modes:

  • "simulate" keeps the predictors and draws a new outcome. With a Gaussian y, the outcome's mean, its group variance and its total variance are those of the null fit of y (one-way analysis of variance by groups), and the planted signal takes the share r2 of that total from the residual. Without y, the total is one and the group share is r2_group. For a binomial or Poisson outcome, y sets the intercept only, and the shares are of the latent variance as in fs_design(). The truth is complete.

  • "spike" adds the planted signal to the real Gaussian y, scaled so that it explains the share r2 of the new outcome's variance. Only the implants are labelled: any signal already in y counts against a method as a false positive.

  • "null" permutes y within groups (or over all rows without groups). Nothing is true.

  • "decoys" appends n_decoys columns made by permuting the rows of randomly chosen columns of x together, so the decoys keep the correlation among themselves and lose any relation to y. The original columns are left unlabelled and out of scoring, and every decoy a method selects is a false positive.

outcome sets the outcome model of the first two modes: "sparse" plants n_true effects placed by support, and "dense" gives every column a Gaussian effect. Schreck et al. (2024) warn that a sparse outcome model favours sparse methods in the comparisons made on it, so a benchmark that runs both gives each kind of selector its own case.

With resample = TRUE, rows are first drawn with replacement by whole groups (or by row without groups), and each drawn group is a new group.

Further ingredients. Four more parts of the truth can be planted in "simulate" and "spike" (random slopes in "simulate" only). Each is off by default.

  • Interacting pairs on the real columns, as in fs_design(): n_pairs pairs chosen under heredity, each adding one standardised term of form pair_form, with share r2_pair.

  • Non-linear main effects: n_nonlinear of the n_true true columns enter through shape in place of a linear term: the centred square ("quadratic"), a sine over one period of the column's range ("sine"), or the indicator above the median ("threshold"). Each term is standardised over the rows and shares r2 with the linear effects. A shaped column stays in the support, its beta is NA, and truth$shapes records its shape and coefficient. A quadratic term of a symmetric column has almost no linear correlation with the outcome.

  • A hidden confounder U with share r2_confounder, built from the columns in hand and left out of x: n_proxies columns off the support and outside the pairs are its proxies, and it is tied to confound of the true columns. U is the standardised sum of three equal parts: the mean of the standardised confounded columns, the mean of the standardised proxies, and independent noise. truth$confounder holds U, its coefficient, the proxies, the confounded columns, the correlation of each column with U, and the omitted-variable bias of each column's coefficient when U is left out, βU(X⊤X)−1X⊤U\beta_U (X^\top X)^{-1} X^\top U with an intercept in the fit. fs_score() scores a selected proxy under proxy_rule.

  • A random slope on column slope across groups, with population variance r2_slope times the total, as in fs_design(). The problem's slopes names it, so methods that do not carry slopes decline.

The planted parts (main effects with their shapes, pairs and U) are scaled together, so that their sum has the requested total share. When two parts are correlated over the rows, as U is with the columns it confounds, each part's own share moves away from its request and the total stays exact. In "spike", the shares are of the new outcome's variance, the planted parts taken as independent of y.

Value

An object of class fs_sim, as from fs_design(), whose truth records the mode in spec$mode, and shapes and confounder when those ingredients are planted.

References

Schreck, N., Slynko, A., Saadati, M., & Benner, A. (2024). Statistical plasmode simulations: Potentials, challenges and recommendations. Statistics in Medicine, 43(9), 1804-1825. doi:10.1002/sim.10012

See Also

fs_accept() asks whether a clone is close enough to the real data for scores on it to mean anything.

Examples

real <- fs_design(n = 150L, p = 12L, n_true = 0L, n_groups = 10L,
  r2 = 0, r2_group = 0.3, seed = 1L)$problem
sim <- fs_implant(real$x, real$y, groups = real$groups, n_true = 3L,
  r2 = 0.4, seed = 2L)
sim$truth$support
fs_score(sim, sim$truth$support[-1L])

Lift a Gaussian selection method to non-Gaussian responses

Description

Wraps a Gaussian selection method so that it runs on binomial, Poisson and negative-binomial responses, with or without grouped random effects, through a working response in the manner of penalised quasi-likelihood (Breslow and Clayton 1993). The result is an approximation: it is marked experimental and is never a default.

Usage

fs_lift(method)

Arguments

method

An fs_method() or the identifier of a method listed by fs_methods(). It must fit Gaussian responses on the "whitened" route and require no random structure.

Details

A null generalised linear mixed model is fitted once: an intercept, the problem's random-slope columns as fixed effects, and a random intercept and slopes across groups with an unstructured covariance G, by lme4::glmer() for binomial (logit link) and Poisson (log link) responses and by glmmTMB::glmmTMB() with nbinom2() for the negative binomial; without groups, by stats::glm() or glmmTMB::glmmTMB(). With eta the conditional linear predictor of that fit and mu its mean, the working response and weights are

z=η+(y−μ)/μ′(η),w=μ′(η)2/V(μ),z = \eta + (y - \mu) / \mu'(\eta), \qquad w = \mu'(\eta)^2 / V(\mu),

the quantities of one iteratively reweighted least-squares step. The working response is treated as Gaussian with covariance V=diag(1/w)+ZGZ⊤V = \mathrm{diag}(1 / w) + Z G Z^\top, which is block-diagonal over the groups; z and the columns of x are whitened by the Cholesky factor of each block, the whitened intercept is projected out of both, and the wrapped method is run on the whitened problem, which has a Gaussian response and no random structure.

Because the linearisation is taken once, round a fit that leaves out every candidate column, the working response is accurate when the candidates move the linear predictor little and degrades as their signal grows, and penalised quasi-likelihood is known to be biased for binary responses with small clusters. Error-rate claims of the wrapped method are therefore not carried over (controls is NA).

Estimates returned by the wrapped method are on the linear-predictor scale of the original response, because whitening and projecting out the intercept leave the coefficients of the candidate columns unchanged. They are one-step estimates from the null fit, and for strong effects they lie well short of the maximum-likelihood values.

Value

An object of class fs_method, with identifier "<base id>_lift", route "working_response", families "binomial", "poisson" and "negbin", carrying "groups" and "slopes", maturity "experimental", and the base method's output, backend (with lme4 and glmmTMB added) and tuning.

References

Breslow, N. E. and Clayton, D. G. (1993). Approximate inference in generalized linear mixed models. Journal of the American Statistical Association, 88, 9-25.

Schall, R. (1991). Estimation in generalized linear models with random effects. Biometrika, 78, 719-727.

See Also

fs_select() runs the lifted method, fs_stabilise() is the other wrapper.

Examples

sim <- fs_design(n = 200L, p = 10L, n_true = 2L, r2 = 0.6,
  family = "binomial", n_groups = 20L, r2_group = 0.1, seed = 1L)
lifted <- fs_lift("forward_stepwise")
fs_select(sim, lifted, criterion = "BIC", seed = 1L)

Define a selection method

Description

Wraps a selection procedure with the declarations fs_select() reads before running it: the response families it fits, the route by which it meets random effects, the packages it needs and its tuning parameters.

Usage

fs_method(
  id,
  name,
  run,
  families = c("gaussian", "binomial", "poisson", "negbin"),
  route = c("whitened", "native", "working_response", "bayes"),
  output = c("set", "ranking", "probability", "path"),
  backend = character(0L),
  tuning = list(),
  controls = NA_character_,
  carries = character(0L),
  requires = character(0L),
  protects = FALSE,
  maturity = c("established", "experimental")
)

Arguments

id

Short identifier, unique in a benchmark.

name

Readable name of the method.

run

Function of problem and tuning, described in Details.

families

Response families the method fits, from "gaussian", "binomial", "poisson" and "negbin".

route

How the method meets random effects: "whitened", "native", "working_response" or "bayes".

output

What the method returns beyond a selected set: "set", "ranking", "probability" or "path".

backend

Character vector of packages the method needs, empty for none.

tuning

Named list of tuning parameters and their defaults.

controls

The error rate the method claims to control (for example "FDR"), or NA for none.

carries

The random structures the method fits, from "groups" (grouped intercepts), "slopes" and "relmat". Empty for none.

requires

The structures, among those in carries, that a problem must have for the method to run. Empty for none.

protects

Whether the method keeps the protected columns of a problem (see fs_problem()) in every fit, unpenalised. A method that does not declines a problem that has them.

maturity

"established" for a method with a published or maintained source, "experimental" for one the package proposes. An experimental method is never a default.

Details

run is called as run(problem, tuning), with problem an fs_problem() and tuning the named list of tuning values in force. It returns a list with

  • selected: the selected columns of problem$x, as indices;

  • scores (optional): one number per column, larger meaning more likely to be true;

  • score_type (optional): "ranking" or "probability";

  • estimates (optional): one estimated effect per column on the linear-predictor scale;

  • path (optional): the supports along the method's path, as a list of column-index vectors in the order the path visits them.

Routes, as in the package design: "native" methods fit random effects themselves; "whitened" methods run on a Gaussian response rotated by a plug-in covariance; "working_response" methods run on a linearised non-Gaussian response; "bayes" methods fit the joint model through 'flexyBayes'. On every route, a method runs on a problem with random effects only when carries names every random structure the problem has, and declines otherwise. A native method declares in carries exactly the structures its backend fits, and in requires those it cannot run without: a problem missing one of them is declined.

Value

An object of class fs_method.

See Also

fs_methods() lists the methods the package ships, fs_select() runs one.

Examples

top_two <- fs_method("top_two", "Two largest marginal correlations",
  run = function(problem, tuning) {
    r <- abs(stats::cor(problem$x, problem$y))[, 1L]
    list(selected = order(r, decreasing = TRUE)[1:2], scores = r)
  },
  output = "ranking")
sim <- fs_design(n = 100L, p = 10L, n_true = 2L, seed = 1L)
fs_select(sim$problem, top_two)

The methods shipped with the package

Description

Lists the registry: every method fs_select() and fs_benchmark() can be given by its identifier.

Usage

fs_methods(maturity = c("established", "all"))

Arguments

maturity

"established" (the default) lists the methods with a published or long-used rule; "all" adds the experimental ones, which run only when asked for by name.

Value

A data frame with one row per method and columns id, name, route, families (comma-separated), output, backend (comma-separated, empty for none), protects (whether it keeps a problem's protected columns), maturity and available (whether every backend package is installed).

See Also

fs_method() to define a method of your own.

Examples

fs_methods()

Choose among nested refits of a method's ordering

Description

Wraps a method that orders the columns (along a path or by scores) so that the stopping point is chosen by a model-selection criterion over maximum-likelihood refits, following section 2.2 of Moldovan and Taylor (2022): the ordering gives nested candidates, each candidate is refitted without penalty, and the criterion picks one.

Usage

fs_nested(
  method,
  criterion = "bic",
  alpha = NULL,
  max_size = Inf,
  cv_folds = 5L,
  gamma = 1
)

Arguments

method

An fs_method() or the identifier of a method listed by fs_methods(), returning a path or scores.

criterion

One of "bic" (the default), "aic", "ebic", "caic", "cv_min", "cv_1se", "size_stability" or "alpha_agreement".

alpha

Optional numeric vector of elastic-net mixing values in ⁠(0, 1]⁠, one base run per value. NULL runs the base method once.

max_size

Largest number of columns in a candidate.

cv_folds

Number of folds for "cv_min", "cv_1se" and "size_stability".

gamma

Weight of the model-space term of "ebic", at least 0.

Details

The ordering is the order of first entry along the base method's path when it returns one, and otherwise the order of its scores. A column that leaves the path and re-enters keeps its first entry, and each exit is counted as a step that is not nested. Columns that enter at the same step (or share a score) enter together, and the candidate adds them as one; such joint entries are counted too. A base method that returns neither a path nor scores is declined.

With alpha given, the base method is run once per mixing value (it must have an alpha tuning parameter), the candidates of all runs are pooled, a support met under several values is refitted once, and the criterion chooses across the pool.

Refits: stats::lm() or stats::glm() without random effects; lme4::lmer(REML = FALSE) or lme4::glmer() with grouped intercepts (and random slopes for the problem's slopes); glmmTMB::glmmTMB() with the nbinom2 family for a negative-binomial response. REML is never used, because REML likelihoods of models with different fixed effects are not comparable. A problem with a relationship matrix is declined. A refit that does not converge enters the curve with a missing value and is never chosen.

The first candidate is the intercept-only model (with the problem's random structure), so a design with no signal can return the empty set. Candidates stop at min(max_size, n - 1 - r) columns, with r the number of random-effect variance and covariance parameters; a problem whose cap is below zero leaves no candidate, not even the intercept-only model, and is declined.

Criteria, by maturity:

  • established: "aic"; "bic", whose sample size is the number of rows (as stats::BIC() of an lme4 fit); "ebic", the extended BIC of Chen and Chen (2008) with weight gamma on log(choose(p, k)), the choice when the number of columns is near or above the number of rows; "caic", the corrected conditional AIC of Greven and Kneib (2010) from cAIC4::cAIC(), for Gaussian, Poisson and Bernoulli responses (it refits once per observation for the last two, and is slow), equal to "aic" for a refit without random effects; "cv_min" and "cv_1se", the K-fold cross-validated deviance of the refit (folds by whole groups when the problem has groups, predictions at population level) at its minimum and under the one-standard-error rule.

  • experimental: "size_stability", the candidate of the size the BIC chooses most often across the K folds; "alpha_agreement", the support the BIC chooses under the most mixing values of alpha.

A method wrapped with an experimental criterion is experimental.

The criterion values of the refits ignore that the ordering was chosen from the same data. They choose a model; they are not a test of one.

Scores are the inverse entry rank (1 for the first entry, 1 / 2 for the second, 0 for a column that never enters), so the ordering is scored on its own. Estimates are the coefficients of the chosen refit, on the linear-predictor scale. The run also returns, under nested, the criterion curve, the chosen size, the counts of exits, joint entries and refits that did not converge, and the sample size the BIC used.

Value

An object of class fs_method, with identifier "<base id>_nested_<criterion>" and output "ranking".

References

Moldovan, M. and Taylor, J. (2022). Elastic Net (Model Selection). Wiley StatsRef: Statistics Reference Online. doi:10.1002/9781118445112.stat08369

Greven, S. and Kneib, T. (2010). On the behaviour of marginal and conditional AIC in linear mixed models. Biometrika, 97(4), 773-789.

Chen, J. and Chen, Z. (2008). Extended Bayesian information criteria for model selection with large model spaces. Biometrika, 95(3), 759-771.

See Also

fs_stabilise(), the other wrapper; fs_select() runs the wrapped method.

Examples

sim <- fs_design(n = 150L, p = 12L, n_true = 3L, r2 = 0.5, seed = 1L)
nested <- fs_nested("marginal_bh", criterion = "bic")
res <- fs_select(sim$problem, nested, seed = 1L)
res$selected

Plant a known treatment effect on kept predictors

Description

Draws an outcome, or two jointly, whose dependence on a kept treatment is known, over predictors taken as they are. The result is an fs_sim, so selectors run on it as on any other draw, and fs_effect() estimates the planted effect under a chosen adjustment.

Usage

fs_plant(
  x = NULL,
  treatment = NULL,
  effect = 0,
  shape = c("rise", "plateau", "optimum", "none"),
  groups = NULL,
  r2_group = 0,
  rho = 0,
  seed,
  regime = NULL,
  n = NULL,
  protect = TRUE
)

Arguments

x

A numeric matrix of predictors, or an fs_clone_data from fs_from_clone(), which also supplies the treatment, the groups and the complete-case set. NULL with regime.

treatment

The treatment, one value per row of x. Taken from x when it is an fs_clone_data.

effect

Planted effect in outcome standard deviations: one value for one outcome, or two for two outcomes planted jointly. Names, when given, name the outcomes.

shape

Dose-response shape, one per outcome or one for both: "rise", "plateau", "optimum" or "none". A two-valued treatment takes "rise" or "none".

groups

Optional grouping of the rows. Taken from x when it is an fs_clone_data.

r2_group

Share of the outcome variance between groups, in [0, 1).

rho

Correlation of the two outcomes' residuals. Zero for one outcome.

seed

Integer seed. The caller's random-number state is put back.

regime

An fs_regime, or the name of a preset of fs_regimes(), to draw every node of. The other arguments except n and seed are then left at their defaults.

n

Number of rows to draw from regime.

protect

With regime, whether the selection problem carries the treatment as a protected column.

Details

Outcome. For outcome kk, row ii in group gg,

yik=δkfk(ti)+bgk+eik,y_{ik} = \delta_k f_k(t_i) + b_{gk} + e_{ik},

with bgk∼N(0,r)b_{gk} \sim N(0, r) and eik∼N(0,1−r)e_{ik} \sim N(0, 1 - r), where rr is r2_group. With no treatment effect the outcome has unit variance, so effect is in outcome standard deviations. Group effects are drawn separately for each outcome, and the two residuals of a row have correlation rho. The predictors in x have no effect: the truth's support is empty, and every column is a candidate control.

Treatment. A treatment with two values plants a shift of effect from the lower value (or first level) to the other. A numeric treatment with three or more values is a dose. With uu the dose rescaled to [0, 1] over its range, shape gives

  • "rise": f(u)=uf(u) = u, a steady rise;

  • "plateau": f(u)=(1−e−5u)/(1−e−5)f(u) = (1 - e^{-5u}) / (1 - e^{-5}), a rise that levels off;

  • "optimum": f(u)=1−((u−0.6)/0.6)2f(u) = 1 - ((u - 0.6) / 0.6)^2, highest at 60% of the range;

  • "none": f(u)=0f(u) = 0.

Every shape is 0 at the lowest dose and at most 1, so effect is the largest gain over the lowest dose. A factor with more than two levels is declined: in a null clone its codes are a random permutation and carry no order.

Truth. truth$causal holds the treatment, its levels, the planted contrast of every level against the lowest for each outcome, the shapes, rho, the outcome matrix and the clone's complete-case set.

A generated regime. With regime, from fs_regime() or a preset name, and x and treatment left NULL, every node of the regime is drawn in causal order: the treatment is a generated node here, the one case in which it is drawn. The observed nodes other than the treatment and the outcome become the columns of x, the candidate controls. The truth's support is the controls with an edge into the outcome, with their coefficients as beta, so selectors and fs_score() run as on any draw. truth$causal holds the continuous treatment, the estimand and its value as the planted "slope", the regime, the role table, the first valid adjustment set (or NULL) and any node on which the sample is selected. With a selection, rows are drawn until n of them have the node within the band the regime states, and that node is always adjusted for by fs_effect().

The treatment in the selection problem. By default the problem of a regime draw carries the treatment as a protected column (see fs_problem()), so a selector chooses controls with the treatment in every fit, as post-double-selection, the outcome-adaptive lasso and the other causal selectors do. A pure instrument is then independent of the outcome given the treatment and is dropped. Methods that cannot keep a protected column decline. With protect = FALSE the treatment is left out and every method runs, choosing controls that predict the outcome over the treatment, instruments included.

Value

An object of class fs_sim whose problem holds the first outcome, and whose truth carries causal as described in Details.

See Also

fs_effect() estimates the planted effect, and fs_effect_ademp() summarises the estimates over replicates.

Examples

x <- matrix(stats::rnorm(400L), ncol = 2L)
dose <- rep(c(0, 40, 80, 120), each = 50L)
sim <- fs_plant(x, dose, effect = c(yield = 0.5, protein = 0.3),
  shape = c("optimum", "rise"), rho = -0.4, seed = 1L)
sim$truth$causal$contrast

Define a selection problem

Description

Collects the response, the candidate predictors and the grouping of a variable-selection problem into one object that every selector and scorer in the package reads.

Usage

fs_problem(
  y,
  x,
  family = c("gaussian", "binomial", "poisson", "negbin"),
  groups = NULL,
  block = NULL,
  slopes = NULL,
  relmat = NULL,
  protect = NULL
)

Arguments

y

Numeric response, one value per row of x. Binomial responses are coded 0 and 1, and count responses are non-negative integers.

x

Numeric matrix of candidate predictors, one column per predictor. Column names are used as predictor names, and x1, x2, ... are supplied when there are none.

family

Response family: "gaussian", "binomial", "poisson" or "negbin".

groups

Optional factor of length nrow(x) naming the unit each row belongs to, for a grouped random intercept. NULL for none.

block

Optional integer vector of length ncol(x) assigning each predictor to a correlated block. NULL puts every predictor in its own block.

slopes

Optional character vector of column names of x whose slopes vary across groups. NULL for none.

relmat

Optional relationship structure for a background random effect: an nrow(x) by nrow(x) symmetric matrix, or "linear" for the cross-product of the centred columns of x. NULL for none.

protect

Optional numeric matrix of columns that every fit keeps, unpenalised, beside the candidates: for example the treatment of a causal problem, whose effect is estimated after selecting its controls. One row per row of x, named columns whose names are not those of x. Protected columns are never candidates, so selections, scores and estimates index x alone. A method that cannot keep them declines the problem with the reason code "selection_method_cannot_protect". NULL for none.

Value

An object of class fs_problem: a list with elements y, x, family, groups, slopes, relmat, protect and meta, a data frame with one row per predictor (name, block).

See Also

fs_design() simulates a problem together with its truth.

Examples

x <- matrix(stats::rnorm(200L), nrow = 50L)
y <- x[, 1L] + stats::rnorm(50L)
fs_problem(y, x)

A causal regime: a linear structural model on a graph

Description

Reads a directed acyclic graph and a standardised path coefficient for each edge, and returns the regime's population answers: the causal estimand, whether it is identified by adjustment, and the coefficient of the treatment under any set of controls. fs_plant() draws data from a regime, and fs_score() with by = "role" scores selections against its causal roles.

Usage

fs_regime(
  dag,
  coef = NULL,
  treatment = "X",
  outcome = "Y",
  estimand = c("total", "direct"),
  roles = NULL,
  ...
)

Arguments

dag

A dagitty graph, as a string or a dagitty object, with its unobserved nodes marked ⁠[latent]⁠; or the name of a preset.

coef

A named numeric vector of path coefficients, one per edge, named "A->B". With a preset, the coefficients to replace.

treatment, outcome

Names of the treatment and outcome nodes.

estimand

"total" or "direct". A preset brings its own when this is not given.

roles

Optional named character vector: the causal role of each observed node, from "confounder", "outcome_cause", "instrument", "mediator", "mediator_descendant", "collider", "butterfly", "outcome_descendant", "post_treatment", "selection_blocker", "selection" and "spurious".

...

Parameters of the preset "hahn_ric".

Details

Model. Every node is a linear combination of its parents plus normal noise, with the noise variance set so that the node has variance 1. A coefficient is therefore a standardised path coefficient, and the covariance of two nodes is the sum of the products of the coefficients along the paths that join them (Wright's rules), which is the algebra Cinelli et al. (2024) use. A node whose parents would explain a variance of 1 or more has no such scaling, and the regime is declined.

Answers. With BB the matrix of coefficients (row the parent, column the child), the total effect is the treatment-outcome entry of (I−B)−1(I - B)^{-1} and the direct effect is the treatment-outcome entry of BB. The population coefficient of the treatment given a set SS is the first entry of ΣAA−1ΣAY\Sigma_{AA}^{-1} \Sigma_{AY}, with AA the treatment followed by SS and Σ\Sigma the implied covariance. The estimand is identified when dagitty::adjustmentSets() returns a set; sets holds them all.

Roles. Each observed node other than the treatment and the outcome carries a causal role, and each role a verdict under two label sets: "disjunctive", which drops an instrument as the modified disjunctive cause criterion does (VanderWeele 2019), and "hahn", which keeps it among the confounders (Hahn et al. 2018). A mediator is dropped for the total effect and kept for the direct effect. The roles of a preset are those of its source. For a graph of your own, give them in roles; nodes left out are "unlabelled".

Presets. dag may name a preset; fs_regimes() lists them with their sources, verdicts and default coefficients. Every edge into the treatment or the outcome defaults to 0.5 and every other edge to 0.4. Taking the nodes in causal order, a node whose parents would explain 0.8 of its variance or more has its incoming coefficients scaled down together until they explain 0.75. coef may replace some or all of a preset's coefficients. The preset "hahn_ric" is built from the parameters rho2, kappa2, phi2, k, p and seed, passed in ... (Hahn et al. 2018, section 3.2).

Value

An object of class fs_regime: a list holding the graph, the nodes in causal order, the coefficient matrix B, the residual variances, the implied covariance sigma, the estimand and its value effect, identified, the adjustment sets sets, the role table roles, and, for a preset, its name, source, verdict, the control the verdict is about and any selection on a node.

References

Cinelli, C., Forney, A., & Pearl, J. (2024). A crash course in good and bad controls. Sociological Methods & Research, 53(3), 1071–1104. doi:10.1177/00491241221099552

Ding, P., & Miratrix, L. W. (2015). To adjust or not to adjust? Sensitivity analysis of M-bias and butterfly-bias. Journal of Causal Inference, 3(1), 41–57. doi:10.1515/jci-2013-0021

Hahn, P. R., Carvalho, C. M., Puelz, D., & He, J. (2018). Regularization and confounding in linear regression for treatment effect estimation. Bayesian Analysis, 13(1), 163–182. doi:10.1214/16-BA1044

Pearl, J. (2010). On a class of bias-amplifying variables that endanger effect estimates. In Proceedings of the Twenty-Sixth Conference on Uncertainty in Artificial Intelligence (pp. 417–424). AUAI Press. https://arxiv.org/abs/1203.3503

VanderWeele, T. J. (2010). Bias formulas for sensitivity analysis for direct and indirect effects. Epidemiology, 21(4), 540–551. doi:10.1097/EDE.0b013e3181df191c

VanderWeele, T. J. (2019). Principles of confounder selection. European Journal of Epidemiology, 34(3), 211–219. doi:10.1007/s10654-019-00494-6

See Also

fs_regimes() for the presets, fs_plant() to draw from a regime.

Examples

if (requireNamespace("dagitty", quietly = TRUE)) {
  r <- fs_regime("cinelli_7")
  r$effect
  r$identified
  r$roles
}

The preset causal regimes

Description

Lists the 27 presets fs_regime() accepts by name: the 18 models and two variations of Cinelli, Forney and Pearl (2024), and the cells of Pearl (2010), Ding and Miratrix (2015), VanderWeele (2010), Hahn et al. (2018) and Brookhart et al. (2006), with their sources, verdicts and default coefficients.

Usage

fs_regimes()

Details

verdict is the source's verdict on adjusting for control: "good", "bad", "neutral", or "undecidable" where no adjustment set exists. select names a node on which the sample is selected, with the value and the half-width of the band kept around it. The default coefficients follow the rule in fs_regime(); "hahn_ric" lists its parameters instead.

Value

A data frame with one row per preset: name, source, estimand, control, verdict, select and coef.

Examples

fs_regimes()[, c("name", "verdict", "control")]

Run a simulation study

Description

Runs the plan of an fs_study(): draws the replicates of every mechanism, runs every selector and reference adjustment set on them, and returns one status row per mechanism, arm and replicate, the estimates, and their performance with Monte Carlo standard errors.

Usage

fs_run(study, dir = NULL)

Arguments

study

An fs_study.

dir

NULL (the default) to keep the run in memory only, or the path of a directory for the checkpoints, created if absent.

Details

Arms. The selectors are run by fs_benchmark(), one method at a time, each under its own seed derived from the mechanism's stream and the method id, so adding or removing a method leaves every other method's numbers as they were. The replicates' data come from the replicate sub-streams and are the same for every arm.

Target "support". Each mechanism's benchmark is laid out by fs_ademp(); performance holds its measures with a mechanism column.

Target "effect". Each replicate's treatment effect is estimated by fs_effect() after adjusting for the selected columns, or for the reference set: "none", "all", "valid", or "optimal", the optimal valid set of fs_adjustment(). Performance is that of fs_effect_ademp() over the replicates that gave an estimate. For a regime, roles holds the share of each causal role each selector kept, from fs_score(by = "role").

Status. A row is "selected" (an estimate or a selection was made), "declined" (with the reason code of the typed refusal), "failed" (with the error's message) or "generator_flag". Declined and failed replicates stay in the table and are counted in cells, so a measure over fewer replicates than were run shows as such.

Generator check. In a regime, each reference set's bias and SE are known exactly before the run (study$known). When the simulated bias or empirical SE differs from its exact value by more than four Monte Carlo SEs (Morris et al. 2019, Table 6, with the exact SE in place of the empirical one), the reference's rows in that mechanism take the status "generator_flag" and checks shows the gap: the generator, not the selectors, is then the first suspect.

Cost of the choice. In a regime, rmse_known is the population RMSE of the sets an arm adjusted for: for a reference its exact value, and for a selector br2+vr‾\sqrt{\overline{b_r^2 + v_r}} over its replicates, with brb_r and vrv_r the exact bias and finite-sample variance of the set chosen in replicate rr. Were each chosen set fixed in advance, the simulated RMSE would equal it; rmse - rmse_known is what estimating after selecting on the same data costs.

Checkpoints. With dir, the run writes the study to plan.rds and each finished mechanism to ⁠mechanism_<k>.rds⁠ in that directory, each file written under a temporary name and then renamed, so a file present is a whole one. Run again with the same study and directory, it reads the mechanisms already written and runs only the rest; every mechanism draws from its own stream, so the result equals that of an uninterrupted run except for runtime. A directory holding the files of another plan (another hash), or files of its own that are not those of a run, is refused. For a method of your own, values its run function finds in its enclosing environment are not in the hash: change them and resume, and the mechanisms already written keep the old values.

Value

An object of class fs_run: a list with hash (the plan's), study, status (one row per mechanism, arm and replicate: mechanism, arm, kind, replicate, status, reason_code, message, n_selected), estimates (target "effect": the rows of fs_effect() with mechanism, arm and replicate), cells (counts per mechanism and arm), performance, roles and checks (NULL where they do not apply), and runtime in seconds.

References

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. doi:10.1002/sim.8086

See Also

fs_study() for the plan; fs_benchmark(), fs_effect() and fs_ademp() for the engine it routes to.

Examples

if (requireNamespace("dagitty", quietly = TRUE)) {
  study <- fs_study(
    aims = "Does a near-instrument cost the selectors precision?",
    data = fs_grid("near_instrument", n = 200L, protect = c(TRUE, FALSE)),
    methods = "forward_stepwise",
    references = c("none", "optimal"),
    target = "effect",
    n_sim = 10L,
    seed = 20261203L
  )
  run <- fs_run(study)
  run
  summary(run)

  # With checkpoints: a second call reads the finished mechanisms.
  dir <- file.path(tempdir(), "near_instrument_run")
  run <- fs_run(study, dir = dir)
  identical(run$status, fs_run(study, dir = dir)$status)
  unlink(dir, recursive = TRUE)
}

Score selections against a known truth

Description

Counts true and false positives of a selection under a stated definition of a true positive, with rates, ranking and effect metrics, and summarises replicate simulations with Monte Carlo standard errors.

Usage

fs_score(
  sim,
  selected,
  scores = NULL,
  score_type = c("ranking", "probability"),
  estimates = NULL,
  pairs = NULL,
  truth_def = NULL,
  window = 1L,
  threshold = 0.5,
  proxy_rule = c("causal", "predictive"),
  by = c("truth", "role")
)

Arguments

sim

An fs_sim from fs_design(), or a list of them.

selected

The selected columns of one simulation, as indices, names or a logical vector over the columns. A list of these when sim is a list.

scores

Optional numeric score per column, larger meaning more likely to be true. A list when sim is a list.

score_type

"ranking" or "probability" (scores in [0, 1]).

estimates

Optional estimated main effects, one per column, on the linear-predictor scale. A list when sim is a list.

pairs

Optional two-column matrix of selected pairs, as indices or names. A list when sim is a list.

truth_def

One or more of "exact", "window", "correlation" and "cluster", or NULL for the default described in Details.

window

Distance in columns for "window".

threshold

Absolute correlation for "correlation".

proxy_rule

One or more of "causal", "predictive" and "excluded", used when a simulation holds a hidden confounder.

by

"truth" to score against the truth's support, or "role" to score against the causal roles of a regime.

Details

Definitions of a true positive. Each true predictor has a neighbourhood: itself ("exact"), the columns within window positions of it ("window"), the columns whose absolute sample correlation with it is at least threshold ("correlation"), or the columns of its block ("cluster"). A selected column is a true positive when it lies in the neighbourhood of some true predictor, and a true predictor is found when its neighbourhood holds a selected column. The true-positive rate is the share of true predictors found. The false-discovery proportion is the share of selected columns that are not true positives, and is 0 when nothing is selected. Wider definitions forgive a selector that picks a correlated neighbour, and reporting several shows how much of a score rests on that forgiveness. When truth_def is NULL, "exact" is reported, with "correlation" added when the design's predictors are correlated.

Columns of a weak tail (see fs_design()) are left out of every count: selecting one is neither a true nor a false positive.

A hidden confounder. When fs_implant() planted a confounder U, its proxies are columns with no effect of their own that are associated with the outcome through U. proxy_rule states how a selected proxy counts: under "causal" it is a false positive; under "predictive" U is one more true predictor, found when any proxy is selected, and every selected proxy is a true positive; under "excluded" the proxies are left out of every count, as a weak tail is. The table then has one row per definition and rule, with the column proxy_rule, and proxy_rate, the share of selected columns that are proxies (0 when nothing is selected). The gap between the causal and the predictive rows is how far a selector is right for prediction and wrong for explanation. Without a confounder in any simulation, neither column appears.

Metrics. The counts are n_selected, tp, fp and fn (true predictors not found). The rates are tpr, fdp, precision (missing when nothing is selected) and f1. The Matthews correlation mcc is given under "exact" only, since the other definitions do not partition the columns. With scores, the average precision auprc of the ranking against the exact support, and with score_type = "probability" the Brier score brier. With estimates, l2_error, the squared distance to the true main effects on the linear-predictor scale, over the columns with a linear effect (shaped columns have no single coefficient). nonlinear_tpr is the share of shaped true columns found, missing when none was planted. With interacting pairs in the truth, member_tpr, the share of true pairs whose two members are both selected. With pairs as well, pair_tpr and pair_fdp score the selected pairs. auprc, brier and l2_error do not depend on truth_def and are reported under "exact" only.

By causal role. With by = "role", each simulation must be drawn from a regime (see fs_regime() and fs_plant()), and the selection is scored against the causal role of each candidate control instead of the truth's support. For each label set ("disjunctive" and "hahn") and role, kept is the share of that role's columns the selection holds. Beside it, for each replicate, fdp is the nominal false-discovery proportion against truth$support (the controls with an edge into the outcome), and harmful is the number of selected columns whose role is dropped under the label set. A knockoff or stability selection can control the first while scoring badly on the second, since a collider or mediator depends on the outcome given the others. The cost of each replicate's choice is exact: bias is the population bias of the treatment's coefficient when the selected set is adjusted for, and var_ratio its asymptotic variance over that of the optimal valid set (see fs_adjustment()), NA when the regime has none. A selected instrument shows as a var_ratio above 1 with no bias when every confounder is observed, and as bias when one is hidden. The result is an fs_role_score: table holds one row per replicate, label set and role, errors one row per replicate and label set, cost one row per replicate, and summary the mean, Monte Carlo SE and count of each, as below.

Replicates. Given lists, each simulation is scored with its own selection. The summary holds, for every definition and metric, the mean over the replicates where it is defined, its Monte Carlo standard error (the standard deviation over those replicates divided by the square root of their number) and that number.

Value

An object of class fs_score: a list with table, one row per replicate and definition with the metrics as columns, and summary, one row per definition and metric with mean, mcse and n. With by = "role", an fs_role_score as described in Details.

References

Morris, T. P., White, I. R. and Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. doi:10.1002/sim.8086

See Also

fs_design() for the simulations, fs_stability() for the agreement of selections across resamples.

Examples

sim <- fs_design(n = 200L, p = 30L, predictors = "block", rho = 0.6,
  n_true = 3L, r2 = 0.5, seed = 1L)
fit <- stats::lm(sim$problem$y ~ sim$problem$x)
pval <- summary(fit)$coefficients[-1L, 4L]
fs_score(sim, which(pval < 0.01), scores = -log(pval))

Run a selection method on a problem

Description

Runs one method on one fs_problem() and returns what it selected, or a typed decline when the method's declarations rule the problem out.

Usage

fs_select(problem, method, ..., seed = NULL)

Arguments

problem

An fs_problem(), or an fs_sim whose problem is used.

method

An fs_method(), or the identifier of a method listed by fs_methods().

...

Tuning values that replace the method's defaults, named as in its tuning list.

seed

Optional integer seed. When given, the method runs under it and the caller's random-number state is put back afterwards.

Details

Before running, the method is declined when the problem's family is not among its families, when a backend package is not installed, or when the problem has a random structure that the method neither fits on the native route nor names in carries, or lacks a structure the method names in requires. A refusal the method raises while running (a condition of class flexybayes_refusal) is a decline as well. A decline is returned as an fs_result with status "declined", the registered reason code and the refusal condition. Any other error inside the method is not caught here; fs_benchmark() records it as a status row.

Value

An object of class fs_result: a list with method (its id), status ("selected" or "declined"), selected (column indices), scores, score_type, estimates, converged (FALSE when the method's backend reports that its fit did not converge, which leaves the status "selected"; NA when the backend does not report it), reason_code, message, condition (the refusal condition of a decline), runtime in seconds provenance (the tuning in force, the seed and the versions of the backend packages), path (the method's ordered candidate sets, NULL when it returns none), nested (the criterion curve and its counts for a method wrapped by fs_nested(), NULL otherwise) and terms (the column names of the problem's x, which selected indexes).

See Also

fs_benchmark() runs methods over many simulations.

Examples

sim <- fs_design(n = 200L, p = 20L, n_true = 3L, r2 = 0.5, seed = 1L)
fs_select(sim, "marginal_bh", q = 0.05)

Stability selection round a selection method

Description

Wraps a method in complementary-pairs stability selection (Shah and Samworth 2013): the method is run on both halves of B random splits of the data, and a column is selected when the share of the 2 * B halves that selected it reaches cutoff.

Usage

fs_stabilise(method, B = 50L, cutoff = 0.75)

Arguments

method

An fs_method() or the identifier of a method listed by fs_methods().

B

Number of complementary pairs of halves.

cutoff

Selection probability at or above which a column is selected, in ⁠[0, 1]⁠.

Details

Each half holds floor(n / 2) rows. When the problem has groups, the halves are drawn by whole groups instead, each holding floor(G / 2) of the G groups, and a relationship matrix is cut to the rows of the half.

The wrapped method keeps the base method's families, route, backend and the random structures it carries, so fs_select() declines it where it would decline the base. Its tuning is the base method's tuning together with B and cutoff, and tuning given to fs_select() reaches the base method on every half.

The scores are the selection probabilities, on the grid 0, ⁠1 / (2B)⁠, ..., 1. For cutoff above one half, Theorem 1 of Shah and Samworth (2013) bounds the expected number of selected columns whose selection probability under the base method on half the data is at most theta by theta / (2 * cutoff - 1) times the expected number of such columns the base method selects on half the data.

Value

An object of class fs_method, with identifier "<base id>_cpss" and output "probability".

References

Shah, R. D. and Samworth, R. J. (2013). Variable selection with error control: another look at stability selection. Journal of the Royal Statistical Society B, 75(1), 55-80. doi:10.1111/j.1467-9868.2011.01034.x

See Also

fs_select() runs the wrapped method, fs_stability() measures agreement between selections.

Examples

sim <- fs_design(n = 120L, p = 15L, n_true = 3L, r2 = 0.5, seed = 1L)
stable <- fs_stabilise("marginal_bh", B = 20L)
res <- fs_select(sim$problem, stable, seed = 1L)
res$selected
round(res$scores, 2)

Stability of selections across resamples

Description

The stability estimator of Nogueira, Sechidis and Brown (2018), which is 1 when every resample selects the same columns and near 0 for selections no more alike than random sets of the same sizes.

Usage

fs_stability(selected, p)

Arguments

selected

A list of at least two selections, each as column indices or a logical vector of length p.

p

Number of candidate columns.

Details

With MM selections over dd columns, p^f\hat p_f the share of selections holding column ff, sf2=M/(M−1)p^f(1−p^f)s^2_f = M / (M - 1) \hat p_f (1 - \hat p_f) and kˉ\bar k the mean selection size, the estimate is

Φ^=1−d−1∑fsf2(kˉ/d)(1−kˉ/d).\hat\Phi = 1 - \frac{d^{-1} \sum_f s^2_f}{(\bar k / d)(1 - \bar k / d)}.

It is missing when every selection is empty or every selection holds every column.

Value

A single number.

References

Nogueira, S., Sechidis, K. and Brown, G. (2018). On the stability of feature selection algorithms. Journal of Machine Learning Research, 18, 1–54. https://jmlr.org/papers/v18/17-514.html

Examples

fs_stability(list(c(1, 2, 3), c(1, 2, 4), c(1, 2, 3)), p = 10L)

State a simulation study before it runs

Description

Writes the plan of a simulation study over one or more grids of mechanisms: its aims, the methods and reference adjustment sets to compare, the target scored, the number of replicates and the seed. The plan prints what the study will do, and for causal regimes what is known before anything runs.

Usage

fs_study(
  aims,
  data,
  methods = character(0L),
  references = NULL,
  target = c("support", "effect"),
  n_sim = NULL,
  mcse = NULL,
  seed
)

Arguments

aims

One sentence: the question the study answers.

data

An fs_grid, or a list of them. Mechanism labels must be unique across the grids.

methods

Ids of registered methods, from fs_methods()$id, an fs_method(), or a list mixing the two.

references

NULL for the default, or a subset of "none", "valid", "all" and "optimal".

target

"support" or "effect".

n_sim

Replicates per mechanism, a whole number of at least 2.

mcse

The largest bias MCSE to plan for, in place of n_sim.

seed

One whole number.

Details

Target. "support" scores the selected predictors against the planted support. "effect" estimates the treatment effect after selection and needs mechanisms with a planted treatment: regimes, or fs_plant.

References. Fixed adjustment sets estimated beside the selectors, for the target "effect" only: "none", "all" (every candidate), "valid" (the first adjustment set of dagitty::adjustmentSets()) and "optimal" (the optimal valid set of Henckel, Perkovic and Maathuis 2022). The last two need regimes. By default all four for regimes, and "none" and "all" otherwise.

Known now. For a regime, fs_adjustment() gives the exact bias and finite-sample standard error of each reference set at the mechanism's n. They are in known, so the run spends its compute on what the selectors do.

Replicates. Give n_sim, or mcse where every mechanism is a regime estimating its effect. The Monte Carlo standard error of a bias is V/nsim\sqrt{V / n_{sim}} (Morris et al. 2019, Table 6), so mcse sets nsim=⌈V/mcse2⌉n_{sim} = \lceil V / \mathrm{mcse}^2 \rceil per mechanism, with VV the largest exact variance of any fixed adjustment set at that n. With n_sim given, the plan prints the bias MCSE it implies for every fixed set. A selector's variance can exceed every fixed set's.

Seeds. seed starts an L'Ecuyer-CMRG generator. Mechanism kk takes the kk-th stream (parallel::nextRNGStream()), and replicate rr its rr-th sub-stream, so a replicate's data do not depend on the methods or on the other mechanisms' replicate counts. The caller's generator and its state are left as they were.

Your own methods. methods takes fs_method() objects beside the ids of registered methods, so a selector from another package, wrapped in one call, runs in a study like the registered ones. Its id must differ from every registered id. Its declarations and the code of its run function enter the plan hash; values its function finds in its enclosing environment do not.

Hash. The md5 of a canonical text form of the plan (its fields sorted, every number written to 17 significant digits). The same plan gives the same hash in any session.

Value

An object of class fs_study: a list with aims, mechanisms, methods (the method ids), user_methods (the fs_method() objects given, by id, or NULL), references, target, n_sim (one count per mechanism), mcse, seed, streams (one generator state per mechanism), variance (the largest exact variance of a fixed set per mechanism, NA where none is known), known (a data frame, or NULL), hash and version.

References

Morris, T. P., White, I. R., & Crowther, M. J. (2019). Using simulation studies to evaluate statistical methods. Statistics in Medicine, 38(11), 2074–2102. doi:10.1002/sim.8086

Henckel, L., Perkovic, E., & Maathuis, M. H. (2022). Graphical criteria for efficient total effect estimation via adjustment in causal linear models. Journal of the Royal Statistical Society Series B: Statistical Methodology, 84(2), 579–599. doi:10.1111/rssb.12451

See Also

fs_grid() for the mechanisms, fs_adjustment() for the costs known now.

Examples

if (requireNamespace("dagitty", quietly = TRUE)) {
  study <- fs_study(
    aims = "When does adjusting for a near-instrument pay?",
    data = fs_grid("near_instrument", n = c(100L, 500L),
      "Z->Y" = c(0, 0.1)),
    methods = c("marginal_bh", "forward_stepwise"),
    target = "effect",
    mcse = 0.01,
    seed = 20261201L
  )
  study
  study$known
}

Acceptance layer 3: transfer of selector rankings from real data to a clone

Description

Computes, for each selector of a panel, five quantities that are observable on real data without knowing the truth, once on the real data and once on the clone, and measures how far the selectors' rankings on each quantity agree.

Usage

fs_transfer(
  real,
  clone,
  methods,
  seed,
  n_halves = 4L,
  n_folds = 5L,
  level = 0.05,
  n_null = 0L
)

Arguments

real

The real data: an fs_problem() or an fs_sim with a Gaussian response, or the observables already computed for it by this function (its observables$real).

clone

The clone, in the same form and with the same columns.

methods

A list of fs_method() objects or registry identifiers, or a character vector of identifiers: the panel. At least three.

seed

Integer seed for folds, half-samples, decoys and the selectors' runs. The caller's random-number state is put back.

n_halves

Number of half-samples for stability. At least two.

n_folds

Number of folds for cv_deviance. At least two.

level

The level α\alpha of the threshold.

n_null

Number of half-splits of the real data for the threshold. Zero for no threshold.

Details

The quantities, one value per selector:

  • cv_deviance: the mean squared error of prediction over n_folds held-out folds, each predicted from a least-squares refit on the columns the selector chose on the other folds (the intercept alone when it chose none);

  • stability: the stability of fs_stability() over the selections on n_halves random half-samples of the rows;

  • model_size: the number of columns selected on all the rows;

  • agreement: the mean Jaccard index between the selector's selection on all the rows and each other selector's;

  • decoy_fd: the number of decoys selected when as many decoy columns as real ones are appended by fs_implant() with mode = "decoys".

Folds, half-samples and decoys are drawn from seed, the same for every selector, and the same for the real data and the clone when they have the same number of rows. A run that declines or fails leaves the value missing, and the column failed counts such runs.

For each quantity, Kendall's tau between the selectors' values on the real data and on the clone is 1−2K1 - 2K, with KK the normalised Kendall distance of Stolte et al. (2025): the share of pairs of selectors ordered differently on the two sides, a pair tied on one side only counting one half and a pair tied on both sides counting as ordered alike. Selectors with a missing value on either side are left out of that quantity, and tau is missing when fewer than three remain or when every remaining value on one side is tied. The summary distance is d=1−τˉd = 1 - \bar\tau, the mean over the quantities with a tau: 0 when every ranking transfers, about 1 when rankings on the clone are unrelated to those on the real data, 2 when every one is reversed.

With n_null above zero, the threshold for dd is the 1−α1 - \alpha quantile of dd over n_null random splits of the real data into two halves (by whole groups when it has groups) compared with each other, fixed before the clone is seen, as the thresholds of fs_accept() are. The halves hold half the rows of the comparison between real data and clone, so the threshold carries the noise of the smaller samples.

Value

An object of class fs_transfer: a list with table (one row per quantity: observable, tau, n_methods), d, threshold and pass (missing when n_null is zero), null (the draws of dd over the half-splits), observables (a list with real and clone, each a data frame with one row per selector and quantity: method, observable, value, failed), level and n_null.

References

Nogueira, S., Sechidis, K. and Brown, G. (2018). On the stability of feature selection algorithms. Journal of Machine Learning Research, 18, 1–54. https://jmlr.org/papers/v18/17-514.html

Stolte, M., Schreck, N., Slynko, A., Saadati, M., Benner, A., Rahnenführer, J. and Bommert, A. (2025). Simulation study to evaluate when plasmode simulation is superior to parametric simulation in comparing classification methods on high-dimensional data. PLOS ONE, 20(6), e0322887. doi:10.1371/journal.pone.0322887

See Also

fs_accept() for layers 1 and 2.

Examples

real <- fs_design(n = 120L, p = 10L, n_true = 3L, r2 = 0.5, seed = 1L)
clone <- fs_design(n = 120L, p = 10L, n_true = 3L, r2 = 0.5, seed = 2L)
fs_transfer(real, clone, c("lasso", "forward_stepwise", "marginal_bh"),
  seed = 1L)

Glance at a selection

Description

One row: the four axes, the out-of-fold increment, the penalised path's tuning report and, where refit = list(method = "bayes") ran, the valuation of the refitted supports.

Usage

## S3 method for class 'fb_select'
glance(x, against = NULL, ...)

Arguments

x

An fb_select object.

against

NULL, or a second fb_select object to difference the valuation against.

...

Ignored.

Details

The out-of-fold scores are losses, so lower is better. loss names the loss: neg_elpd, minus the log predictive density summed over a held-out unit's rows (the Bayesian workflow's default), or nlpd (per row), rmse or mse. loss_protected_only and loss_full are that loss averaged over the n_units held-out units, for the protected model alone and with the candidates added, and loss_reduction is loss_protected_only - loss_full, positive when the candidates improve prediction.

value_elpd is the held-out log predictive density summed over the held-out units, and value_elpd_se its standard error across units; value_formula states both. block_share_median, block_share_lower and block_share_upper are the posterior median and 95% interval of the share of between-trial variance the declared block explains, pooled over folds.

With ablation = TRUE, ablation_blocks counts the blocks whose ablation ran, ablation_metric is the loss they were scored at, ablation_nested is FALSE (see "Grouped ablation" in fb_select()) and ablation_contract_hash identifies the contract every path shares; each block's difference is in tidy(x, level = "group").

With against, a second valuation on the same value contract (the same data, resamples, seed and prediction), value_difference is the sum over units of the paired differences elpd_u(x) - elpd_u(against), and value_difference_se is sqrt(U) times their standard deviation over the U units. Valuations on different contracts refuse with selection_value_contract_mismatch.

Value

A one-row data.frame.


Displays for a selection

Description

Displays for a selection

Usage

## S3 method for class 'fb_select'
plot(
  x,
  type = c("elpd_by_size", "rank_stability", "shrinkage", "benchmark", "entrance_path",
    "entrance_heatmap", "loss_surface"),
  ...
)

Arguments

x

An fb_select object.

type

"elpd_by_size", "rank_stability", "shrinkage", "benchmark", "entrance_path", "entrance_heatmap" or "loss_surface". "entrance_path" plots the common out-of-fold loss against s = lambda / lambda_max on a logarithmic axis and labels each candidate at its median first entry, tidy(x)$entry_s_median: the point on s by which at least half of the folds that could estimate it had admitted it. A candidate admitted on fewer than half of those folds is not labelled, candidates entering at the same point share one label, and labels on neighbouring points alternate above and below the curve. The ordinate is the mean over scoring units of each unit's score, not an inclusion probability. "entrance_heatmap" draws one row per candidate (level = "column") or declared group (level = "group") and one column per point of the grid. With source = "folds" (the default) a cell is the share of the folds able to estimate the row whose solution holds it there, and a marker sits at the row's median entry; with source = "stability" a cell is the share of the stability subsamples that hold it, and a stable row is starred. Both displays are available for optimiser workflows and optimiser benchmark arms whose penalty has a finite null anchor, which excludes ridge() and exclusive_lasso().

"loss_surface" draws, with plotly, the out-of-fold loss of the entrance path over s and the elastic-net mixing parameter alpha. One fb_select() call walks one mixing value, so the surface is built from x and the results passed as alongside, one per further mixing value, run with the same base, candidates, resamples, seed and decision. They are drawn together only when they share one score contract (the same assignment of units to folds, response, design, metric and scoring unit), one grid on s, one decision rule, one set of penalised columns and one covariance source; otherwise the display refuses with selection_loss_surface_undefined. Each cell is the loss the path stored at that point. The diamond is the point x selected, and each other result's selected point is an open circle at its own alpha; the display compares the mixing values and chooses none of them. Without plotly it refuses with loss_surface_requires_plotly.

...

Passed to the underlying plotting call. The entrance heat map also takes level, source, max_rows (default 40) and label_cex; the loss surface takes alongside, a list of fb_select objects at the other mixing values.

Value

Invisibly, the data the display was drawn from. For "loss_surface", the plotly widget, returned visibly and carrying the values it was drawn from as its values attribute: surface (one row per mixing value and grid point), chosen (each result's selected point, primary marking the one of x), metric, scoring_unit and contract_hash. Called for the plot it draws.


Tidy a selection into one row per candidate coefficient

Description

Tidy a selection into one row per candidate coefficient

Usage

## S3 method for class 'fb_select'
tidy(x, level = c("column", "group"), ...)

Arguments

x

An fb_select object.

level

"column" (the default), one row per design column, or "group", one row per declared group of penalised columns.

...

Ignored. Where refit = list(method = "bayes") refitted each fold's frozen support, value_folds_in_support counts the folds whose refit held the column, and value_in_block says whether its term is in the block the block share is stated for.

Details

Retention is read at the vocabulary the decision actually chose in. A projection, a full decision and an optimiser support all choose FORMULA TERMS – f, x1:f – while the design carries contrast columns – fB, x1:fB. Matching a chosen term against a column name reports every factor and interaction column as dropped however the decision went, so the term recorded on the column map is what the match is made against. A posterior threshold is the one decision that chooses coefficient by coefficient, and its retention is matched on the column.

Where a penalised optimiser ran – as the workflow, or as the glmnet arm of benchmark = TRUE – each row also carries what that path did with the column over its lambda grid, on the coordinate the grid was built on: s = lambda / lambda_max, with each fold's lambda_max read on its own training rows. folds_available counts the folds whose training rows identified the column at all, which is a different statement from the folds that never held it: a column a fold could not estimate was never on that fold's path. path_entry_s is the largest s at which any fold holds the column and path_exit_s the smallest s at which a fold that held it has let it go, so a column retained across the whole path has an entry and no exit. path_reentries is the largest number of returns in any one fold. Those summaries are taken from the attribute support_path_by_fold, one row per fold and column, and the membership at every point of every fold is the attribute support_path.

path_entry_s is the earliest entry on any fold. The typical entry is entry_s_median: the point on s by which at least half of the folds that could estimate the column had admitted it, where a fold that never admitted it counts against it, and NA when fewer than half did. This is the point plot(x, type = "entrance_path") labels and plot(x, type = "entrance_heatmap") marks. entry_s_q25 and entry_s_q75 are the same rule at a quarter and at three quarters of the folds, so read along the path entry_s_q25 is the larger s, and entry_s_iqr is their difference.

level = "group" returns the same profile for each declared group of penalised columns, a group entering on a fold where any member does: the grouping of a grouped penalty (the model term under group = "term", the specification under group = "block"), and otherwise the penalty specification that claimed the column, named block_1, block_2, ... in the order the specifications were written.

With ablation = TRUE, each group row also carries ablation_loss_difference, the mean over held-out units of the unit's loss with the group dropped minus its loss under the full path, its standard error ablation_loss_se and ablation_n_units; with the Bayesian refit as well, ablation_elpd_difference and ablation_elpd_se. They are NA where no ablation ran or the group's ablation was refused.

Where fb_decision() asked for subsample stability, each row also carries stability_available, the subsamples that could estimate it, stability_max_frequency, its largest selection frequency at or above the chosen tuning point, and stability_selected, whether that frequency reaches the cutoff.

Value

A data.frame. At level = "column", one row per design column: the column, the formula term it came from, its role, its block and family, whether the decision retained it, and, where a reference posterior was fitted, its posterior mean and standard deviation on the scientific scale. Beside them, the penalised path's folds_available, folds_entered, path_entry_s, path_exit_s, path_reentries, entry_s_median, entry_s_q25, entry_s_q75, entry_s_iqr and the three stability columns, all NA for a protected column and on a run with no penalised path, with the path itself in the attributes support_path and support_path_by_fold; with a Bayesian refit, also value_folds_in_support and value_in_block, NA where no refit ran. At level = "group", one row per group with its rule, n_columns, columns, the same profile and stability columns and the five ablation columns, and the per-fold group record in the attribute support_path_by_fold.