Skip to content

API reference

Most code needs only the three estimators. The layers beneath them are public as well, for running a search or a selector on its own, writing a scorer, or building and evaluating expressions directly.

Estimators

beamfeat.BeamFeatRegressor

Bases: RegressorMixin, _BeamFeatBase

Constructs features, then fits a linear model on them.

The linear model is the point: its coefficients combine with the feature formulas to give a closed-form expression for the fitted relationship, available via equation().

Parameters:

Name Type Description Default
alpha float | str

Ridge regularisation strength for the downstream model. The default "auto" selects the strength by efficient leave-one-out cross-validation over a logarithmic grid, which stays stable when many correlated features are selected from few rows; pass a float to fix the strength instead.

'auto'

Other arguments match BeamFeatTransformer.

Attributes:

Name Type Description
features_

Selected expressions.

feature_formulas_

Their formula strings.

model_

The fitted downstream linear model, None when no feature was kept.

scaler_

The StandardScaler applied to the features before the linear model, None when no feature was kept. coef_ divided by its scale_ gives the coefficients on the raw features.

coef_

Coefficients of the downstream model, on the standardised features.

intercept_

Intercept of the downstream model; the training mean of the target when no feature was kept.

alpha_

The ridge penalty used, chosen by cross-validation when alpha="auto"; None when no feature was kept.

fdr_scope_

Which set fdr_controlled_ is a statement about; see BeamFeatTransformer. "screened set" is what equation() marks in its output.

equations_

The forward path through the screened set, one record per number of terms, with the record of the fitted model marked; see BeamFeatTransformer and equations().

The other fitted attributes, such as selection_report_, are those of BeamFeatTransformer.

equation(precision=4, max_terms=None, style='significant')

Return the fitted model as a readable closed-form equation.

Parameters:

Name Type Description Default
precision int

Significant figures for the coefficients, or decimal places when style="fixed".

4
max_terms int | None

If set, include only the terms with the largest standardised coefficients. The omitted terms are held at their training mean, whose contribution moves into the constant, so the shortened equation agrees with the model on average rather than treating the omitted terms as zero.

None
style str

"significant" adapts to each coefficient's magnitude, "fixed" aligns decimal places, "scientific" uses uniform e-notation. "fixed" falls back to significant figures for any value that would otherwise display as zero.

'significant'

Returns:

Type Description
str

A string such as y = 2.104*(a * b) - 0.512*log(c) + 3.991.

str

When the parsimony step dropped terms from the screened set, a

str

suffix records how many of the certified terms are printed and

str

how to print them all, since the guarantee covers the screened

str

set rather than this subset of it. At the default forward step it

str

also says how many terms parsimony_alpha=0.05 would print,

str

when that is fewer.

equations(precision=4, max_n_terms=None)

Return the forward path through the screened set, one equation per size.

Line k holds the k terms the greedy forward step of parsimony="forward" would fit if it stopped there, with its complexity, the in-sample R^2 of a least-squares fit of those terms on the rows screening used, and the R^2 its last term added. The line holding the returned features is marked *; at the default settings it is the first line whose successor adds less than parsimony_tol. At the default forward step, the line where parsimony_alpha=0.05 would stop is marked a when it holds fewer terms. The records behind the text are equations_.

Each line is written y ~ a + b: a linear model in those terms, without coefficients, since only the marked line has fitted ones, which the regressor's and classifier's equation() prints. For classification the R^2 is that of the integer-coded labels, the ranking heuristic the forward step uses, and not a classification metric.

The FDR guarantee covers the screened set, the last line, and not an equation chosen from this list: every line is a subset of the screened set chosen on the rows screening used, as the features returned at the default settings are. The output says so in its last line.

Parameters:

Name Type Description Default
precision int

Decimal places for R^2, and significant figures for its gain.

4
max_n_terms int | None

If set, show only the equations with at most this many terms, and the marked lines whatever their size. The remaining lines are elided as ....

None

Returns:

Type Description
str

The list as text, or a one-line explanation when nothing was

str

screened.

fit(X, y)

Construct features and fit the downstream model.

formulas()

Return the selected expressions as readable formula strings.

get_feature_names_out(input_features=None)

Return the formula strings of the constructed features.

latex(precision=4, max_terms=None, style='significant', note=True)

Return the fitted model as a LaTeX equation.

The same equation as equation(), with the same terms, order and coefficients, and the same note, set as \text. Each feature is rendered by sympy.latex from to_sympy(), so sympy is required, as it is there. The string has no math delimiters; in a notebook, IPython.display.Math(model.latex()) renders it.

Parameters:

Name Type Description Default
precision int

As in equation().

4
max_terms int | None

As in equation().

None
style str

As in equation(). E-notation is written as a power of ten.

'significant'
note bool

Whether to append the bracketed note. False returns the bare equation, for pasting into a document; the guarantee still covers the screened set, not the printed subset.

True

Returns:

Type Description
str

A string such as y = 2.104 a b - 0.512 \log{\left(c \right)} + 3.991.

latex_formulas()

Return the selected expressions as LaTeX strings.

Rendered by sympy.latex from to_sympy(), so sympy is required, as it is there; the formulas are in the order of feature_formulas_.

predict(X)

Predict using the constructed features and fitted model.

A row on which a fitted expression cannot be evaluated (outside its domain, such as the logarithm of a negative value) is predicted as NaN, with a warning; the other rows are unaffected. score() raises on such rows rather than scoring the others in silence.

score(X, y, sample_weight=None)

Return the R^2 of predict() on X.

Raises:

Type Description
ValueError

If a fitted expression cannot be evaluated on some row. R^2 over the remaining rows would be a different quantity, so it is not returned in its place.

to_sympy()

Return the selected expressions as sympy objects.

beamfeat.BeamFeatClassifier

Bases: ClassifierMixin, _BeamFeatBase

Constructs features, then fits a logistic model on them.

Parameters:

Name Type Description Default
C float

Inverse regularisation strength for the downstream model.

1.0

Other arguments match BeamFeatTransformer.

Attributes:

Name Type Description
features_

Selected expressions.

classes_

Class labels seen during fit.

model_

The fitted downstream logistic model, None when no feature was kept or the training data had a single class.

scaler_

The StandardScaler applied to the features before the logistic model, None when no feature was kept.

coef_

Coefficients of the logistic model, on the standardised features; empty when no feature was kept.

intercept_

Intercepts of the logistic model; empty when no feature was kept.

class_prior_

Class frequencies of the training labels, set only when no feature was kept, in which case the model predicts them.

fdr_scope_

Which set fdr_controlled_ is a statement about; see BeamFeatTransformer. "screened set" is what equation() marks in its output.

equations_

The forward path through the screened set, one record per number of terms, with the record of the fitted model marked; see BeamFeatTransformer and equations(). Its R^2 is of the integer-coded labels, the forward step's ranking heuristic.

The other fitted attributes, such as selection_report_, are those of BeamFeatTransformer.

decision_function(X)

Return the model's decision scores.

With no feature selected the scores are the log prior odds (binary) or the log priors (multiclass), so they agree with predict() and predict_proba(). NaN on a row where a fitted expression cannot be evaluated; see predict().

equation(precision=4, max_terms=None, style='significant')

Return the fitted classifier as a readable log-odds equation.

For binary problems the single line gives the log-odds of the positive class (classes_[1]): logit P(y = c1) = ..., so the decision boundary is the zero level set of the right-hand side. For multiclass problems one line is returned per class; these are the softmax scores of the fitted multinomial model, and the predicted class is the argmax across lines.

Parameters:

Name Type Description Default
precision int

Significant figures for the coefficients, or decimal places when style="fixed".

4
max_terms int | None

If set, include only the terms with the largest standardised coefficients per line. The omitted terms are held at their training mean, whose contribution moves into the constant.

None
style str

"significant" adapts to each coefficient's magnitude, "fixed" aligns decimal places, "scientific" uses uniform e-notation. "fixed" falls back to significant figures for any value that would otherwise display as zero.

'significant'

When the parsimony step dropped terms from the screened set, a suffix records how many of the certified terms are printed and how to print them all, and at the default forward step how many terms parsimony_alpha=0.05 would print, when that is fewer. The terms are shared across the lines of a multiclass equation, so the suffix appears once at the end of the block.

equations(precision=4, max_n_terms=None)

Return the forward path through the screened set, one equation per size.

Line k holds the k terms the greedy forward step of parsimony="forward" would fit if it stopped there, with its complexity, the in-sample R^2 of a least-squares fit of those terms on the rows screening used, and the R^2 its last term added. The line holding the returned features is marked *; at the default settings it is the first line whose successor adds less than parsimony_tol. At the default forward step, the line where parsimony_alpha=0.05 would stop is marked a when it holds fewer terms. The records behind the text are equations_.

Each line is written y ~ a + b: a linear model in those terms, without coefficients, since only the marked line has fitted ones, which the regressor's and classifier's equation() prints. For classification the R^2 is that of the integer-coded labels, the ranking heuristic the forward step uses, and not a classification metric.

The FDR guarantee covers the screened set, the last line, and not an equation chosen from this list: every line is a subset of the screened set chosen on the rows screening used, as the features returned at the default settings are. The output says so in its last line.

Parameters:

Name Type Description Default
precision int

Decimal places for R^2, and significant figures for its gain.

4
max_n_terms int | None

If set, show only the equations with at most this many terms, and the marked lines whatever their size. The remaining lines are elided as ....

None

Returns:

Type Description
str

The list as text, or a one-line explanation when nothing was

str

screened.

fit(X, y)

Construct features and fit the downstream classifier.

formulas()

Return the selected expressions as readable formula strings.

get_feature_names_out(input_features=None)

Return the formula strings of the constructed features.

latex(precision=4, max_terms=None, style='significant', note=True)

Return the fitted classifier as a LaTeX log-odds equation.

The same equations as equation(): for a binary problem the log-odds of classes_[1], for a multiclass problem one softmax score per class in an aligned block, followed by the same note. Each feature is rendered by sympy.latex from to_sympy(), so sympy is required, as it is there. The string has no math delimiters.

Parameters:

Name Type Description Default
precision int

As in equation().

4
max_terms int | None

As in equation().

None
style str

As in equation(). E-notation is written as a power of ten.

'significant'
note bool

Whether to append the bracketed notes. False returns the bare equations, for pasting into a document; the guarantee still covers the screened set, not the printed subset.

True

latex_formulas()

Return the selected expressions as LaTeX strings.

Rendered by sympy.latex from to_sympy(), so sympy is required, as it is there; the formulas are in the order of feature_formulas_.

predict(X)

Predict class labels.

A row on which a fitted expression cannot be evaluated (outside its domain, such as the logarithm of a negative value) cannot be given a NaN label, so it is assigned the most frequent training class -- the prediction of a model with no features -- with a warning. The other rows are unaffected. predict_proba() and decision_function() return NaN for such rows, which is how to find them.

predict_proba(X)

Predict class probabilities.

NaN on a row where a fitted expression cannot be evaluated; see predict().

to_sympy()

Return the selected expressions as sympy objects.

beamfeat.BeamFeatTransformer

Bases: TransformerMixin, _BeamFeatBase

Constructs and selects features, for use inside a pipeline.

Parameters:

Name Type Description Default
scorer str | Scorer

Scoring strategy for the search. A name ("correlation", "spearman", "mutual_information", "gradient_boosting", or an alias such as "mi") or a Scorer instance.

'correlation'
selector str | Selector | None

FDR-controlled selector, or None to keep the search output unfiltered. A name ("permutation", "knockoff") or a Selector instance, whose own settings apply in place of target_fdr and selection_correction.

'permutation'
problem_type str

"regression" or "classification". Determines how the scorer and selector treat the target.

'regression'
max_depth int

Maximum expression depth.

2
beam_width int

Expressions retained at each search depth.

50
max_features int | None

Cap on the features the search ranks by score, before selection; residual_slots adds up to that many more.

None
target_fdr float

Nominal false discovery rate for the selector.

0.1
unary_ops tuple[str, ...]

Unary operators to apply. "sign", off by default, adds switches at zero, such as x2*sign(x0) for a target whose slope in x2 changes sign with x0.

