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'
|
Other arguments match BeamFeatTransformer.
Attributes:
| Name | Type | Description |
|---|---|---|
features_ |
Selected expressions. |
|
feature_formulas_ |
Their formula strings. |
|
model_ |
The fitted downstream linear model, |
|
scaler_ |
The |
|
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
|
|
fdr_scope_ |
Which set |
|
equations_ |
The forward path through the screened set, one record
per number of terms, with the record of the fitted model marked;
see |
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 |
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'
|
Returns:
| Type | Description |
|---|---|
str
|
A string such as |
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 |
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 |
4
|
max_terms
|
int | None
|
As in |
None
|
style
|
str
|
As in |
'significant'
|
note
|
bool
|
Whether to append the bracketed note. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
A string such as |
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, |
|
scaler_ |
The |
|
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 |
|
equations_ |
The forward path through the screened set, one record
per number of terms, with the record of the fitted model marked;
see |
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 |
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'
|
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 |
4
|
max_terms
|
int | None
|
As in |
None
|
style
|
str
|
As in |
'significant'
|
note
|
bool
|
Whether to append the bracketed notes. |
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'
|
selector
|
str | Selector | None
|
FDR-controlled selector, or |
'permutation'
|
problem_type
|
str
|
|
'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; |
None
|
target_fdr
|
float
|
Nominal false discovery rate for the selector. |
0.1
|
unary_ops
|
tuple[str, ...]
|
Unary operators to apply. |
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 |
None
|
selection_holdout
|
float | None
|
Fraction of the training rows held out of the
search for selection, strictly between 0 and 1, or |
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
|
selection_correction
|
str
|
|
'by'
|
on_no_discoveries
|
str
|
What to return when the screen rejects no null:
|
'empty'
|
parsimony
|
str | None
|
|
'forward'
|
parsimony_tol
|
float
|
Minimum incremental R^2 a feature must add to be kept by
|
0.001
|
random_state
|
int | None
|
Seed. Fitting is deterministic given this. |
0
|
verbose
|
int
|
Progress reporting to stdout. |
0
|
n_jobs
|
int | None
|
Workers that evaluate and score the search's candidates:
threads, or processes for |
1
|
max_inputs
|
int | None
|
Most distinct input columns one feature may use, or
|
None
|
fitted_ops
|
tuple[str, ...]
|
Parametric operators whose one constant is fitted
inside the expression: |
DEFAULT_FITTED
|
certify_test
|
str
|
The test the |
'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 |
'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 |
False
|
parsimony_alpha
|
float | None
|
Level of a chance check on each term the forward
step of |
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 |
0
|
max_search_rows
|
int | None
|
Most rows the search runs on, or |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
features_ |
Selected |
|
feature_formulas_ |
Their formula strings. |
|
feature_ranges_ |
Each feature's smallest and largest value on the
training rows, one row per feature. |
|
search_result_ |
The |
|
selection_result_ |
The |
|
fdr_controlled_ |
Whether the returned features came from the
FDR-screened set. |
|
fdr_scope_ |
Which set |
|
equations_ |
The greedy forward path through the screened set, one
record per size |
|
selection_report_ |
One dict per candidate screened, in the search's
order: |
|
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. |
|
input_report_ |
One dict per (candidate, column) pair the input test
ran on: |
|
certification_result_ |
The |
|
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 |
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
|
|
required |
y
|
array - like
|
Target. Required, since both search and selection are supervised. |
None
|
Returns:
| Type | Description |
|---|---|
BeamFeatTransformer
|
|
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 |
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 |
q |
float
|
The false discovery rate level. |
correction |
str
|
|
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 |
required |
X
|
Any
|
The held-out rows, one column per input: an array of shape
|
required |
y
|
Any
|
The target on those rows, finite, shape |
required |
q
|
float
|
The false discovery rate level, in (0, 1). |
0.1
|
correction
|
str
|
|
'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 |
None
|
random_state
|
int | None
|
Seed for the permutations. |
0
|
Returns:
| Type | Description |
|---|---|
EquationScreen
|
An |
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
|
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 |
train |
ndarray
|
The rows the clone was fitted on, as positions in |
test |
ndarray
|
The rows it was scored on: every row not in |
formulas |
tuple[str, ...]
|
The selected features' formulas, as |
equation |
str | None
|
The fitted equation, as |
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 |
fdr_controlled |
bool | None
|
The clone's |
feature_classes |
tuple[int, ...]
|
The class of each formula, as a position in
|
equation_class |
int
|
The class of the equation, as a position in
|
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 |
test_size |
float
|
The fraction of the rows each split held out. |
resample |
str
|
|
random_state |
int | None
|
The seed the splits and the clones' seeds came from. |
splits |
tuple[SplitResult, ...]
|
One |
features |
tuple[FeatureClass, ...]
|
The distinct features selected, one
|
equations |
tuple[EquationClass, ...]
|
The distinct equations printed, one
|
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 |
required |
X
|
array - like
|
|
required |
y
|
array - like
|
Target, one entry per row of |
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
|
0.25
|
resample
|
str
|
|
'splits'
|
random_state
|
int | None
|
Seed of the partitions and of the clones'
|
0
|
n_jobs
|
int | None
|
Splits fitted at the same time, through joblib. |
1
|
Returns:
| Type | Description |
|---|---|
StabilityReport
|
The |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If an argument is out of range, or |
Search
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'
|
problem_type
|
ProblemType
|
|
'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 |
50
|
max_features
|
int | None
|
Maximum features returned by score. Defaults to
|
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. |
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
|
n_jobs
|
int | None
|
Workers that evaluate and score a depth's candidates, chunk
by chunk, through joblib. |
1
|
chunk_size
|
int | None
|
Candidates evaluated and scored together. Bounds the
candidate values held at once to |
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
|
fitted_ops
|
Sequence[str]
|
Parametric operators whose constant is fitted to the
data, from |
()
|
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
|
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
|
Attributes:
| Name | Type | Description |
|---|---|---|
result_ |
SearchResult | None
|
|
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
|
required |
target
|
ndarray
|
Target vector, one entry per row. |
required |
columns
|
Sequence[str] | None
|
Column names, when |
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 |
None
|
Returns:
| Type | Description |
|---|---|
SearchResult
|
A |
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 |
trace |
list[SearchTrace]
|
Per-depth |
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; |
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
|
n_fitted |
int
|
Of the candidates proposed, those carrying a constant
fitted at this depth (see |
n_magnitude |
int
|
Of the candidates kept, those kept for their magnitude
score in the slots |
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
|
|
required |
references
|
Sequence[ndarray]
|
Standardised reference vectors of length |
required |
stats
|
ColumnStats | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
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 |
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 |
required |
operand
|
ndarray
|
The operand's values on the search rows. |
required |
target
|
ndarray
|
The target, centred and scaled to unit variance, as
|
required |
partners
|
ndarray | None
|
Optional |
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
|
|
required |
target
|
ndarray
|
The standardised target. |
required |
partners
|
ndarray | None
|
Optional |
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 |
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'
|
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'
|
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'
|
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
|
|
required |
incumbent
|
ndarray | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
An opaque value to pass to |
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
|
|
required |
target
|
ndarray
|
|
required |
incumbent
|
ndarray | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
score_prepared(candidates, prepared, stats=None)
Score candidate columns against state from prepare().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidates
|
ndarray
|
|
required |
prepared
|
Any
|
The value |
required |
stats
|
ColumnStats | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
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 ( |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
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'
|
random_state
|
int | None
|
Seed (used by the model-X sampler and the orthogonal complement basis). |
0
|
offset
|
Offset
|
|
1
|
shrinkage
|
float
|
Ridge term added to the covariance diagonal for numerical stability. |
1e-06
|
construction
|
Literal['auto', 'fixed', 'gaussian']
|
|
'auto'
|
s_method
|
Literal['equicorrelated', 'ci']
|
|
'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'
|
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'
|
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 |
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 |
threshold |
float
|
The data-dependent cut applied to |
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:
-
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.
-
Fail-fast unit checking. When dimensional metadata is supplied, unit compatibility is validated at construction time, before any array work. Invalid combinations raise
UnitErrorimmediately.
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
|
|
stats |
ColumnStats
|
|
rejections |
list[tuple[int, ExclusionReason, str, bool]]
|
|
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 |
n_rows |
int
|
Rows per column. |
dtype |
dtype
|
Working dtype. |
variance_tol |
float
|
Relative constancy threshold, as on |
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
|
required |
columns
|
Sequence[str] | None
|
Column names, required when |
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 |
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 |
required |
outcome
|
BatchOutcome
|
What |
required |
Returns:
| Type | Description |
|---|---|
list[Node]
|
The surviving nodes, in order, matching the columns of |
list[Node]
|
|
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 |
True
|
Returns:
| Type | Description |
|---|---|
ndarray | None
|
A 1-D array of length |
ndarray | None
|
excluded. When |
ndarray | None
|
|
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]
|
|
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 |
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 |
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 |
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
|
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. |
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 |
redundant |
Callable[..., bool] | None
|
Optional predicate on input arrays; returning True marks the
result as identical to its operand ( |
constant_grid |
Callable[[ndarray], list[ndarray]] | None
|
Set for a parametric operator, one that carries a
constant fitted to the data, such as the |
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 |
Raises:
| Type | Description |
|---|---|
NodeError
|
If |
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 |
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
|
None
|
Returns:
| Type | Description |
|---|---|
Node
|
A new |
Raises:
| Type | Description |
|---|---|
NodeError
|
If |
UnitError
|
If the operation is dimensionally invalid. |