| 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 |
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().
x |
An |
... |
Not used. |
run_id |
Optional single string naming the run. When |
An orchestraManifest::orchestra_manifest.
fs_select(); orchestraManifest::verify_manifest() and
orchestraManifest::consume_manifest() on the consuming side.
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 }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
## S3 method for class 'fb_select' augment( x, data = NULL, type = c("unit_scores", "assessment_predictions", "value_rows", "value_units"), against = NULL, ... )## S3 method for class 'fb_select' augment( x, data = NULL, type = c("unit_scores", "assessment_predictions", "value_rows", "value_units"), against = NULL, ... )
x |
An |
data |
Ignored; the out-of-fold results are the ones the folds computed and cannot be recomputed on other rows. |
type |
|
against |
|
... |
Ignored. |
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.
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.
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 )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 )
method |
|
metric |
|
rule |
|
tolerance |
Nats per unit. Required by, and only used by,
|
search |
|
nterms_max |
Largest submodel the search considers. |
validate_search |
Whether the search itself is cross-validated.
|
threshold |
Posterior probability cut, in (0, 1). Used by, and only
by, |
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, |
stability_subsamples |
The number B of stability subsamples, a whole
number. |
stability_cutoff |
The frequency at or above which a column is
stable, in (0.5, 1]. Read only when |
stability_unit |
The units a subsample draws half of, as a one-sided
formula or a character vector. |
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
|
lambda_min_ratio |
The smallest point of that path as a fraction of
each fold's |
"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.
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.
fb_select(), which takes this object; fb_resamples() for the
folds the decision is assessed on.
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)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)
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.
fb_penalty( ..., resolution = c("term", "coefficient"), scaling = c("train_fold_standardize", "none") )fb_penalty( ..., resolution = c("term", "coefficient"), scaling = c("train_fold_standardize", "none") )
... |
One or more two-sided formulas, |
resolution |
|
scaling |
|
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.
An fb_penalty object: a list carrying $specs (the parsed
target and family of each formula), $resolution and $scaling.
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.
| 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.
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.
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))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))
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.
fb_resamples( unit = NULL, v = 10L, repeats = 1L, fold_id = NULL, strata = NULL, weights_by = NULL )fb_resamples( unit = NULL, v = 10L, repeats = 1L, fold_id = NULL, strata = NULL, weights_by = NULL )
unit |
Columns whose rows must stay together in a fold, as a
one-sided formula ( |
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 |
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 ( |
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.
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").
fb_select(), which takes this object; fb_decision() for the
decision rule scored on these folds.
fb_resamples() fb_resamples(unit = ~ site, v = 5L)fb_resamples() fb_resamples(unit = ~ site, v = 5L)
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.
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, ... )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, ... )
base |
A fitted flexyBayes model. Its fixed effects are the protected
block and are never penalised. A base fitted with |
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 |
penalty |
|
workflow |
|
fallback |
|
benchmark |
|
resamples |
An |
prediction |
|
decision |
An |
engine |
|
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 |
|
covariance |
The source of the fold covariance V that the benchmark
and optimiser workflows whiten by and plug in. |
refit |
|
ablation |
|
protected_alias |
|
keep_fold_data |
|
... |
Reserved. |
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.
priorthe 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.
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.
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.
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.
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.
fb_penalty() for the prior, fb_resamples() for the folds,
fb_decision() for the rule.
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 ) }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 ) }
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.
fb_select_fold_data(x, folds = NULL)fb_select_fold_data(x, folds = NULL)
x |
An |
folds |
Fold labels to return, or |
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.
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).
fb_select_path(), fb_select_refit().
Other selection fold data:
fb_select_path(),
fb_select_refit()
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) }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) }
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.
fb_select_path( x, alpha = NULL, n_lambda = NULL, lambda_min_ratio = NULL, folds = NULL )fb_select_path( x, alpha = NULL, n_lambda = NULL, lambda_min_ratio = NULL, folds = NULL )
x |
An |
alpha |
The elastic-net mixing parameter, a single number in
|
n_lambda, lambda_min_ratio
|
The grid, or |
folds |
Fold labels to solve, or |
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.
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.
fb_select_fold_data(), fb_select_refit().
Other selection fold data:
fb_select_fold_data(),
fb_select_refit()
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)) }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)) }
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.
fb_select_refit(x, columns, folds = NULL)fb_select_refit(x, columns, folds = NULL)
x |
An |
columns |
Candidate column names, as in the columns of
|
folds |
Fold labels to refit, or |
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.
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).
fb_select_fold_data(), fb_select_path().
Other selection fold data:
fb_select_fold_data(),
fb_select_path()
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 }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 }
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.
fs_accept(real, clone, level = 0.05, n_null = 200L, seed)fs_accept(real, clone, level = 0.05, n_null = 200L, seed)
real |
The real data: an |
clone |
The clone, in the same form and with the same columns. |
level |
The level |
n_null |
Number of splits of the real data. |
seed |
Integer seed for the splits. The caller's random-number state is put back. |
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 , 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
quantile of its null distribution, for level
and statistics, so the chance of rejecting a clone
drawn from the real data's law is at most about . 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 : 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.
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.
fs_implant() plants truth into an accepted clone.
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)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)
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.
fs_ademp(bench, aims, sims, mechanism = NULL)fs_ademp(bench, aims, sims, mechanism = NULL)
bench |
An |
aims |
A character vector stating the aims of the study. |
sims |
The simulations the benchmark ran, in the same order: an
|
mechanism |
Optional character vector naming the mechanism of each
simulation. |
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, , and the share carries that of a proportion,
. 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.
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).
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
fs_benchmark() runs the cells, fs_score() scores them.
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)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)
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.
fs_adjustment(regime, sets = NULL, n = NULL, max_controls = 10L)fs_adjustment(regime, sets = NULL, n = NULL, max_controls = 10L)
regime |
An |
sets |
|
n |
Optional sample size. With it, |
max_controls |
The largest number of controls for which every subset is tried. |
Variance. Every node of a regime is Gaussian, so the least-squares
coefficient of the treatment from rows, in the regression
of the outcome on , a set and an intercept, has
variance
where is the residual variance of
given 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 is the mean of the inverse of a
Wishart matrix on degrees of freedom, so se is exact at
every , 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
(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.
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.
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
fs_regime() for the regime, fs_effect() for the estimates
these costs describe.
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) }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) }
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().
fs_benchmark(sims, methods, seed, truth_def = NULL)fs_benchmark(sims, methods, seed, truth_def = NULL)
sims |
An |
methods |
A list of |
seed |
Integer seed for the cells. |
truth_def |
Passed to |
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.
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.
fs_select() runs one method on one problem.
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$statussims <- 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
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.
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 )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 )
n |
Number of rows. |
p |
Number of candidate predictors. |
predictors |
Law of the predictors: |
rho |
Correlation between neighbouring columns ( |
block_size |
Number of consecutive columns in a block. |
n_factors |
Number of common factors under |
bandwidth |
Largest distance between correlated columns under
|
sigma |
A |
markers |
If |
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 |
support |
Placement of the true predictors: |
effects |
Effect sizes before scaling: |
signs |
Signs of the effects: |
tail |
Rate of the weak geometric tail after the support, in [0,
1). Above zero it needs |
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:
|
pair_form |
Form of each pair's term: |
r2_pair |
Share of latent variance explained by the pair terms. Above
zero exactly when |
family |
Response family: |
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 |
slope |
Column index or name of the predictor whose slope varies
across the groups, or |
r2_slope |
Share of latent variance explained by the random slope.
Above zero exactly when |
relmat |
|
r2_relmat |
Share of latent variance explained by the background.
Above zero exactly when |
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
|
seed |
Integer seed for the draw. |
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 has unit-length loadings on
n_factors common factors and correlation with column .
"banded": correlation at distance
, where 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 , 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 for the family, the total is
. The main effects and the pair terms are scaled together so
that their sum has variance 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
. A random slope on column slope across the same groups has
population variance , 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 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.
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.
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
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$pairssim <- 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
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.
fs_effect( sims, adjust = c("none", "all", "selected", "valid"), selections = NULL, rows = c("all", "complete"), level = 0.95 )fs_effect( sims, adjust = c("none", "all", "selected", "valid"), selections = NULL, rows = c("all", "complete"), level = 0.95 )
sims |
An |
adjust |
|
selections |
With |
rows |
|
level |
Confidence level of the intervals. |
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 intervals for lm() and Wald intervals for lmer(). The
global test of no treatment effect is the Wald test on all contrasts
together: an test for lm(), 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".
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.
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
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)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)
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.
fs_effect_ademp(effects, alpha = 0.05)fs_effect_ademp(effects, alpha = 0.05)
effects |
A data frame from |
alpha |
Level of the global test for the rejection rate. |
With the estimate in replicate of
, the planted value and the
mean estimate, the Monte Carlo SEs are those of Morris, White and
Crowther (2019, Table 6): for the bias
,
for the empirical SE , for
the MSE , and for coverage and rejection
. The rejection rate is of the
global test at alpha, so it is the same on every level of an outcome.
The RMSE is . Table 6 gives no Monte Carlo SE
for it, so its SE is the first-order delta-method value
, reported as
NA when 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 . With normal errors and no bias that is a relative
, 0.125% at 200 replicates.
When effects carries residual correlations, rows with level
"residual correlation" give their mean, bias and empirical SE.
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.
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
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)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)
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.
fs_from_clone(clone, treatment, groups = NULL, covariates = NULL)fs_from_clone(clone, treatment, groups = NULL, covariates = NULL)
clone |
A |
treatment |
Name of the treatment column, a single string. |
groups |
Name of the column whose levels are the groups, or |
covariates |
Names of the numeric columns to keep as predictors.
|
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.
A list of class fs_clone_data:
Numeric matrix of the predictors, missing values imputed.
Logical, one per row of x: TRUE where no value
was imputed.
Integer, named by column: the values imputed.
The treatment column.
Factor of the groups, or NULL.
Integer: the rows of the clone kept.
Integer: the rows dropped for a missing treatment or group.
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
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)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)
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().
fs_grid(source, ...)fs_grid(source, ...)
source |
A preset name or names, an |
... |
Named arguments of the source, each a value or a vector of values to cross. |
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.
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.
fs_study() to state a study over one or more grids.
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))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))
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.
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 )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 )
x |
Numeric matrix or data frame of the predictors. |
y |
The real outcome, one value per row of |
mode |
|
family |
Response family of the planted outcome in |
groups |
Optional grouping of the rows, one value per row. |
outcome |
|
n_true |
Number of true predictors under |
support |
Placement of the true predictors, as in |
block |
Optional integer block of each column, used by |
effects |
|
signs |
|
r2 |
Share of variance the planted signal explains. |
r2_group |
Share of variance of the group intercepts in
|
n_decoys |
Number of decoy columns in |
resample |
Whether to draw the rows by whole groups first. |
n_pairs |
Number of interacting pairs. |
heredity |
|
pair_form |
|
r2_pair |
Share of variance of the pair terms. Above zero exactly
when |
n_nonlinear |
Number of true columns entering through |
shape |
|
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 |
r2_slope |
Share of variance of the random slope. Above zero exactly
when |
seed |
Integer seed. The caller's random-number state is put back. |
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, 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.
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.
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
fs_accept() asks whether a clone is close enough to the real
data for scores on it to mean anything.
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])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])
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.
fs_lift(method)fs_lift(method)
method |
An |
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
the quantities of one iteratively reweighted least-squares step. The
working response is treated as Gaussian with covariance
, 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.
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.
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.
fs_select() runs the lifted method, fs_stabilise() is the
other wrapper.
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)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)
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.
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") )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") )
id |
Short identifier, unique in a benchmark. |
name |
Readable name of the method. |
run |
Function of |
families |
Response families the method fits, from |
route |
How the method meets random effects: |
output |
What the method returns beyond a selected set:
|
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
|
carries |
The random structures the method fits, from |
requires |
The structures, among those in |
protects |
Whether the method keeps the protected columns of a
problem (see |
maturity |
|
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.
An object of class fs_method.
fs_methods() lists the methods the package ships,
fs_select() runs one.
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)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)
Lists the registry: every method fs_select() and fs_benchmark() can
be given by its identifier.
fs_methods(maturity = c("established", "all"))fs_methods(maturity = c("established", "all"))
maturity |
|
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).
fs_method() to define a method of your own.
fs_methods()fs_methods()
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.
fs_nested( method, criterion = "bic", alpha = NULL, max_size = Inf, cv_folds = 5L, gamma = 1 )fs_nested( method, criterion = "bic", alpha = NULL, max_size = Inf, cv_folds = 5L, gamma = 1 )
method |
An |
criterion |
One of |
alpha |
Optional numeric vector of elastic-net mixing values in
|
max_size |
Largest number of columns in a candidate. |
cv_folds |
Number of folds for |
gamma |
Weight of the model-space term of |
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.
An object of class fs_method, with identifier
"<base id>_nested_<criterion>" and output "ranking".
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.
fs_stabilise(), the other wrapper; fs_select() runs the
wrapped method.
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$selectedsim <- 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
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.
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 )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 )
x |
A numeric matrix of predictors, or an |
treatment |
The treatment, one value per row of |
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:
|
groups |
Optional grouping of the rows. Taken from |
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 |
n |
Number of rows to draw from |
protect |
With |
Outcome. For outcome , row in group ,
with and , where
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 the dose rescaled to
[0, 1] over its range, shape gives
"rise": , a steady rise;
"plateau": , a rise that
levels off;
"optimum": , highest at 60% of
the range;
"none": .
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.
An object of class fs_sim whose problem holds the first
outcome, and whose truth carries causal as described in Details.
fs_effect() estimates the planted effect, and
fs_effect_ademp() summarises the estimates over replicates.
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$contrastx <- 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
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.
fs_problem( y, x, family = c("gaussian", "binomial", "poisson", "negbin"), groups = NULL, block = NULL, slopes = NULL, relmat = NULL, protect = NULL )fs_problem( y, x, family = c("gaussian", "binomial", "poisson", "negbin"), groups = NULL, block = NULL, slopes = NULL, relmat = NULL, protect = NULL )
y |
Numeric response, one value per row of |
x |
Numeric matrix of candidate predictors, one column per
predictor. Column names are used as predictor names, and |
family |
Response family: |
groups |
Optional factor of length |
block |
Optional integer vector of length |
slopes |
Optional character vector of column names of |
relmat |
Optional relationship structure for a background random
effect: an |
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 |
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).
fs_design() simulates a problem together with its truth.
x <- matrix(stats::rnorm(200L), nrow = 50L) y <- x[, 1L] + stats::rnorm(50L) fs_problem(y, x)x <- matrix(stats::rnorm(200L), nrow = 50L) y <- x[, 1L] + stats::rnorm(50L) fs_problem(y, x)
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.
fs_regime( dag, coef = NULL, treatment = "X", outcome = "Y", estimand = c("total", "direct"), roles = NULL, ... )fs_regime( dag, coef = NULL, treatment = "X", outcome = "Y", estimand = c("total", "direct"), roles = NULL, ... )
dag |
A dagitty graph, as a string or a |
coef |
A named numeric vector of path coefficients, one per edge,
named |
treatment, outcome
|
Names of the treatment and outcome nodes. |
estimand |
|
roles |
Optional named character vector: the causal role of each
observed node, from |
... |
Parameters of the preset |
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 the matrix of coefficients (row the parent,
column the child), the total effect is the treatment-outcome entry of
and the direct effect is the treatment-outcome entry of
. The population coefficient of the treatment given a set
is the first entry of , with the
treatment followed by and 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).
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.
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
fs_regimes() for the presets, fs_plant() to draw from a
regime.
if (requireNamespace("dagitty", quietly = TRUE)) { r <- fs_regime("cinelli_7") r$effect r$identified r$roles }if (requireNamespace("dagitty", quietly = TRUE)) { r <- fs_regime("cinelli_7") r$effect r$identified r$roles }
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.
fs_regimes()fs_regimes()
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.
A data frame with one row per preset: name, source,
estimand, control, verdict, select and coef.
fs_regimes()[, c("name", "verdict", "control")]fs_regimes()[, c("name", "verdict", "control")]
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.
fs_run(study, dir = NULL)fs_run(study, dir = NULL)
study |
An |
dir |
|
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 over its replicates,
with and the exact bias and finite-sample variance
of the set chosen in replicate . 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.
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.
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
fs_study() for the plan; fs_benchmark(), fs_effect() and
fs_ademp() for the engine it routes to.
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) }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) }
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.
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") )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") )
sim |
An |
selected |
The selected columns of one simulation, as indices, names
or a logical vector over the columns. A list of these when |
scores |
Optional numeric score per column, larger meaning more
likely to be true. A list when |
score_type |
|
estimates |
Optional estimated main effects, one per column, on the
linear-predictor scale. A list when |
pairs |
Optional two-column matrix of selected pairs, as indices or
names. A list when |
truth_def |
One or more of |
window |
Distance in columns for |
threshold |
Absolute correlation for |
proxy_rule |
One or more of |
by |
|
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.
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.
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
fs_design() for the simulations, fs_stability() for the
agreement of selections across resamples.
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))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))
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.
fs_select(problem, method, ..., seed = NULL)fs_select(problem, method, ..., seed = NULL)
problem |
An |
method |
An |
... |
Tuning values that replace the method's defaults, named as in
its |
seed |
Optional integer seed. When given, the method runs under it and the caller's random-number state is put back afterwards. |
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.
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).
fs_benchmark() runs methods over many simulations.
sim <- fs_design(n = 200L, p = 20L, n_true = 3L, r2 = 0.5, seed = 1L) fs_select(sim, "marginal_bh", q = 0.05)sim <- fs_design(n = 200L, p = 20L, n_true = 3L, r2 = 0.5, seed = 1L) fs_select(sim, "marginal_bh", q = 0.05)
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.
fs_stabilise(method, B = 50L, cutoff = 0.75)fs_stabilise(method, B = 50L, cutoff = 0.75)
method |
An |
B |
Number of complementary pairs of halves. |
cutoff |
Selection probability at or above which a column is
selected, in |
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.
An object of class fs_method, with identifier
"<base id>_cpss" and output "probability".
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
fs_select() runs the wrapped method, fs_stability() measures
agreement between selections.
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)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)
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.
fs_stability(selected, p)fs_stability(selected, p)
selected |
A list of at least two selections, each as column indices
or a logical vector of length |
p |
Number of candidate columns. |
With selections over columns, the share of
selections holding column , and the mean selection size, the estimate is
It is missing when every selection is empty or every selection holds every column.
A single number.
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
fs_stability(list(c(1, 2, 3), c(1, 2, 4), c(1, 2, 3)), p = 10L)fs_stability(list(c(1, 2, 3), c(1, 2, 4), c(1, 2, 3)), p = 10L)
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.
fs_study( aims, data, methods = character(0L), references = NULL, target = c("support", "effect"), n_sim = NULL, mcse = NULL, seed )fs_study( aims, data, methods = character(0L), references = NULL, target = c("support", "effect"), n_sim = NULL, mcse = NULL, seed )
aims |
One sentence: the question the study answers. |
data |
An |
methods |
Ids of registered methods, from |
references |
|
target |
|
n_sim |
Replicates per mechanism, a whole number of at least 2. |
mcse |
The largest bias MCSE to plan for, in place of |
seed |
One whole number. |
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
(Morris et al. 2019, Table 6), so mcse sets
per mechanism, with
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
takes the -th stream (parallel::nextRNGStream()), and replicate
its -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.
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.
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
fs_grid() for the mechanisms, fs_adjustment() for the costs
known now.
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 }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 }
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.
fs_transfer( real, clone, methods, seed, n_halves = 4L, n_folds = 5L, level = 0.05, n_null = 0L )fs_transfer( real, clone, methods, seed, n_halves = 4L, n_folds = 5L, level = 0.05, n_null = 0L )
real |
The real data: an |
clone |
The clone, in the same form and with the same columns. |
methods |
A list of |
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 |
n_folds |
Number of folds for |
level |
The level |
n_null |
Number of half-splits of the real data for the threshold. Zero for no threshold. |
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 , with 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 , 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 is the quantile of 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.
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
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.
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
fs_accept() for layers 1 and 2.
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)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)
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.
## S3 method for class 'fb_select' glance(x, against = NULL, ...)## S3 method for class 'fb_select' glance(x, against = NULL, ...)
x |
An |
against |
|
... |
Ignored. |
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.
A one-row data.frame.
Displays for a selection
## S3 method for class 'fb_select' plot( x, type = c("elpd_by_size", "rank_stability", "shrinkage", "benchmark", "entrance_path", "entrance_heatmap", "loss_surface"), ... )## S3 method for class 'fb_select' plot( x, type = c("elpd_by_size", "rank_stability", "shrinkage", "benchmark", "entrance_path", "entrance_heatmap", "loss_surface"), ... )
x |
An |
type |
|
... |
Passed to the underlying plotting call. The entrance heat map
also takes |
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
## S3 method for class 'fb_select' tidy(x, level = c("column", "group"), ...)## S3 method for class 'fb_select' tidy(x, level = c("column", "group"), ...)
x |
An |
level |
|
... |
Ignored.
Where |
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.
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.