DEFAULT_UNARY
binary_ops tuple[str, ...]

Binary operators to apply.

DEFAULT_BINARY
redundancy_threshold float

Absolute correlation at or above which a candidate is treated as a duplicate.

0.95
include_originals bool

Whether input columns compete alongside constructed expressions.

True
units dict[str, Any] | None

Optional units of the input columns: a mapping of column name to unit, or a sequence with one unit per column. A unit is a pint quantity or unit, or a string pint parses, such as "kg" or "m / s**2". Supplying units restricts the search to dimensionally valid expressions; cover every column, since one without a unit combines freely with the rest.

None
selection_holdout float | None

Fraction of the training rows held out of the search for selection, strictly between 0 and 1, or None to select on the search rows (which forfeits the guarantee, so fdr_controlled_ is then False).

0.5
parsimony_holdout float | None

Fraction of the selection rows held back to re-test the returned terms, strictly between 0 and 1, or None (default) for no re-test. certify_test sets the test.

None
selection_correction str

"by" (Benjamini-Yekutieli, default) or "bh" (Benjamini-Hochberg), used when selector is the name "permutation". A selector instance keeps its own correction and target_fdr, and a warning names any estimator setting it overrides; PermutationSelector() defaults to "bh".

'by'
on_no_discoveries str

What to return when the screen rejects no null: "empty" (default) keeps no constructed features, "fallback" keeps the unfiltered search output with fdr_controlled_ False, "raise" raises NoDiscoveriesError.

'empty'
parsimony str | None

"forward" (default) fits a compact subset of the screened set, chosen by greedy forward selection on the selection rows. That subset is not re-tested, so the FDR guarantee covers the set it was drawn from and not the terms returned, and fdr_scope_ (and the regressor's and classifier's equation()) marks this whenever terms were dropped. None returns the screened set entire, so the returned features are exactly the set the guarantee covers; parsimony_holdout buys both, for rows. Either way equations_ records the forward path through the whole screened set.

'forward'
parsimony_tol float

Minimum incremental R^2 a feature must add to be kept by parsimony="forward". Ignored when parsimony is None.

0.001
random_state int | None

Seed. Fitting is deterministic given this.

0
verbose int

Progress reporting to stdout. 0 (default) is silent; 1 prints one line per stage -- the split, the search, the screening, the parsimony step and the fitted result; 2 adds per-depth search detail and the strongest certified candidates with their p- and q-values.

0
n_jobs int | None

Workers that evaluate and score the search's candidates: threads, or processes for "gradient_boosting" (see BeamSearch). 1 (default) uses the calling thread only, -1 every core, and None follows an enclosing joblib configuration (joblib.parallel_config, or parallel_backend before joblib 1.3). Small searches run in the calling thread regardless. With input_test, as many threads share its tests. The fitted result is the same for every value.

1
max_inputs int | None

Most distinct input columns one feature may use, or None (default) for no limit. Candidates over it are ruled out during the search, before evaluation. A feature of depth d uses at most 2**d columns, so at the default max_depth of 2 a value of 4 or more has no effect. A law that needs more inputs than the limit cannot be found.

None
fitted_ops tuple[str, ...]

Parametric operators whose one constant is fitted inside the expression: "exp_scaled" (exp(a*x)), "pow" (x^a), "inv_shift" (1/(x + a)) and "log_shift" (log(x + a)). All four by default; () keeps every expression free of constants, as the default did before 0.6.0, and fits about twice as fast on small data. "sign_shift" (sign(x + a), its threshold between the operand's 5% and 95% quantiles) is off by default; it adds switches away from zero, such as x2*sign(x0 - 0.7). The constants are fitted during the search, on the search rows only (see BeamSearch), so the screen on the selection rows sees fixed expressions and its guarantee is unchanged; with selection_holdout=None the rows are shared, as they are for the search itself. A fitted constant is part of the expression: transform and predict reuse it, and the formulas and to_sympy() show it, as an exact fraction when it was snapped to one. A law the plain operators can write keeps its plain form unless the snapping test, on the search rows, rejects the null that the plain form fits as well: log(x0), not a fitted near copy such as (x0)^(-0.02).

DEFAULT_FITTED
certify_test str

The test the parsimony_holdout re-test applies to each returned term on the held-back rows. "marginal" (default) re-runs the configured selector, whose null is that the term is independent of the target, so it rejects the null of a term that only rides on a true one, x0*x7 when the target depends on x0 alone. "conditional" tests each term given the other returned terms, with a Freedman-Lane permutation test: the target and the term are residualised on the other terms and an intercept, the target's residuals are permuted, the statistic is the partial correlation, and the screen's step-up correction is applied at the screen's level. Its null is that the term's coefficient is zero in a linear model of the target on all the returned terms. A term standing in for a true one the others leave out is not null in that sense, so rejecting its null is not a false rejection. Its p-values are approximate: they rest on the errors of a linear model of the target on the other terms being exchangeable (independent and identically distributed, say, so of constant variance), and are close to exact rather than exact even then, except for a single term, where the test is the marginal one. If the re-test rejects no null, the screened set is returned, which carries the screen's marginal guarantee only. After the forward step "conditional" needs parsimony_alpha: without it the step hands the re-test riders it cannot certify, and on noisy data the screened set comes back in most fits, so that combination raises. With parsimony=None the re-test sees the whole screened set and needs no parsimony_alpha. Regression only; ignored when parsimony_holdout is None. See the guarantees page for its measured calibration.

'marginal'
magnitude_slots int | str

Beam slots added at each search depth for candidates ranked by how well their magnitude tracks the target's, for laws whose parts do not correlate with the target, such as x0*x1*x2 with centred inputs, whose pairwise products the score's ranking leaves among noise. "auto" (default) adds 10 for regression and none for classification, whose labels carry no magnitude; 0 adds none, the default before 0.7.0. On wide tables, where the first depth cannot propose every pair of inputs, the inputs are also proposed in an order that interleaves the two rankings. The ranking is part of the search, on the search rows only (see BeamSearch), so the screen on the selection rows sees fixed expressions and its guarantee is unchanged. In benchmarks/release_comparison/ the slots recovered every x0*x1*x2 stress law (exact recovery 0.40 and 0.55 without them, 1.00 with), left the held-out score of 10 of 12 real datasets within 0.005 (riboflavin fell by 0.011, eyedata rose by 0.009), and cost a fifth more fit time. A positive value is for regression only.

'auto'
input_test bool

Whether to test, on the selection rows, each column inside each candidate that reads more than one, and drop a screened term before parsimony runs when the test fails to reject the null for one of its columns. False (default) leaves the fit unchanged. A column is tested by permuting its rows alone, wherever it occurs in the expression, and recomputing the screen's statistic; the screen's step-up correction is applied across every (candidate, column) pair of every candidate, screened or not. The null is that the column is independent of the target and of the candidate's other columns, under which the p-values are exact: it removes (x0*x1)/(x1 + x8) when x8 is unrelated to everything, but a junk column correlated with a real one is not null in that sense, so its null can be rejected and the term kept. The screen's guarantee is unchanged and still covers the screened set. If the test would drop every screened term, the screened set is used with a warning. Each draw re-evaluates the expression, so the time grows with the rows: a few seconds at a few hundred rows, minutes at ten thousand, which n_jobs threads share.

False
parsimony_alpha float | None

Level of a chance check on each term the forward step of parsimony="forward" adds after the first, or None (default) for none, which leaves the fit unchanged. On a noisy target the best of many remaining terms adds more than parsimony_tol to R^2 by fitting noise alone, so the step keeps riders. With a level, the step also stops at the first term whose gain fails to reject the null that it is no larger than the best gain the remaining terms reach against noise: 200 wild-bootstrap draws of the current residual (each row's residual times an independent standard normal), net of the terms already added. Like parsimony_tol it shapes the returned subset, on the selection rows, and not the screen, whose guarantee is unchanged; it is a stopping rule, not a guarantee on the subset. It suits a target of a few strong terms: on real data, whose many modest effects each add little, it stopped after one to five terms on 10 of 12 datasets in benchmarks/three_settings/ and lowered held-out score on 9. Ignored when parsimony is None.

None
residual_slots int

Places added to the search's final ranking for terms that explain what the leading terms leave. The ranking keeps the max_features candidates (beam_width by default) that score best against the target, and a dominant term fills it with restatements of itself, so that a weaker term beside it is cut, such as log(x3) in x0*x1/x2 + 0.5*log(x3). A positive value adds up to that many places for the first terms of a greedy forward path through the search's candidates, each the one that adds most to a least-squares fit of those before it; a path term replaces a ranked near copy of itself, and is first compared with the other transforms of its operand, which the search may have dropped as near copies (log(x3) beside 1/x3). 0 (default) adds none. The path terms explain what the leading terms leave, noise as well as a weak term, so on their own they add riders to the printed equation; parsimony_alpha=0.05 beside them stops the forward step before the riders, and the weak term is still printed. The path is part of the search, on the search rows only (see BeamSearch), so the screen's guarantee is unchanged. A positive value is for regression only.

0
max_search_rows int | None

Most rows the search runs on, or None (default) for every search row. The search's time and memory grow with its rows, while a strong term stands out on a few thousand. With a value, the search runs on that many search rows, drawn at random (random_state), and its expressions are then checked on every search row against the search's filters (an operator's domain, a denominator near zero). The screen still runs on every selection row, none of which the search sees, so its guarantee is unchanged. What a sample can cost is a weak term: ranked on fewer rows, it can be cut before the screen tests it.

None

Attributes:

Name Type Description
features_

Selected Node expressions.

feature_formulas_

Their formula strings.

feature_ranges_

Each feature's smallest and largest value on the training rows, one row per feature. transform and predict raise ExtrapolationWarning when new rows take a feature more than one width of this range beyond it.

search_result_

The SearchResult.

selection_result_

The SelectionResult, or None if no selector was used.

fdr_controlled_

Whether the returned features came from the FDR-screened set. None if no selector was used.

fdr_scope_

Which set fdr_controlled_ is a statement about -- "printed equation" when the guarantee covers the returned features, "screened set" when it covers a larger set they were drawn from, None when the flag is not True.

equations_

The greedy forward path through the screened set, one record per size k from 1 to the size of the screened set, in order of k. Each record is a dict with "n_terms" (k); "formulas" and "features", the k terms as formula strings and Node expressions in the order the path adds them; "r2", the in-sample R^2 of a least-squares fit of them on the rows screening used (of the integer-coded labels for classification, a ranking heuristic); "complexity", the number of nodes in their expression trees plus one per term for its coefficient and one per fitted constant; and "model", whether they are the returned features. At most one record is marked, and none is when the returned features are not on the path, after a parsimony_holdout re-test for instance. The path is recorded whatever parsimony is, and the steps up to the returned subset are those the forward step takes, so recording it changes nothing that is returned. None without a selector, and empty when the screen rejected no null. The FDR guarantee covers the screened set, the last record, and not a record chosen from the list; equations() renders it and says so.

selection_report_

One dict per candidate screened, in the search's order: "formula"; "p_value" and "q_value", None for a knockoff selector, which computes neither; "statistic"; "screened", whether the screen rejected its null, which marks the set the guarantee covers; and "kept", whether it is among the returned features. None without a selector.

fdp_inflation_

The size of the certified set divided by the number of returned features, |S|/|S'|: the factor by which returning a subset can raise the realised false discovery proportion. 1.0 when the returned features are the certified set, None when nothing was certified.

input_report_

One dict per (candidate, column) pair the input test ran on: "formula", "column", "p_value", "q_value" and "null_rejected", whether the step-up correction rejects the column's null, that it is independent of the target and of the candidate's other columns. None when input_test is False.

certification_result_

The SelectionResult of the parsimony_holdout re-test, or None when it did not run. Its method is "conditional_permutation" under certify_test="conditional".

n_features_out_

Number of features produced.

n_features_in_

Number of input columns seen during fit.

feature_names_in_

Names of the input columns, when X had string column names.

A row on which a fitted expression cannot be evaluated at transform time (outside its domain, such as the logarithm of a negative value) is NaN in that expression's column, with a warning naming the expression; the other rows are unaffected. Impute or drop those rows before a downstream model that does not accept NaN.

equations(precision=4, max_n_terms=None)

Return the forward path through the screened set, one equation per size.

Line k holds the k terms the greedy forward step of parsimony="forward" would fit if it stopped there, with its complexity, the in-sample R^2 of a least-squares fit of those terms on the rows screening used, and the R^2 its last term added. The line holding the returned features is marked *; at the default settings it is the first line whose successor adds less than parsimony_tol. At the default forward step, the line where parsimony_alpha=0.05 would stop is marked a when it holds fewer terms. The records behind the text are equations_.

Each line is written y ~ a + b: a linear model in those terms, without coefficients, since only the marked line has fitted ones, which the regressor's and classifier's equation() prints. For classification the R^2 is that of the integer-coded labels, the ranking heuristic the forward step uses, and not a classification metric.

The FDR guarantee covers the screened set, the last line, and not an equation chosen from this list: every line is a subset of the screened set chosen on the rows screening used, as the features returned at the default settings are. The output says so in its last line.

Parameters:

Name Type Description Default
precision int

Decimal places for R^2, and significant figures for its gain.

4
max_n_terms int | None

If set, show only the equations with at most this many terms, and the marked lines whatever their size. The remaining lines are elided as ....

None

Returns:

Type Description
str

The list as text, or a one-line explanation when nothing was

str

screened.

fit(X, y=None)

Construct and select features from the training data.

Parameters:

Name Type Description Default
X array - like

(n_samples, n_features) training data.

required
y array - like

Target. Required, since both search and selection are supervised.

None

Returns:

Type Description
BeamFeatTransformer

self.

formulas()

Return the selected expressions as readable formula strings.

get_feature_names_out(input_features=None)

Return the formula strings of the constructed features.

latex_formulas()

Return the selected expressions as LaTeX strings.

Rendered by sympy.latex from to_sympy(), so sympy is required, as it is there; the formulas are in the order of feature_formulas_.

to_sympy()

Return the selected expressions as sympy objects.

transform(X)

Evaluate the selected expressions on new data.

Warnings and errors

beamfeat.NoDiscoveriesWarning

Bases: UserWarning

Raised when FDR-controlled testing leaves no feature to return.

The screen rejected no null, or a later test (the parsimony_holdout re-test, or input_test) would drop every term the screen selected; the message says which, and what the estimator returns instead.

Emitted through warnings (not only logging) so it is visible in notebooks and default configurations — the scikit-learn convention for fit-time conditions the user must act on.

beamfeat.NoDiscoveriesError

Bases: RuntimeError

Raised in on_no_discoveries="raise" mode when the screen rejects no null.

beamfeat.DegenerateFitWarning

Bases: UserWarning

Raised when the assembled model scores poorly on the selection holdout.

FDR screening bounds the expected share of selected features that are not associated with the target; it says nothing about whether the linear model built on them is well conditioned — a feature can be a true discovery and still carry extreme leverage that destabilises the fit. These are different claims, and this warning marks the gap when it opens: negative R^2 on the selection rows for regression, or accuracy below the majority-class rate for classification. The check is a diagnostic — the selection rows also enter the final fit — not an independent evaluation.

beamfeat.ExtrapolationWarning

Bases: UserWarning

Raised when new rows take a feature far beyond its range on the training rows.

A formula is fitted where the training data lie, and beyond them it can behave unlike anything the fit saw: a ratio whose denominator approaches zero there takes any size and either sign. predict, transform and the probability methods warn when a feature's values on the new rows lie more than one width of its training range beyond that range, and say on how many rows, which features and how far. Predictions on those rows extrapolate the equation; check them before relying on them.

Screening another tool's equation

beamfeat.screen

Screen another tool's equation on rows it did not see.

A symbolic regression tool (PySR, Operon, gplearn, PySINDy and the like) reports an equation fitted on some rows, with no statement about whether its terms are real. screen_equation() tests the equation's terms on other rows, which the tool never saw. There the terms are fixed functions, so a permutation test of each term against the target is valid in finite samples, whatever the tool did to find them.

The marginal test. Each top-level additive term of the equation, as written, is one candidate. Its null is that the term is independent of the target. The test is the one beamfeat's own fits use, PermutationSelector: the term's absolute Pearson correlation with the target against the same statistic on permuted targets, with the add-one p-value. The Benjamini-Yekutieli step-up (correction="by", the default) controls the false discovery rate among the kept terms under any dependence between their p-values; Benjamini-Hochberg ("bh") needs positive dependence.

The input test (input_test=True). The marginal test keeps a term such as x0*x7 when x0 carries it, whatever x7 is. The input test asks, of each variable of each term that uses more than one, whether the term needs it: the variable's rows are permuted inside the term alone and the term's correlation with the target is recomputed, every pair against the same permutations. A variable's null is that it is independent of the target and of the term's other variables together. The p-value is the add-one estimator over the fewest draws that let the strictest step-up threshold be reached (at least 1,000), except that a pair stops at its tenth exceedance, after L draws, with p = 10 / L (Besag and Clifford's sequential estimator, valid in the same sense). The step-up runs over every (term, variable) pair of every term, kept by the marginal test or not, so which pairs are tested does not depend on the marginal outcome. A term is kept when the marginal test rejects its null and, with the input test, the input test rejects the null of each of its variables. A variable correlated with another input is not null in this sense, so a stand-in for a true input can have its null rejected: no test of association can tell the two apart.

What is never kept. A term undefined (not finite, or not real) or constant on any of the rows cannot be tested. It is reported as untestable and never kept, and so is every pair of it in the input test.

Coefficients. The kept terms are reported as the tool wrote them. To use them, refit their coefficients on the rows the tool searched, never on the rows that screened them: a refit on the screen rows would reuse them.

Few rows make a weak test. A term the screen does not keep has no support on these rows, which is not a finding that it is false. With a few dozen rows a real term of modest effect is often not kept.

EquationScreen dataclass

What screen_equation() found: each term, its p-value, and what was kept.

Attributes:

Name Type Description
terms tuple

The equation's top-level additive terms that use a variable, each as written, in sympy's order of the sum's terms. A constant term carries no variable and is left out.

p_values ndarray

The marginal test's p-value of each term; NaN for a term that cannot be tested.

marginal tuple[int, ...]

Indices of the terms whose marginal null is rejected.

kept tuple[int, ...]

Indices of the kept terms: those of marginal and, with the input test, whose every variable's null is rejected as well.

untestable tuple[int, ...]

Indices of the terms undefined or constant on the rows.

input_pairs tuple[tuple[int, str], ...]

The input test's (term index, variable name) pairs, empty without the input test.

input_p_values ndarray

The p-value of each pair.

input_rejected tuple[int, ...]

Positions in input_pairs of the pairs whose null is rejected.

q float

The false discovery rate level.

correction str

"by" (Benjamini-Yekutieli) or "bh" (Benjamini-Hochberg).

input_test bool

Whether the input test ran.

n_rows int

The number of rows the terms were tested on.

kept_terms property

The kept terms, as the tool wrote them.

removed property

Indices of the terms not kept, untestable ones included.

summary()

One line per term: its p-value, whether its nulls are rejected, and whether it is kept.

screen_equation(equation, X, y, *, q=0.1, correction='by', input_test=False, feature_names=None, random_state=0)

Test another tool's equation, term by term, on rows the tool did not see.

See the module documentation for the tests, their nulls and what they guarantee. The guarantee needs rows the tool never saw: pass rows held out from its fit, not the rows it searched.

Parameters:

Name Type Description Default
equation Any

The equation, as a sympy expression or a string sympy can read, in the names of X's columns (for instance a PySR model's sympy(), which names the columns x0, x1, ... when it was fitted on an array); or a list of its terms, each tested whole. A list keeps a term such as 2*(x0 + x1) as one, where reading the sum splits it in two.

required
X Any

The held-out rows, one column per input: an array of shape (n_rows, n_inputs) or a pandas DataFrame.

required
y Any

The target on those rows, finite, shape (n_rows,).

required
q float

The false discovery rate level, in (0, 1).

0.1
correction str

"by" (Benjamini-Yekutieli, any dependence) or "bh" (Benjamini-Hochberg, positive dependence), for the terms and for the input test's pairs.

'by'
input_test bool

Also test each variable inside each term of more than one.

False
feature_names Any

The columns' names. Default: a DataFrame's column names, else x0, x1, .... Each name must be a Python identifier.

None
random_state int | None

Seed for the permutations.

0

Returns:

Type Description
EquationScreen

An EquationScreen.

Raises:

Type Description
ValueError

If the arguments are invalid, or the equation uses a name that is not one of the columns.

ImportError

If sympy is not installed.

Stability over splits

beamfeat.stability

How much a fitted equation depends on the split it was fitted on.

A fit prints one equation, found on one random split of its training rows into a search part and a selection part. Where many expressions predict about equally well, another split, or another sample of rows, prints another equation, and nothing in a single fit shows whether the printed one is the discovery or one draw among many equally good ones. stability_report() measures it, as the stability study of the beamfeat paper (TMLR 2026, Appendix E) did, by refitting on many random splits and counting the distinct equations they print.

Splits. Each of n_splits splits divides the rows at random into a training part and a test part of test_size (stratified by class when the estimator classifies). A clone of the estimator, with a random_state of its own, is fitted on the training part: the search, the screen, the parsimony step and the downstream model never see the test rows. The clone is then scored once on the test part. The partitions and the clones' seeds come from a numpy.random.SeedSequence of random_state, one child per split, so a report is the same on every run with the same random_state, whatever n_jobs is, and the first k splits are the same whatever n_splits is.

What varies. By default (resample="splits") each split draws its own partition as well as its own seed. The report then measures split-to-split variability: how far the equation and the score move with another sample of training rows, another test part and another seed, and the spread of the scores includes the variation between test parts. With resample="seeds" every split keeps the partition of the first, and only the clones' seeds differ, as in the paper's study. That measures seed-to-seed variability on fixed data: how far the equation moves with the random search/selection split inside the fit alone, which is the split the guarantee is conditional on, and the scores vary only through it.

Equivalence. Formulas spelled differently can be the same feature: log((x0 * x1)) and (log(x0) + log(x1)), or (x0 - x1) and (x1 - x0). Every selected feature is evaluated on the rows of X, or on 1500 of them drawn at random when there are more, and the target is not used. A feature belongs to the first class, in order of appearance, whose first member it correlates with above 0.999 in absolute value, on at least 50 rows (or on every row, when there are fewer) where both are defined. This is the value-equivalence of the paper's study. It merges rewritings, and rescalings, shifts and sign flips, which a linear model's coefficient and intercept absorb. It also merges near-duplicates whose values agree that closely on the data, such as one expression on two almost identical columns. Identical formulas are always one class, and a feature that cannot be compared, being defined on too few rows or constant on them, shares its class only with identical formulas. An equation is the set of the classes of its features: two splits print the same equation when their features fall in the same classes, whatever the coefficients.

EquationClass dataclass

Printed equations that are one equation, up to equivalence.

Attributes:

Name Type Description
features tuple[int, ...]

The classes of its features, as positions in StabilityReport.features, ascending, so the most frequent first. Empty for the equation of a split that selected no feature.

formulas tuple[str, ...]

The formulas naming those classes, in the same order.

splits tuple[int, ...]

The splits that printed it, ascending.

count property

Number of splits that printed the equation.

FeatureClass dataclass

Selected features that are one feature, up to equivalence.

Attributes:

Name Type Description
formula str

The spelling selected in the most splits, which names the class; the first to appear, among equally frequent ones.

spellings dict[str, int]

Every formula of the class, with the number of splits that selected it, most frequent first.

splits tuple[int, ...]

The splits that selected a feature of the class, ascending.

count property

Number of splits that selected a feature of the class.

SplitResult dataclass

One split of a StabilityReport.

Attributes:

Name Type Description
index int

Position of the split, from 0.

seed int

The random_state the clone was fitted with.

train ndarray

The rows the clone was fitted on, as positions in X, ascending.

test ndarray

The rows it was scored on: every row not in train.

formulas tuple[str, ...]

The selected features' formulas, as formulas() returns them.

equation str | None

The fitted equation, as equation() prints it; None for a transformer, which has none.

score float

The score on the test rows, NaN when it is undefined.

n_undefined int

Test rows on which a selected formula is undefined (outside its domain, or not finite). They leave a regressor's or transformer's score undefined; the classifier predicts its most frequent training class on them, as its predict does.

fdr_controlled bool | None

The clone's fdr_controlled_.

feature_classes tuple[int, ...]

The class of each formula, as a position in StabilityReport.features.

equation_class int

The class of the equation, as a position in StabilityReport.equations.

estimator Any

The fitted clone.

StabilityReport dataclass

What stability_report() returns; print it for the summary.

Attributes:

Name Type Description
estimator Any

An unfitted clone of the estimator the splits refitted.

score_name str

What scores measures: "R^2" or "accuracy", followed for a transformer by the model fitted on its features.

test_size float

The fraction of the rows each split held out.

resample str

"splits", when each split drew its own partition and seed, or "seeds", when they shared one partition and only the seeds differed.

random_state int | None

The seed the splits and the clones' seeds came from.

splits tuple[SplitResult, ...]

One SplitResult per split, in order.

features tuple[FeatureClass, ...]

The distinct features selected, one FeatureClass each, the most frequent first, and in order of first appearance among equally frequent ones.

equations tuple[EquationClass, ...]

The distinct equations printed, one EquationClass each, ordered in the same way.

scores property

The held-out score of each split, NaN where it is undefined.

summary(max_rows=5)

The report as text: scores, equations and features.

Parameters:

Name Type Description Default
max_rows int

Most equations, and most features, listed by name. The equations listed are those printed in more than one split; the rest of either list is counted.

5

Returns:

Type Description
str

The text, ending with the definition of equivalence it counts by.

stability_report(estimator, X, y, *, n_splits=30, test_size=0.25, resample='splits', random_state=0, n_jobs=1)

Refit an estimator on random splits and count the distinct equations.

Each split fits a clone of estimator on a random training part of the rows, with a seed of its own, and scores it once on the remaining test part, which no step of the fit sees. The report counts the distinct equations and features the splits printed, up to the equivalence the module documentation defines, and records the spread of the scores. See the module documentation for how the splits and seeds are drawn, and for what each choice of resample measures.

The score is the estimator's own score on the test part: R^2 for BeamFeatRegressor, accuracy for BeamFeatClassifier. A transformer has no score of its own, so a model is fitted on its features over the training part: for regression a ridge regression on the standardised features, its penalty chosen by leave-one-out cross-validation among 25 values from 1e-4 to 1e4, scored by R^2, as in the paper's stability study; for classification the logistic regression BeamFeatClassifier fits, scored by accuracy. When the transformer selects nothing, the prediction is the training mean or the most frequent training class.

A test row on which a selected formula is undefined leaves the R^2 of a regressor undefined, as its score says by raising, and likewise a transformer's score: that split's score is NaN, and the summary counts it. The classifier predicts its most frequent training class on such a row, as its predict does, and is scored.

Parameters:

Name Type Description Default
estimator Any

A BeamFeatRegressor, BeamFeatClassifier or BeamFeatTransformer, fitted or not. It is cloned and left as it is. Each clone's random_state is the split's seed; every other setting is kept, including a scorer or selector instance's own seed.

required
X array - like

(n_samples, n_features) data. A DataFrame's column names flow into the formulas, as they do in a fit.

required
y array - like

Target, one entry per row of X.

required
n_splits int

Number of splits, at least 2.

30
test_size float

Fraction of the rows each split holds out of its fit and scores on, strictly between 0 and 1. The test part has ceil(test_size * n_samples) rows, as in scikit-learn's ShuffleSplit, and both parts need at least 2.

0.25
resample str

"splits" (default) draws a partition and a seed for each split, and measures split-to-split variability. "seeds" keeps the first split's partition for every split and varies only the seeds, as the paper's stability study did, and measures seed-to-seed variability on fixed data. The seeds are the same either way, so the first split is too.

'splits'
random_state int | None

Seed of the partitions and of the clones' random_state: a non-negative integer, or None for fresh entropy, in which case the report differs from run to run.

0
n_jobs int | None

Splits fitted at the same time, through joblib. 1 (default) fits them one after another in the calling process, -1 uses every core, and None follows an enclosing joblib configuration (joblib.parallel_config, or parallel_backend before joblib 1.3) or else means 1. The workers are processes unless that configuration names another backend. The report is the same for every value. Each clone still runs its own search with the estimator's n_jobs, so parallelise one or the other.

1

Returns:

Type Description
StabilityReport

The StabilityReport.

Raises:

Type Description
TypeError

If estimator is not one of the three estimators.

ValueError

If an argument is out of range, or X and y disagree in length or have too few rows for test_size.

beamfeat.search

Target-guided beam search over the expression DAG.

Exhaustive expansion is the scaling failure of breadth-first feature construction: the candidate count compounds at every depth, and the cost is paid in full before any of it is scored. This module instead expands only a bounded frontier. At each depth, every surviving expression is extended by the available operators, the resulting candidates are scored against the target, and only the best beam_width survive to be extended again.

Two properties keep the beam useful rather than merely small:

Marginal scoring. Once features have been selected, each candidate is scored both against the raw target and against the residual left by the selected features, and ranked on the larger of the two. The residual score rewards a candidate that explains something new; the raw score keeps alive a refinement of an incumbent, such as log(a) when a is already selected, which the residual alone would discard.

Redundancy pruning. Ranking on the larger score lets a beam fill with mutually correlated variants of one expression. Before a candidate is admitted to a depth's beam, its correlation against everything already admitted at that depth is checked, and it is dropped if it reaches redundancy_threshold. The check is within a depth: a candidate that restates a feature from an earlier depth can occupy a beam slot. Such restatements are removed in the final ranking, which applies the same check across all depths.

Magnitude slots (magnitude_slots), off by default here and on by default in the estimators for regression. A part of a law can be uncorrelated with the target, as x0*x1 is with x0*x1*x2 when the inputs are centred, and the score then ranks it among noise. With the option, each depth but the last keeps a few more candidates, those whose magnitude best tracks the target's (see magnitude_scores()), and a first depth too wide to propose every pair proposes those inputs early.

Residual slots (residual_slots), off by default. The final ranking keeps the max_features candidates that score best against the target, and a dominant term fills it with restatements of itself, so that a weaker term beside it, such as log(x3) in x0*x1/x2 + 0.5*log(x3), is cut although the search built it. With the option, the first terms of a greedy forward path through every candidate the search kept join the ranking, each the one that adds most to a least-squares fit of those before it; a restatement adds nothing to the term it restates, and the weaker term comes second. The path also chooses among the transforms of a path term's operand, which a depth may have dropped as near copies of one another.

Memory stays bounded as well. On a wide table one depth can propose hundreds of thousands of candidates. They are evaluated and scored a chunk at a time (chunk_size, by default as many columns as fit in CHUNK_BYTES) and only their scores are kept; the candidates the redundancy pass reaches are evaluated again. Peak memory then depends on the chunk and the beam rather than on the number of candidates. A scorer whose scores depend on the whole batch, such as mutual information, still receives a depth at once.

Search is deterministic: given the same data, parameters, and random_state, the returned features and their order are identical across runs, whatever n_jobs and chunk_size are set to.

BeamSearch

Guided beam search for feature construction.

Parameters:

Name Type Description Default
scorer str | Scorer

Scoring strategy. Either a name ("correlation", "spearman", "mutual_information", "gradient_boosting", or an alias such as "mi" or "rank") or a Scorer instance. Defaults to "correlation"; it and "spearman" are the choices cheap enough for wide beams; see GradientBoostingScorer for the tradeoff.

'correlation'
problem_type ProblemType

"regression" or "classification".

'regression'
max_depth int

Maximum expression depth. Depth 1 permits single transforms and pairwise combinations of inputs; each further depth composes on the results of the last.

2
beam_width int

Expressions retained at each depth. This is the parameter that bounds cost: each depth applies the operators to the beam and pairs it with every expression kept so far, so the work grows polynomially in beam_width and max_depth rather than compounding with depth.

50
max_features int | None

Maximum features returned by score. Defaults to beam_width; residual_slots adds up to that many more.

None
unary_ops Sequence[str]

Unary operators to apply. Defaults to log, sqrt, reciprocal, square, and abs.

DEFAULT_UNARY
binary_ops Sequence[str]

Binary operators to apply. Defaults to mul, div, add, sub.

DEFAULT_BINARY
redundancy_threshold float

Absolute correlation at or above which a candidate is considered a duplicate of one already admitted at the same depth and dropped. The final ranking applies the same threshold across depths. 1.0 drops only exact affine or sign-flipped copies.

0.95
include_originals bool

Whether input columns are eligible for the final result alongside constructed expressions.

True
max_candidates_per_depth int

Hard ceiling on candidates constructed at one depth, as a guard against a wide beam and many operators producing an unaffordable round. Candidates beyond the ceiling are not proposed. When the ceiling binds, parents are traversed in score order, so the truncation falls on the least promising ones; at depth 1 the parents are the input columns, ranked by their score against the target.

200000
random_state int | None

Seed passed to the scorer. Search itself is deterministic.

0
verbose int

Progress reporting to stdout. 0 is silent, 1 prints a single summary line for the search, 2 adds a line per depth.

0
n_jobs int | None

Workers that evaluate and score a depth's candidates, chunk by chunk, through joblib. 1 (the default) works in the calling thread, -1 uses every core, and None follows the active joblib configuration (joblib.parallel_config, or parallel_backend before joblib 1.3) or else means 1. Workers are threads, since numpy releases the GIL, except for GradientBoostingScorer, whose model fits run in worker processes; a whole-batch scorer such as MutualInformationScorer receives n_jobs through the joblib backend instead. Depths of fewer than MIN_PARALLEL_CANDIDATES candidates are scored in the calling thread unless the scorer fits models. The result does not depend on this value.

1
chunk_size int | None

Candidates evaluated and scored together. Bounds the candidate values held at once to chunk_size * n_rows per worker, rather than one column per candidate of the whole depth. Defaults to as many columns as fit in CHUNK_BYTES. Scorers whose scores depend on the whole batch, such as MutualInformationScorer, still score a depth at once (see scores_by_column()). The result does not depend on this value.

None
max_inputs int | None

Most distinct input columns one expression may use. Candidates over the limit are rejected as they are constructed, before evaluation. Input columns themselves always pass. None (default) sets no limit. An expression of depth d uses at most 2d columns, so a value of 2max_depth or more has no effect. Set it at or above the number of inputs the laws you look for need: one that needs more cannot be built, and the search returns the best expression within the limit instead.

None
fitted_ops Sequence[str]

Parametric operators whose constant is fitted to the data, from "exp_scaled" (exp(a*x)), "pow" (x^a, for positive x), "inv_shift" (1/(x + a)), "log_shift" (log(x + a)) and "sign_shift" (sign(x + a), the threshold between the operand's 5% and 95% quantiles). Empty by default, which leaves every expression free of constants. At each depth, each operator is fitted to each expression of the previous depth's beam (at the first depth, the beam_width best input columns), and to the previous depth's beam_width best candidates that the redundancy check kept out of the beam; the fitted expressions join that depth's candidates, to be scored, pruned and kept like the rest; they are not counted against max_candidates_per_depth. The constant maximises the absolute correlation with the target, alone and, while the depth limit leaves room for a product, as a factor of an expression in the beam, and is snapped to a simple value such as 1/2 when the data cannot tell the two apart; see beamfeat.parametric. A fitted pole keeps a margin from the data, and pow fits a negative power, whose pole is at 0, only where the operand stays more than that margin above 0 (see pole_margins()). At the end, a kept expression with fitted constants gives way to a near copy with fewer when the snapping test fails to reject the null that the copy fits as well, so that log(x0) is returned rather than (x0)^(-0.02). The fit sees only the rows the search is given.

()
magnitude_slots int

Beam slots added at each depth for candidates ranked by how well their magnitude tracks the target's, for laws whose parts do not correlate with the target. 0 (default) adds none and leaves the search unchanged. With centred inputs, x0 and x1 do not correlate with x0*x1, nor does x0*x1 with x0*x1*x2, so the ranking by score leaves them among noise; but the magnitude of a factor tracks the magnitude of the product. The magnitude score of a candidate c is the absolute correlation of log(1 + |c|/rms(c)) with the same transform of the centred target, or of its residual on the expressions kept so far, whichever is larger; rms is the root mean square. When those expressions outnumber a quarter of the rows, the residual on that many of the best-scoring ones counts too: a residual on as many columns as rows is empty. After the beam_width candidates the score keeps, up to this many more are kept from those it left out, best magnitude score first and subject to the same redundancy check, at every depth but the last, which has no next depth to build on. At the first depth, when max_candidates_per_depth can bind, the inputs are proposed in an order that interleaves their magnitude ranking with their score ranking, at a share of magnitude_slots / (beam_width + magnitude_slots) and starting with the best magnitude score, so that a pair of inputs neither of which correlates with the target is still proposed. Regression only: a class label carries no magnitude. The score sees only the rows the search is given, and of more than MAGNITUDE_ROWS of them, that many evenly spaced.

0
residual_slots int

Places added to the final ranking for the first terms of a greedy forward path through every candidate the search kept, each the one that most increases the R^2 of a least-squares fit on those before it; 0 (default) adds none. A dominant term fills the ranking by score with restatements of itself, and a weaker term beside it is cut; a restatement adds nothing to a fit that holds the term it restates, so the path takes the weaker term next. A path term takes the place of a ranked candidate that is a near copy of it, and is dropped if it is a near copy of an earlier path term; the ranking otherwise keeps every candidate the score kept. At most a quarter of the rows. Before the final path, the operand of each path term that is an input column or a transform of one operand, and that operand's transforms by unary_ops, join the candidates: transforms of one operand can correlate past redundancy_threshold, as log(x), sqrt(x) and 1/x do on a positive range of small spread, and a depth then keeps only the best-scoring of them. Regression only. The path sees only the rows the search is given, and of more than RESIDUAL_ROWS of them (fewer on a wide table, so that the candidate values stay within RESIDUAL_BYTES, but at least MAGNITUDE_ROWS), that many evenly spaced.

0

Attributes:

Name Type Description
result_ SearchResult | None

SearchResult from the most recent run().

run(data, target, columns=None, units=None, evaluator=None)

Execute the search.

Parameters:

Name Type Description Default
data Any

Mapping of column name to array, or a 2-D array. Ignored if evaluator is supplied.

required
target ndarray

Target vector, one entry per row.

required
columns Sequence[str] | None

Column names, when data is a 2-D array.

None
units dict[str, Any] | None

Optional mapping of column name to pint quantity. Supplying units restricts the search to dimensionally valid expressions.

None
evaluator Evaluator | None

A pre-built Evaluator, to reuse a warm cache across runs.

None

Returns:

Type Description
SearchResult

A SearchResult. Also stored on result_.

SearchResult dataclass

Outcome of a completed beam search.

Attributes:

Name Type Description
nodes list[Node]

Selected expressions, ordered best-scoring first.

scores ndarray

Score against the raw target for each entry of nodes, in the same order.

trace list[SearchTrace]

Per-depth SearchTrace records.

evaluation_log EvaluationLog | None

Rejections recorded during evaluation, for auditing.

n_proposed_total int

Candidates constructed across depths 1 and above. The input columns are not counted; trace[0] records them.

n_evaluated_total int

Of those, the candidates that survived evaluation and were scored. The input columns are likewise not counted.

n_rejected_redundant_final int

Accumulated features dropped as near-duplicates in the final ranking across depths.

elapsed float

Total wall-clock seconds.

names property

Formula strings for the selected expressions.

summary()

Multi-line human-readable summary of the run.

SearchTrace dataclass

Per-depth record of what the search did.

Exposed so that the cost of a run can be attributed rather than guessed, and so that a beam that collapsed or saturated is visible after the fact.

Attributes:

Name Type Description
depth int

Search depth this record describes; depth 0 is the input columns.

n_proposed int

Candidates constructed at this depth, before evaluation.

n_evaluated int

Candidates that survived evaluation.

n_rejected_units int

Candidates rejected at construction for unit mismatch.

n_rejected_numeric int

Candidates rejected during evaluation.

n_rejected_redundant int

Candidates dropped for redundancy against the beam.

n_kept int

Candidates retained in the beam.

best_score float

Highest ranking score among the candidates kept at this depth. At depth 0 this is the score against the raw target.

elapsed float

Wall-clock seconds spent at this depth.

n_rejected_constraints int

Candidates rejected at construction by max_inputs; 0 when it is not set.

n_fitted int

Of the candidates proposed, those carrying a constant fitted at this depth (see fitted_ops on BeamSearch).

n_magnitude int

Of the candidates kept, those kept for their magnitude score in the slots magnitude_slots adds; 0 when it is not set.

magnitude_scores(candidates, references, stats=None)

How well each candidate's magnitude tracks a reference's, at best.

Each column c is transformed to log(1 + |c|/rms(c)), where rms is its root mean square, and scored by its largest absolute correlation with any of references, which are standardised transforms of the same kind (see magnitude_slots on BeamSearch). The logarithm turns a product into a sum, so the magnitude of a factor correlates with the magnitude of the product even when the factor itself does not correlate with it; the 1 inside it treats magnitudes far below the column's scale alike, so that rows where a product nears zero, and the noise there, do not dominate, and it compresses a heavy tail. The score does not change when a column is scaled or changes sign.

Each column is transformed, standardised and reduced on its own, so a score does not depend on the other columns it is computed with.

Parameters:

Name Type Description Default
candidates ndarray

(n_samples, n_candidates) candidate values.

required
references Sequence[ndarray]

Standardised reference vectors of length n_samples.

required
stats ColumnStats | None

Optional column_stats() of candidates, when the caller has them already.

None

Returns:

Type Description
ndarray

(n_candidates,) scores in [0, 1]; 0 for a column that is zero

ndarray

throughout or not finite.

beamfeat.parametric

Fitting the constant of a parametric operator.

A parametric operator, such as exp_scaled (exp(a*x)) or inv_shift (1/(x + a)), carries one constant. fit_constants() chooses it for a given operand by a one-dimensional search: a coarse grid from the operator's constant_grid, then a golden-section refinement between the grid neighbours of the best point. fit_constants_many() fits many operands at once: the refinements and the snapping run side by side, one array operation per step for all of them, which is what a search fitting hundreds of operands needs.

Objective. The constant maximises the absolute Pearson correlation of the transformed operand with the target, whatever scorer the search uses. Correlation is smooth in the constant and costs one pass over the rows, so the fit stays cheap for any scorer; the configured scorer then ranks the fitted node against every other candidate. Correlation is also what the final linear model rewards: a feature with correlation r leaves a fraction 1 - r^2 of the target's variance unexplained on its own.

A constant is often only identifiable in context: 1/(x0*x1 + a) is the denominator of (x0 + x1)/(1 + x0*x1), and alone it correlates best with the target as a approaches the pole. When the caller passes partners (expressions the result may be multiplied by), the fit is therefore also run on the product with each, and the constant best for the best partner is returned beside the one best alone. BeamSearch proposes the node with each constant, and the product with its partner, as candidates to be scored like any other.

Discarded fits. A fit whose best grid point is the end of a grid segment ran into a bound -- the margin a shift keeps between its pole and the data (see pole_margins()), the smallest positive power when the operand comes within that margin of 0 (the pole of a negative power), the linear limit of a small scale, the step limit of a large one, or the outermost quantile a threshold of sign_shift may take -- and is discarded, as is one whose values are not finite, constant, or outside the operator's domain. Snapping and rounding stay within the same bounds, so a simple constant never moves a pole closer to the data than the margin. And since every operator but sign_shift tends to an affine function of its operand at one end of its range (a small scale, a distant shift, a power of 1), a fit is also discarded unless the likelihood-ratio test below rejects the null that the operand itself, or for a product the partner alone, fits as well; otherwise the constant only fits noise. A threshold of sign_shift is held to the same test.

Snapping. The data rarely pin a constant to more digits than they support, and exp(-0.49991*x^2) is a worse answer than exp(-x^2/2). After the refinement, the simple values of SNAP_VALUES (0, +-1, +-2, +-3, +-1/2, +-3/2, +-1/3, +-1/4) are tried. For each, a likelihood-ratio test asks whether the data reject the null that the constant takes that value, and the simplest value it fails to reject is used: the smallest denominator, then the best fit. The test is for a least-squares fit of the target on the feature: with L(a) = 1 - r(a)^2 the unexplained fraction and n the rows, it fails to reject when n * log(L(simple) / L(optimum)) is at most SNAP_LR, the 99.9% point of a chi-squared variable with one degree of freedom, so it runs at level 0.001. A tolerance stated this way scales with the noise and the sample: on near-noiseless data the test fails to reject only a value that fits essentially as well as the optimum, on noisy data a wider range, as it should. A fixed tolerance on |r| cannot do both; at 0.1% noise, r is within 1e-6 of 1 and a tolerance of 1e-4 would snap to a constant that leaves a hundred times the noise unexplained. The 99.9% point rather than the 95% one makes the simpler constant the default: the null for a law's true constant is falsely rejected, a Type I error, in one fit in a thousand rather than one in twenty. If the test rejects every simple value, the constant is rounded to the fewest significant digits (up to six) that cost at most ROUND_LR, so that the printed constant is the stored one.

Everything here is deterministic.

FittedConstant

Bases: NamedTuple

A constant returned by fit_constants().

Attributes:

Name Type Description
value float

The constant.

partner int | None

Column of partners whose product with the operator the constant was fitted for, or None for the operator alone.

fit_constants(spec, operand, target, partners=None)

Fit the constant of a parametric operator to one operand.

Parameters:

Name Type Description Default
spec OperatorSpec

A parametric operator (one with a constant_grid).

required
operand ndarray

The operand's values on the search rows.

required
target ndarray

The target, centred and scaled to unit variance, as prepare() returns it.

required
partners ndarray | None

Optional (n_rows, n_partners) matrix of expressions the result may be multiplied by later. When given, the constant that best fits the product with the best partner is returned as well.

None

Returns:

Type Description
list[FittedConstant]

At most two fitted constants: the one best for the operator alone,

list[FittedConstant]

then the one best in a product, each omitted when its fit ran into

list[FittedConstant]

a bound or produced no valid values. The two may have equal values.

fit_constants_many(spec, operands, target, partners=None, with_partners=None)

fit_constants() for each column of operands, fitted together.

The result for a column is the one fit_constants() gives it, with partners when with_partners is None or true for that column and without them otherwise.

Parameters:

Name Type Description Default
spec OperatorSpec

A parametric operator.

required
operands ndarray

(n_rows, n_operands), one operand per column.

required
target ndarray

The standardised target.

required
partners ndarray | None

Optional (n_rows, n_partners) matrix, as for fit_constants().

None
with_partners Sequence[bool] | None

Per operand, whether to fit the product with a partner too.

None

Returns:

Type Description
list[list[FittedConstant]]

One list of fitted constants per operand.

Scoring

beamfeat.scoring

Candidate scoring strategies for guided beam search.

A Scorer answers one question: how useful is this candidate feature, given the target and the features already selected? The "given the features already selected" part is what keeps a beam from filling with near-duplicates of the same underlying signal, which is the dominant failure mode of scoring candidates in isolation.

Four strategies are provided, trading signal quality against cost:

CorrelationScorer Absolute Pearson correlation against the residual left by the incumbent features. Cheapest by a wide margin; detects only monotone-linear relationships to the residual, but that is often enough to find a feature whose nonlinearity is already baked into its expression.

SpearmanScorer Absolute rank correlation against the same residual. One sort per column dearer than Pearson; sees any monotone relationship and is insensitive to outlying values.

MutualInformationScorer Nearest-neighbour mutual information between candidate and residual. Detects nonmonotone dependence that correlation misses, at roughly one to two orders of magnitude more compute.

GradientBoostingScorer Measured out-of-fold improvement in predictive performance when the candidate is added to the incumbent set. The most faithful signal, since it scores what is actually being optimised, and the most expensive.

All scorers are deterministic given a random_state, and all handle the empty-incumbent case (the first beam round, where there is no residual yet) by scoring against the raw target.

A scorer whose score for a candidate depends on that candidate's column alone declares itself separable. A round can then be scored in pieces: prepare() handles the target and the incumbents once, and score_prepared() scores any chunk of candidates against the result, reusing the ColumnStats computed when the chunk was evaluated. The scores equal those of score_batch() on the whole round, which is how the search keeps its memory bounded.

ColumnStats

Bases: NamedTuple

Per-column summary shared by evaluation, scoring and standardisation.

Attributes:

Name Type Description
mean ndarray

Mean of each column.

variance ndarray

Mean squared deviation of each column, as numpy.var().

magnitude ndarray

Mean absolute value of each column.

take(index)

Statistics of the columns selected by index.

CorrelationScorer

Bases: Scorer

Absolute Pearson correlation with the residualised target.

The cheapest scorer, and the default. Each candidate costs one standardisation and one dot product against the residual, so scoring is linear in the batch size and handles beam widths in the thousands without difficulty.

The apparent weakness — that Pearson correlation sees only linear relationships — matters less here than it would elsewhere. A candidate such as log(a) / sqrt(b) already encodes its nonlinearity in the expression itself, so a linear scorer applied to the transformed column still detects it. What this scorer genuinely misses is nonmonotone dependence between a candidate and the residual, such as a candidate tracking the residual's magnitude but not its sign.

Parameters:

Name Type Description Default
problem_type ProblemType

"regression" or "classification".

'regression'
random_state int | None

Unused; accepted for interface uniformity.

0

GradientBoostingScorer

Bases: Scorer

Out-of-fold predictive improvement from adding the candidate.

Fits a small gradient-boosted model on the incumbent set, then on the incumbent set plus each candidate, and scores the candidate by the improvement in cross-validated performance. This is the only scorer that measures the quantity actually being optimised, and correspondingly the only one whose ranking cannot be fooled by a statistic that correlates with the target without improving prediction.

The cost is substantial and grows with the candidate count: one model fit per candidate per fold, so a wide beam over hundreds of candidates can run for minutes where correlation scoring takes milliseconds. It is practical only with a narrow beam (roughly 15 or below) and a bounded subsample_size; the estimators apply a single scorer throughout the search, so there is no cheaper-scorer-first pass to reserve it for.

Parameters:

Name Type Description Default
problem_type ProblemType

"regression" or "classification".

'regression'
random_state int | None

Seed for the estimator and fold assignment.

0
n_folds int

Number of cross-validation folds.

3
max_iter int

Boosting iterations per fit. Kept low deliberately; this is a ranking signal, not a final model.

40
max_depth int

Tree depth per fit.

3
subsample_size int | None

If set, score on a random subsample of this many rows rather than the full data. The single most effective way to make this scorer affordable.

2000

MutualInformationScorer

Bases: Scorer

Nearest-neighbour mutual information with the residualised target.

Detects dependence that correlation cannot, including nonmonotone relationships. The estimator is the Kraskov-style k-nearest-neighbour method from scikit-learn, which is nonparametric but noticeably slower than a dot product; expect roughly one to two orders of magnitude more time than CorrelationScorer.

For classification, mutual information is computed against the class labels directly rather than against a residual, since a least-squares residual of a categorical target is not meaningful. This means the classification path scores absolute rather than marginal relevance, so redundancy control falls to the search layer's redundancy pass (redundancy_threshold).

Parameters:

Name Type Description Default
problem_type ProblemType

"regression" or "classification".

'regression'
random_state int | None

Seed for the estimator's tie-breaking noise. Fixed by default so scores are reproducible.

0
n_neighbors int

Neighbourhood size for the estimator. Smaller values reduce bias and increase variance.

3

Cost and variance caveat: k-nearest-neighbour mutual-information estimation is orders of magnitude slower than correlation scoring and high-variance at moderate sample sizes, so a wide beam over thousands of candidates can both blow the time budget and rank on estimator noise. Prefer it for narrow searches where non-monotone structure is suspected.

Scorer

Bases: ABC

Base class for candidate scoring strategies.

Subclasses implement score_batch(). Scores are compared only against one another within a single beam round, so their absolute scale is unconstrained; only the ordering matters. Higher is better, and scores must be non-negative and finite.

name = 'scorer' class-attribute instance-attribute

Human-readable identifier, used in logs and reports.

separable = False class-attribute instance-attribute

Whether each candidate's score depends on its own column alone, so that a batch scored in pieces receives the scores it would receive whole. Declared by the class that defines score_batch(); a subclass that overrides score_batch() without declaring it is scored whole.

prepare(target, incumbent=None)

Compute the target-side state shared by every candidate in a round.

Only separable scorers implement this; see scores_by_column().

Parameters:

Name Type Description Default
target ndarray

(n_samples,) target vector.

required
incumbent ndarray | None

Optional (n_samples, n_selected) matrix of features already selected.

None

Returns:

Type Description
Any

An opaque value to pass to score_prepared().

score(candidate, target, incumbent=None)

Score a single candidate. Convenience wrapper over score_batch().

score_batch(candidates, target, incumbent=None) abstractmethod

Score every candidate column against the target.

Parameters:

Name Type Description Default
candidates ndarray

(n_samples, n_candidates) matrix of candidate feature values.

required
target ndarray

(n_samples,) target vector.

required
incumbent ndarray | None

Optional (n_samples, n_selected) matrix of features already selected. Scorers use this to measure marginal value, so that a candidate duplicating an incumbent scores near zero.

None

Returns:

Type Description
ndarray

(n_candidates,) array of non-negative finite scores.

score_prepared(candidates, prepared, stats=None)

Score candidate columns against state from prepare().

Parameters:

Name Type Description Default
candidates ndarray

(n_samples, n_candidates) matrix of candidate feature values.

required
prepared Any

The value prepare() returned.

required
stats ColumnStats | None

Optional column_stats() of candidates, when the caller has them already.

None

Returns:

Type Description
ndarray

(n_candidates,) array, equal to what score_batch() gives

ndarray

for the same candidates, target and incumbent.

scores_by_column()

Whether a batch may be split into pieces and scored piece by piece.

True only when the class that defines score_batch() declares separable; the search then scores candidates in bounded chunks through prepare() and score_prepared(), and scores a batch whole otherwise.

SpearmanScorer

Bases: CorrelationScorer

Rank correlation: Pearson on the rank-transformed candidate and target.

Invariant to monotone transforms of either variable and insensitive to outliers in the tails, so it is the natural choice when the relationship is monotone but nonlinear, or when heavy-tailed values would let a few extreme rows dominate a product-moment correlation. It shares the structural limits of any single-column score: a non-monotone relationship (a symmetric bump) and a marginally-quiet-but-jointly-essential feature are both invisible to it, exactly as to Pearson.

Residualisation follows CorrelationScorer; ranks are taken after residualising, so the score measures monotone association with what the incumbent set has not explained. Tied values share their average rank, so a score never depends on row order; a constant candidate, or an incumbent set that explains the target exactly, scores zero, and a candidate with a non-finite value scores zero, as under CorrelationScorer.

For classification only the candidates are ranked. A classification residual is a label minus a fitted function of the incumbents, so within each class its order is set by the incumbents alone; ranking it would turn that order into signal, and a copy of an incumbent would score well. Without incumbents the two coincide, since the ranks of a binary residual are an affine function of it.

Leverage caveat: rank transformation hides magnitudes, so a feature with a near-singularity (a reciprocal or logarithm evaluated close to its pole) can rank-correlate well while carrying extreme values that destabilise the downstream least-squares fit. The estimators' holdout fit check (DegenerateFitWarning) flags the resulting failures; treat that warning seriously when this scorer is selected.

column_stats(values)

Mean, variance and magnitude of every column of a 2-D array.

Each column is reduced as a contiguous vector, so every statistic equals the one computed from that column on its own, to the last bit; reducing along the rows of a row-major matrix sums in a different order. Overflow is not reported: it shows up as an infinite variance.

is_constant(values)

Whether a column carries no variation a scorer can use.

Constancy is judged relative to the values' magnitude rather than by an absolute floor on the spread, since an absolute floor makes the verdict depend on the column's units: a product of small-unit columns sits at the product of their magnitudes and lands under any fixed floor while carrying real signal. A spread twelve orders below the magnitude is far inside accumulated float64 rounding noise, so nothing informative is discarded.

Exposed so that a caller screening a wide table can apply the same test the estimator applies, and so that the diagnostic reported at fit time cannot drift from the behaviour it describes.

make_scorer(scorer, problem_type='regression', random_state=0, **kwargs)

Resolve a scorer name or instance into a Scorer.

Parameters:

Name Type Description Default
scorer str | Scorer

A scorer name ("correlation", "spearman", "mutual_information", "gradient_boosting", or an alias such as "mi" or "rank"), or an already-constructed Scorer, which is returned unchanged.

required
problem_type ProblemType

Passed to the constructed scorer. An instance keeps its own problem type; a warning is issued when it differs from this one.

'regression'
random_state int | None

Passed to the constructed scorer.

0
**kwargs Any

Additional scorer-specific arguments.

{}

Returns:

Type Description
Scorer

A Scorer instance.

Raises:

Type Description
ValueError

If scorer names no known strategy, or problem_type is not recognised.

TypeError

If scorer is neither a string nor a Scorer.

Selection

beamfeat.selection

False-discovery-rate controlled feature selection.

Feature construction proposes far more candidates than any dataset can support. Each candidate carries its own null hypothesis, and the selected features are those whose nulls a selector rejects. This module provides selectors that control the false discovery rate — the expected proportion of rejected nulls that are true, that is, of selected features that are spurious — and is explicit about the assumptions under which each guarantee holds.

PermutationSelector (default) A permutation test of marginal association, corrected for multiplicity. The test statistic is a fixed function of the data (|Pearson correlation| for regression, eta-squared for classification), so permuting the target yields p-values valid in finite samples for the null hypothesis that a feature is marginally independent of the target (Phipson & Smyth, 2010). Multiplicity is handled by Benjamini-Hochberg, valid under positive regression dependence, or Benjamini-Yekutieli, valid under arbitrary dependence (Benjamini & Yekutieli, 2001). This class defaults to the former; the estimators default to the latter, since engineered candidates share parents and positive dependence cannot be assumed.

The marginal null composes correctly with constructed features: two
near-duplicate expressions of one true signal are *both* genuinely
associated with the target, so selecting both is not a false discovery
under this null. De-duplication is the job of the redundancy pass, not
the error-control procedure.

KnockoffSelector The knockoff filter. Two constructions are provided and routed automatically:

- **Fixed-X** (Barber & Candès, 2015), used when ``n > 2p``. Treats the
  design as fixed and makes *no distributional assumption about the
  features* — deterministic engineered columns are fine. The guarantee
  requires the linear model ``y = X beta + noise`` with Gaussian,
  homoskedastic noise, and a design of full column rank, and a statistic
  that sees the data only through ``[X X~]' [X X~]`` and ``[X X~]' y``;
  the lasso-path entry statistic used here is one. Columns that
  are constant or linearly dependent on earlier ones are left out of the
  construction and cannot be selected (see `KnockoffSelector`).
- **Model-X Gaussian** (Candès et al., 2018), used when ``n <= 2p``, or
  on request. Requires the features to be jointly Gaussian, which
  engineered features are not, so a warning is recorded whenever it
  runs.

The estimators' certify_test="conditional" re-tests the terms they return with a Freedman-Lane permutation test of each term given the others. It is not a screen and is not exported; its null and the assumptions behind it are stated with that parameter and on the guarantees page. The estimators' input_test=True tests, for each column a candidate reads, the null that the column is independent of the target and of the candidate's other columns, by permuting that column alone; it is not exported either.

Selective inference caveat. Every guarantee above is for testing a candidate set that is fixed before seeing the data used for testing. If candidates were chosen by a search on the same data — chosen, in part, because they correlate with this sample's target — the p-values are optimistically biased and the nominal FDR is not guaranteed. The estimators in beamfeat.estimators therefore hold out a split of the training data for selection by default; see selection_holdout.

References

Barber, R. F. & Candès, E. J. (2015). Controlling the false discovery rate via knockoffs. Annals of Statistics, 43(5), 2055-2085.

Benjamini, Y. & Hochberg, Y. (1995). Controlling the false discovery rate. JRSS-B, 57(1), 289-300.

Benjamini, Y. & Yekutieli, D. (2001). The control of the false discovery rate in multiple testing under dependency. Annals of Statistics, 29(4), 1165-1188.

Candès, E., Fan, Y., Janson, L. & Lv, J. (2018). Panning for gold: model-X knockoffs. JRSS-B, 80(3), 551-577.

Ke, Z. T., Liu, J. S. & Ma, Y. (2024). Power of knockoff: the impact of ranking algorithm, augmented design, and symmetric statistic. JMLR, 25, 1-67.

Liu, J. & Rigollet, P. (2019). Power analysis of knockoff filters for correlated designs. NeurIPS 32, 15420-15429.

Phipson, B. & Smyth, G. K. (2010). Permutation p-values should never be zero. Stat. Appl. Genet. Mol. Biol., 9(1), Article 39.

KnockoffSelector

Bases: Selector

Knockoff filter with automatic fixed-X / model-X routing.

Fixed-X (Barber & Candès, 2015) is used when n > 2p. The design is treated as fixed, so no assumption about the distribution of the features is required — deterministic engineered columns are admissible. The finite-sample FDR guarantee (with offset=1) requires the linear model y = X beta + eps with i.i.d. Gaussian noise, and a design of full column rank.

Statistic. On the fixed-X path for regression, the signed maximum of the lasso path: W_j = max(Z_j, Z~_j) * sign(Z_j - Z~_j), where Z_j is the penalty at which column j first enters the path. It depends on the data only through the Gram matrix of originals and knockoffs and their inner products with the target, as the fixed-X guarantee requires. Elsewhere — model-X, where any statistic that swaps sign with the pair is valid, and the heuristic classification path — it is the difference of cross-validated lasso (or L1-logistic) coefficient magnitudes. Versions up to 0.5.0 used that difference on the fixed-X path too, where cross-validation looks at individual rows and the guarantee did not strictly cover it.

How far each knockoff is from its original. Both constructions set the correlation of column j with its knockoff to 1 - s_j; the larger s_j, the easier the lasso tells them apart. s_method chooses s. "equicorrelated" (default) uses one value, s_j = min(1, 2 lambda_min), so a single tight pair of columns shrinks s for every column. "ci" (conditional independence; Liu & Rigollet, 2019) uses s_j = c / (Sigma^-1)_jj, i.e. c times the share of column j that the other columns do not explain, with the largest c <= 1 the construction allows. Constructed candidates come in groups of near-copies (x, x^2, log x), and there "ci" keeps s large for the columns outside the tightest group. Ke et al. (2024) found it more powerful than equicorrelated knockoffs on block and factor designs; in benchmarks/knockoff_s_method.py the gain was on constructed columns, while Gaussian block and factor designs came out about equal. Both satisfy the exchangeability identities, so the guarantee is the same.

Rank-deficient designs. When the design covariance has an eigenvalue below 1e-6 — a constant column, a duplicate, or a column that is a linear combination of others, all common among constructed candidates — every valid knockoff of the columns involved equals the column itself, and the equicorrelated s makes every knockoff nearly equal its original. The lasso statistic is then decided by its tie-breaking between identical columns, which favours the originals, so knockoff+ selects nulls. The model-X construction fails the same way. Columns are therefore dropped, latest first, until the remaining covariance is well conditioned; the dropped columns get the statistic W = 0, so they cannot be selected, and the warning lists them. The guarantee then covers the retained columns, and the fixed-X / model-X routing uses their count.

Model-X Gaussian (Candès et al., 2018) is used when n <= 2p, where the fixed-X construction does not exist, or when construction is "gaussian". It requires the features to be jointly Gaussian, an assumption engineered features violate, and a warning is recorded whenever it runs. Prefer PermutationSelector in that regime.

Power and the offset. offset=1 requires (1 + #negatives)/#positives <= target_fdr, unsatisfiable with fewer than 1/target_fdr features regardless of signal; measured on a 25-feature Gaussian design at level 0.1, offset=1 recovered almost nothing while offset=0 recovered everything. offset=1 remains the default because it is the stated finite-sample guarantee; a warning fires when the design is too narrow for it.

Parameters:

Name Type Description Default
target_fdr float

Nominal false discovery rate.

0.1
problem_type ProblemType

"regression" or "classification". The fixed-X guarantee is stated for regression; classification uses the same machinery heuristically and records a warning.

'regression'
random_state int | None

Seed (used by the model-X sampler and the orthogonal complement basis).

0
offset Offset

1 for knockoff+ (default), 0 for the modified-FDR filter.

1
shrinkage float

Ridge term added to the covariance diagonal for numerical stability.

1e-06
construction Literal['auto', 'fixed', 'gaussian']

"auto" (default), "fixed", or "gaussian".

'auto'
s_method Literal['equicorrelated', 'ci']

"equicorrelated" (default) or "ci"; see above.

'equicorrelated'
warn_on_violation bool

Whether to check assumptions and record findings.

True

PermutationSelector

Bases: Selector

Permutation test of marginal association, with FDR correction.

Statistic. For regression, the absolute Pearson correlation between each feature and the target; for classification, eta-squared (the between-class share of each feature's variance). Both are fixed functions of (X_j, y), which is the condition for a permutation test to be valid: comparing the observed statistic to the same statistic computed on (X_j, pi(y)) over random permutations pi yields a valid p-value for the null that X_j is marginally independent of y, via the add-one estimator (1 + #exceedances) / (B + 1) (Phipson & Smyth, 2010). Statistics that re-tune themselves on the observed target — a cross-validated lasso penalty, for instance — do not satisfy this condition unless the tuning is repeated inside every permutation.

What the null means for constructed features. Marginal independence is the appropriate null here: an expression that genuinely co-varies with the target is a true discovery even if another selected expression carries the same information. Redundancy among true discoveries is resolved by the redundancy pass in the search, not by the error-control procedure.

Multiplicity. Benjamini-Hochberg by default, which controls FDR under positive regression dependence; set correction="by" for the Benjamini-Yekutieli procedure, valid under arbitrary dependence at the cost of a log(m)-factor in power.

Resolution. The smallest attainable p-value is 1/(B + 1), and the leading feature has to reach the threshold its correction sets: target_fdr / m under Benjamini-Hochberg, and target_fdr / (m c(m)) under Benjamini-Yekutieli, where c(m) = sum_{j<=m} 1/j. B therefore must be at least m / target_fdr - 1 in the first case and c(m) times that in the second for the null of a lone leading feature to be rejectable at all, and one further null exceedance doubles the requirement. When auto_permutations is on (default), B is raised to twice the bound belonging to the configured correction — satisfiable with headroom for a single exceedance — capped at max_permutations. The requirement binds hardest when few candidates reach the floor together: several tied true signals relax the threshold by their count, whereas a single one carries it alone. Because the statistic is a chunked matrix product, the larger counts remain inexpensive; raising B ninefold on a 4088-column problem left the fit time unchanged within noise.

Parameters:

Name Type Description Default
target_fdr float

Nominal false discovery rate.

0.1
problem_type ProblemType

"regression" or "classification".

'regression'
random_state int | None

Seed for the permutation draws.

0
n_permutations int

Minimum number of permutations.

2000
auto_permutations bool

Raise B to the satisfiability bound when needed.

True
max_permutations int

Hard cap on B.

1000000
correction Literal['bh', 'by']

"bh" (Benjamini-Hochberg, default) or "by" (Benjamini-Yekutieli, arbitrary dependence).

'bh'

SelectionResult dataclass

Outcome of a selection run.

Attributes:

Name Type Description
selected ndarray

Indices of the selected features, ascending.

statistics ndarray

Importance statistic per feature. For the permutation selector this is 1 - p_value so that larger is better; for knockoffs it is the antisymmetric statistic W.

p_values ndarray | None

Permutation p-values, valid in finite samples, where the method produces them.

q_values ndarray | None

The p-values adjusted by the selector's step-up correction (Benjamini-Hochberg or Benjamini-Yekutieli); a feature is selected when its q-value is at most target_fdr. None where the method computes no p-values.

threshold float

The data-dependent cut applied to statistics. inf means nothing met the criterion.

target_fdr float

The nominal FDR level requested.

n_candidates int

Number of features considered.

method str

Name of the selector used.

warnings_raised list[str]

Assumption or configuration issues detected.

n_selected property

Number of features selected.

mask()

Boolean mask over the candidate features.

summary()

Human-readable summary of the run.

Selector

Bases: ABC

Base class for FDR-controlled selectors.

select(features, target) abstractmethod

Select features controlling the FDR at target_fdr.

knockoff_threshold(statistics, target_fdr, offset=1)

Data-dependent threshold of the knockoff filter.

Finds the smallest positive cut t at which (offset + #{W_j <= -t}) / #{W_j >= t} <= target_fdr. offset=1 gives knockoff+ (finite-sample FDR control); offset=0 controls a modified FDR.

make_selector(selector, target_fdr=0.1, problem_type='regression', random_state=0, **kwargs)

Resolve a selector name or instance into a Selector.

An instance is returned as it is: its own settings (target_fdr among them) apply, and the other arguments here are not used.

Expressions

beamfeat.expression

Expression DAG with structural hashing, lazy evaluation, and unit propagation.

The central abstraction is Node, an immutable description of how to compute a feature from input columns. Nodes are descriptions, not data: they carry no arrays. Evaluation happens on demand via Evaluator, which caches intermediate results keyed by structural hash so that shared subexpressions are computed once.

Two design decisions distinguish this from eager approaches:

  1. Structural hashing. Two nodes describing the same computation compare equal and hash identically, regardless of construction order. This makes deduplication automatic and lets the evaluator cache across a whole search.

  2. Fail-fast unit checking. When dimensional metadata is supplied, unit compatibility is validated at construction time, before any array work. Invalid combinations raise UnitError immediately.

Numerical failures during evaluation are never silent. Nodes that overflow, produce non-finite values, or degenerate to near-zero variance are recorded in an EvaluationLog with a reason, and excluded from results. The log is part of the public API so users can audit what was rejected.

Many nodes can also be evaluated away from the evaluator, in another thread or process: Evaluator.plan_batch() gathers what they need into an EvaluationBatch, EvaluationBatch.run() computes them with the same checks as Evaluator.evaluate(), and Evaluator.commit_batch() records its rejections in the log.

BatchOutcome

Bases: NamedTuple

Result of EvaluationBatch.run().

Attributes:

Name Type Description
kept list[int]

Positions, within the batch, of the nodes that survived.

values ndarray | None

(n_rows, len(kept)) column-major matrix of their values, or None once a caller has dropped it.

stats ColumnStats

ColumnStats of those columns.

rejections list[tuple[int, ExclusionReason, str, bool]]

(position, reason, detail, filtered) for each rejected node, in position order.

EvaluationBatch dataclass

Nodes planned by Evaluator.plan_batch(), ready to compute.

Holds no reference to the evaluator, so it can be run in another thread or process.

Attributes:

Name Type Description
entries list[Any]

Per node, either None (excluded at planning, with any record already made), an array (a value known at planning), or an (OperatorSpec, arguments) pair to compute, the arguments being the operands followed by any fitted constant.

n_rows int

Rows per column.

dtype dtype

Working dtype.

variance_tol float

Relative constancy threshold, as on Evaluator.

run()

Apply the search-time filters and compute the surviving columns.

The checks, their order and the rejection details are those of Evaluator.evaluate(). The variance and magnitude behind the constancy check are kept as ColumnStats, so that a scorer can standardise the columns without computing them again.

EvaluationLog

Record of nodes excluded during evaluation.

Exposed on Evaluator so callers can inspect why candidates were dropped. Supports iteration, len, and filtering by reason.

by_reason(reason)

Return all records matching reason.

clear()

Discard all records.

counts()

Return a count of rejections per reason.

record(node, reason, detail='')

Append a rejection record.

Evaluator

Lazily evaluates nodes against a data matrix, caching by structural key.

The cache is bounded and least-recently-used. Leaf columns are pinned and never evicted, since they are the base of every expression. Intermediate results are evicted under memory pressure and recomputed if needed again.

Numerical failures are recorded in log and reported by returning None from evaluate(); they never propagate as exceptions and are never silently discarded. Each failing node is recorded once: evaluating it again returns None without a second record, until the log is cleared.

Returned arrays are read-only, since they are shared with the cache.

Parameters:

Name Type Description Default
data Mapping[str, ndarray] | ndarray

Mapping of column name to 1-D array, or a 2-D array with columns supplied separately.

required
columns Sequence[str] | None

Column names, required when data is a 2-D array.

None
units Mapping[str, Any] | None

Optional mapping of column name to pint quantity.

None
dtype dtype | type

Working dtype. Defaults to float64; float32 halves memory but makes overflow substantially more likely in deep expressions.

float64
cache_size int

Maximum number of non-leaf arrays held in the cache.

4096
variance_tol float | None

Relative constancy threshold. A column is treated as constant when its variance falls below variance_tol times the square of its mean magnitude, so the verdict does not depend on the unit the caller happened to choose. Defaults to 1e-24 for float64, a spread twelve orders below the magnitude: the cut is_constant() applies, so the columns the search drops as constant are the ones the fit-time warning names. Narrower dtypes default to 1e-10, as their rounding noise alone exceeds that cut.

None

columns property

Names of the available input columns.

dtype property

Working dtype for evaluation.

n_rows property

Number of rows in the data.

cache_info()

Return current cache occupancy and capacity.

clear_cache()

Evict all cached intermediate results. Leaves are retained.

commit_batch(nodes, outcome)

Record a batch's rejections and return its surviving nodes.

Parameters:

Name Type Description Default
nodes Sequence[Node]

The nodes passed to plan_batch(), in the same order.

required
outcome BatchOutcome

What EvaluationBatch.run() returned for them.

required

Returns:

Type Description
list[Node]

The surviving nodes, in order, matching the columns of

list[Node]

outcome.values.

evaluate(node, apply_filters=True)

Compute the values of node, using and updating the cache.

Parameters:

Name Type Description Default
node Node

The expression to evaluate.

required
apply_filters bool

Whether to apply the search-time admissibility filters — zero variance, and the operators' domain predicates. These express whether a candidate is worth exploring, and they are data-dependent: a column that varies across a training set may be constant within some subset of it. At transform time that must not change the result, so transform_values() passes False and computes the expression unconditionally. Genuine numerical failures (overflow, non-finite results) are still caught either way.

True

Returns:

Type Description
ndarray | None

A 1-D array of length n_rows, or None if the node was

ndarray | None

excluded. When None is returned, the reason is appended to

ndarray | None

log.

evaluate_many(nodes)

Evaluate several nodes, returning only those that survived.

Parameters:

Name Type Description Default
nodes Sequence[Node]

Expressions to evaluate.

required

Returns:

Type Description
list[Node]

A tuple of (surviving nodes, matrix with one column per surviving

ndarray

node in the same order). If nothing survives, the matrix has shape

tuple[list[Node], ndarray]

(n_rows, 0).

leaf_nodes()

Return leaf nodes for every input column, with units attached.

plan_batch(nodes)

Prepare distinct nodes for evaluation away from this evaluator.

Evaluating a wide round of candidates one evaluate() call at a time spends most of its time on per-column overhead, and cannot be shared between workers because the cache and the log are mutable. A batch splits the work in three: this method resolves each node's operands (and settles leaves, cached values and known failures) here; EvaluationBatch.run() then applies the search-time filters and computes the values with no access to the evaluator, so batches can run concurrently; commit_batch() records the rejections, in node order.

Operands are resolved through evaluate(), so a failing operand is recorded when the batch is planned, ahead of the batch's own rejections. Computed values are not cached: a round's candidates are each evaluated once, and the few kept are cached when next evaluated.

Parameters:

Name Type Description Default
nodes Sequence[Node]

Expressions to evaluate. Each should appear once.

required

Returns:

Type Description
EvaluationBatch

An EvaluationBatch for EvaluationBatch.run().

transform_values(node)

Compute node without applying search-time admissibility filters.

Use this when replaying an already-selected expression on new data. Applying the search filters here would make the output depend on which rows are present — a subset in which some column happens to be constant would silently yield a different answer than the full data.

Returns:

Type Description
ndarray | None

The computed values, or None if the expression genuinely cannot

ndarray | None

be evaluated (overflow, or a non-finite result).

ExclusionReason

Bases: str, Enum

Why an evaluated node was excluded from the candidate pool.

Recorded rather than silently dropped, so that rejections are auditable.

DOMAIN_ERROR = 'domain_error' class-attribute instance-attribute

Input fell outside the operator's valid domain (e.g. log of a negative).

DUPLICATE = 'duplicate' class-attribute instance-attribute

Result is numerically identical to an already-accepted feature, such as abs of an operand that is never negative.

NON_FINITE = 'non_finite' class-attribute instance-attribute

Evaluation produced NaN or infinite values.

OVERFLOW = 'overflow' class-attribute instance-attribute

Evaluation, or the variance of its result, overflowed.

UNDERFLOW = 'underflow' class-attribute instance-attribute

Evaluation triggered a floating-point underflow.

ZERO_VARIANCE = 'zero_variance' class-attribute instance-attribute

Result is constant, or within tolerance of constant.

Node dataclass

An immutable description of how to compute a feature.

Nodes are compared and hashed structurally: two nodes describing the same computation are equal even if constructed independently. This is what makes subexpression sharing and deduplication automatic.

Nodes are not constructed directly in normal use. Use leaf(), transform(), and combine(), which handle canonicalisation and unit propagation.

Attributes:

Name Type Description
op str

Operator name, or "leaf" for input columns.

children tuple[Node, ...]

Operand nodes. Empty for leaves.

column str | None

Source column name. Set only for leaves.

unit Any

Optional pint quantity describing the result's dimensions.

depth int

Longest path to a leaf. Leaves have depth 0.

_key str

Cached canonical structural key. Used for hashing and equality.

const float | None

The fitted constant of a parametric operator, such as the a in exp(a*x); None for every other node. Part of the key, so nodes that differ only in their constant are distinct.

is_leaf property

Whether this node is an input column.

key property

Canonical structural key. Stable across processes.

n_constants property

Number of fitted constants in the expression tree.

Counted the way n_operators counts operators: a constant in a subexpression that appears twice counts twice.

n_operators property

Number of operator applications in the expression (leaves count 0).

Distinct from size, which counts DAG nodes including leaves with shared subexpressions counted once; this counts operator applications in the expression tree, the quantity used as the parsimony tie-break in beam ranking.

name property

Human-readable formula for this node.

size property

Number of nodes in the DAG rooted here, counting shared nodes once.

columns()

Return the names of source columns this expression depends on.

leaves()

Return the distinct leaf nodes this expression depends on.

subnodes()

Return every distinct node in the DAG rooted at this node.

to_sympy(symbols=None)

Convert to a sympy expression for display or simplification.

Imported lazily: sympy is only needed when a user asks for a symbolic form, so it stays off the hot path during search.

Parameters:

Name Type Description Default
symbols Mapping[str, Any] | None

Optional mapping of column name to the sympy symbol used for it. By default each column gets a real symbol named after it, sanitised into an identifier; columns whose sanitised names coincide are given distinct numeric suffixes.

None

NodeError

Bases: ValueError

Raised when a node cannot be constructed from the given arguments.

OperatorSpec dataclass

Description of a feature-construction operator.

Attributes:

Name Type Description
name str

Identifier used in node keys and formulas, e.g. "log".

arity int

Number of operands (1 for transforms, 2 for combinations).

fn Callable[..., ndarray]

Callable applied to numpy arrays.

formula Callable[..., str]

Callable producing a display string from operand names.

unit_fn Callable[..., Any] | None

Callable propagating units. Receives operand units and returns the result unit. Raises to signal dimensional invalidity. If None, the operator is treated as unit-preserving for arity 1 and unit-requiring-match for arity 2.

domain Callable[..., bool] | None

Optional predicate on input arrays; returning False marks the operand as outside the operator's valid domain.

commutative bool

Whether operand order is irrelevant. Commutative operands are sorted during hashing so x+y and y+x unify.

redundant Callable[..., bool] | None

Optional predicate on input arrays; returning True marks the result as identical to its operand (abs of a column that is never negative), so it is excluded as a duplicate.

constant_grid Callable[[ndarray], list[ndarray]] | None

Set for a parametric operator, one that carries a constant fitted to the data, such as the a in exp(a*x). fn, formula, domain and redundant then receive the constant as a last argument after the operand (formula as a float). Called with the operand's values, it returns the coarse grid of constants the fit starts from, as one or more increasing segments; a fit whose best grid point is a segment's end is rejected as running into a bound. Parametric operators must be unary, and are applied through transform() with const.

parametric property

Whether the operator carries a fitted constant.

RejectedNode dataclass

A node that was evaluated but excluded, with the reason why.

UnitError

Bases: NodeError

Raised when an operation is dimensionally invalid.

Raised at construction time, before any numerical work is performed.

UnitRegistryError

Bases: UnitError

Raised when operands carry units from different pint registries.

pint cannot multiply or divide quantities from two UnitRegistry instances, so this is a configuration problem rather than a dimensional verdict on one candidate. Evaluator converts the units it is given into a single registry, so it only arises for nodes built directly with leaf() from mixed registries.

combine(op, left, right)

Apply a binary operator to two nodes.

Unit compatibility is checked here, before any numerical work. For commutative operators, operands are canonicalised so that combine("add", x, y) and combine("add", y, x) return equal nodes.

Parameters:

Name Type Description Default
op str

Registered binary operator name.

required
left Node

First operand.

required
right Node

Second operand.

required

Returns:

Type Description
Node

A new Node.

Raises:

Type Description
NodeError

If op is unknown, has the wrong arity, or the operands are identical.

UnitError

If the operation is dimensionally invalid.

leaf(column, unit=None)

Create a leaf node referring to an input column.

Parameters:

Name Type Description Default
column str

Name of the source column.

required
unit Any

Optional pint quantity describing the column's dimensions.

None

Returns:

Type Description
Node

A depth-0 Node.

parametric_operators()

Names of the registered parametric operators, in sorted order.

These are the operators BeamSearch accepts in fitted_ops.

pole_margins(x)

Smallest distances a fitted pole keeps below and above the values x.

Each is the larger of POLE_MARGIN_SPREADS times the spread of the POLE_MARGIN_ROWS most extreme values at that end (all of them, for fewer rows) and POLE_MARGIN_FLOOR times the range of x.

The shifts of inv_shift and log_shift place their pole at least this far from the values. pow has its pole at 0 when its exponent is negative, so a negative exponent is fitted only when the smallest value exceeds the margin below; otherwise only exponents from 0.1 to 4 are.

transform(op, child, const=None)

Apply a unary operator to a node.

Unit compatibility is checked here, before any numerical work.

Parameters:

Name Type Description Default
op str

Registered unary operator name.

required
child Node

Operand node.

required
const float | None

The constant of a parametric operator (see OperatorSpec.constant_grid), such as the a of exp_scaled, exp(a*x). Required for a parametric operator and refused for any other. A constant that reduces the operator to a plain one gives the plain node: pow with 2 is square, inv_shift with 0 is reciprocal.

None

Returns:

Type Description
Node

A new Node one level deeper than child.

Raises:

Type Description
NodeError

If op is unknown or has the wrong arity, if const is missing, not finite, or given to an operator without one, or if the constant makes the result constant.

UnitError

If the operation is dimensionally invalid.