# In Colab, or wherever beamfeat is not installed yet
%pip install -q "beamfeat[all]"
Reading a fit¶
The three notebooks before this one plant an answer and check that beamfeat
finds it. Real fits do not arrive that way. They arrive as an equation you did
not write, containing columns you did not expect, with fdr_controlled_
reporting True and no obvious way to tell a triumph from a coincidence.
This notebook is about that moment. We take a problem with a known physical answer, hide it among noise, and then get it wrong on purpose — because the ways it goes wrong are more instructive than the way it goes right, and every one of them has a fix.
import sys
import warnings
import numpy as np
import pandas as pd
# beamfeat's warnings, in order with the printed output and without this
# machine's file paths
def show_warning(message, category, *_):
sys.stdout.flush()
print(f"{category.__name__}: {message}", file=sys.stderr, flush=True)
warnings.filterwarnings("default")
warnings.showwarning = show_warning
from beamfeat import BeamFeatRegressor
rng = np.random.default_rng(99)
n = 300
The problem¶
Hydraulic power of a centrifugal pump, P = rho * g * Q * H / eta: density,
gravity, flow rate, head, efficiency. Five real variables, buried among eight
columns of plausible-looking nonsense — the ambient noise any plant historian
is full of.
Note that g is a constant. Keep an eye on it.
columns = {
"rho": rng.uniform(800, 1200, n), # density, kg/m^3
"g": np.full(n, 9.81), # gravity, m/s^2 — constant
"Q": rng.uniform(0.01, 0.5, n), # flow rate, m^3/s
"H": rng.uniform(10, 100, n), # head, m
"eta": rng.uniform(0.6, 0.9, n), # efficiency, dimensionless
}
power = columns["rho"] * columns["g"] * columns["Q"] * columns["H"] / columns["eta"]
y = power + rng.normal(0, 0.02 * power.std(), n)
for index in range(8):
columns[f"noise_{index}"] = rng.uniform(0, 50, n)
X = pd.DataFrame(columns)
print(f"{X.shape[0]} rows, {X.shape[1]} columns, {X.shape[1] - 5} of them irrelevant")
300 rows, 13 columns, 8 of them irrelevant
Start at the defaults¶
Always. The defaults are max_depth=2, beam_width=50.
model = BeamFeatRegressor(random_state=99).fit(X, y)
print(model.equation())
print(f"R^2: {model.score(X, y):.4f}")
UserWarning: beamfeat: 1 of 13 columns are constant (g) and cannot be selected. They are ignored and cost nothing, but check whether they are meant to carry data.
y = 9.799*((H * Q) / (eta / rho)) + 279.9 [1 of 50 certified terms; parsimony=None prints all 50] R^2: 0.9996
(H * Q) / (eta / rho) is rho * Q * H / eta — the physics, exactly, with
none of the eight noise columns in it.
The suffix is the equation being honest about its own scope: screening
certified fifty formulas, most of them pairing the physics core with a noise
column, and the parsimony step kept the one that carries the model. Those
fifty are the set the guarantee covers. parsimony=None prints them all, and
the section below on the marginal null explains why the noisy ones are there
and why rejecting their nulls is not an error.
Where did gravity go?¶
It is in the coefficient. g never varies, so no expression containing it can
be distinguished from the same expression without it: rho * g is just
9.81 * rho, perfectly collinear with rho, and the redundancy pass keeps one
representative of the pair. The scaling then lands in the linear model, which
is why the fitted coefficient reads 9.80 rather than 1. Under
parsimony=None the same scaling is shared across fifty collinear terms and
the leading coefficient reads lower, which is why a constant is easiest to
read off the compact fit.
This generalises. A multiplicative constant is absorbed into the coefficient rather than recovered as a symbol, so its absence from the formula is not a miss. Check the coefficient before concluding a factor was lost.
Searching harder makes it worse¶
Five variables feels like it should need a deep search. Let us give it one:
depth 3, and a wider beam. verbose=1 shows what each stage did.
deep = BeamFeatRegressor(
random_state=99, max_depth=3, beam_width=60, verbose=1
).fit(X, y)
print()
print(deep.equation())
print(f"R^2: {deep.score(X, y):.4f}")
print(f"fdr_controlled_: {deep.fdr_controlled_}")
print(
f"candidates proposed: {deep.search_result_.n_proposed_total}, "
f"against {model.search_result_.n_proposed_total} at the defaults"
)
UserWarning: beamfeat: 1 of 13 columns are constant (g) and cannot be selected. They are ignored and cost nothing, but check whether they are meant to carry data.
[beamfeat] fit: 300 rows x 13 columns, split 150 search / 150 selection [beamfeat] search: depth 3, beam 60 -> 56622 proposed, 60 candidates (1.64s) [beamfeat] screen: 60 candidates, permutation (BY) at q=0.1 -> 60 certified [beamfeat] parsimony: 60 certified -> 1 term (|S|/|S'| = 60.00) [beamfeat] result set: 1 term in the fitted equation (the guarantee covers the certified set, not this subset) [beamfeat] result: y = 9.799*(noise_0 + ((rho / eta) * (H * Q))) + 16.98 [1 of 60 certified terms; parsimony=None prints all 60] [FDR controlled over the screened set] y = 9.799*(noise_0 + ((rho / eta) * (H * Q))) + 16.98 [1 of 60 certified terms; parsimony=None prints all 60] R^2: 0.9996 fdr_controlled_: True candidates proposed: 56622, against 14266 at the defaults
The physics is still in there — (rho / eta) * (H * Q), the same law
spelled another way — but noise_0 has been bolted onto it, and
fdr_controlled_ is still
True. The R^2 is unchanged to four decimals. We searched four times as many
candidates for an equation nobody can read.
Why the flag is still True¶
This is the single most important thing to understand about the guarantee, and it is not a defect.
The null being tested is marginal: is this expression, as a whole, independent of the target? An expression that combines the true core with a noise column is emphatically not independent of the target — the core sees to that — so its null is false and rejecting it is not an error under the criterion. The guarantee bounds the expected share of selected formulas that are pure noise. It says nothing about whether every column inside a formula earns its place.
So fdr_controlled_ = True means what it says, and it is not the property you
wanted here. Noise hitchhikes on a strong signal.
Depth is not the number of variables¶
The instinct that sent us to max_depth=3 was wrong arithmetic. Depth counts
composition levels, not variables, and a binary operator combines any two
surviving expressions — not a variable onto a chain.
So rho * Q * H / eta, four variables, is depth two:
| depth | built |
|---|---|
| 1 | (Q * H) and (eta / rho) |
| 2 | (Q * H) / (eta / rho) |
The default reached it on the first try. The extra level bought no accuracy and
gave the search room to decorate a finished answer with noise. Raise max_depth
when a target you expect is not being recovered, never speculatively: a deeper
search enlarges the candidate pool, every threshold scales as 1/m, and each
extra candidate costs power on the ones that matter.
Units are the fix¶
The screen cannot tell that noise_0 does not belong — as we just saw, the
expression is genuinely associated with the target once noise_0 is attached
to the core. Physics can. You cannot add a dimensionless number to a quantity
in kg·m/s, and beamfeat rules out such expressions at construction, before they
are ever scored. (There is a statistical route too: input_test=True tests
each column inside each term, as the guide describes.)
units = {
"rho": "kg/m**3", "g": "m/s**2", "Q": "m**3/s", "H": "m",
"eta": "dimensionless",
**{f"noise_{index}": "dimensionless" for index in range(8)},
}
gated = BeamFeatRegressor(
random_state=99, max_depth=3, beam_width=60, units=units
).fit(X, y)
print(gated.equation())
print(f"R^2: {gated.score(X, y):.4f}")
from beamfeat import UnitError
from beamfeat.expression import combine, leaf, transform
# The same expression built with the units above; UnitError if they rule it out.
def with_units(node):
if node.is_leaf:
return leaf(node.column, units[node.column])
children = [with_units(child) for child in node.children]
if len(children) == 1:
return transform(node.op, children[0], node.const)
return combine(node.op, *children)
# Formulas of the whole certified set, not only the pruned equation, that the
# units rule out.
def ruled_out(model):
full = BeamFeatRegressor(**{**model.get_params(), "parsimony": None, "verbose": 0}).fit(X, y)
count = 0
for node in full.features_:
try:
with_units(node)
except UnitError:
count += 1
return count, full.n_features_out_
for label, m in (("no units", deep), ("units", gated)):
count, total = ruled_out(m)
print(f"certified formulas the units rule out, {label:8s}: {count} of {total}")
UserWarning: beamfeat: 1 of 13 columns are constant (g) and cannot be selected. They are ignored and cost nothing, but check whether they are meant to carry data.
y = 9.799*((rho / eta) * (H * Q)) + 279.9 [1 of 60 certified terms; parsimony=None prints all 60] R^2: 0.9996
UserWarning: beamfeat: 1 of 13 columns are constant (g) and cannot be selected. They are ignored and cost nothing, but check whether they are meant to carry data.
certified formulas the units rule out, no units: 55 of 60
UserWarning: beamfeat: 1 of 13 columns are constant (g) and cannot be selected. They are ignored and cost nothing, but check whether they are meant to carry data.
certified formulas the units rule out, units : 0 of 60
The same over-deep search now returns the clean core. Identical R^2, no parasites — and the effect is not just in the pruned equation: rebuilt with the units, almost every formula the unlabelled search certified is ruled out, most of them for adding a noise column to a dimensioned quantity, and not one of those certified under the units is. That is the general lesson — where a statistical criterion cannot separate two candidates, a structural constraint often can, and it costs nothing because it applies before any numerical work.
Two cautions about what units check.
They enforce that an expression is internally coherent, not that it matches the
target's dimension. rho * Q * H / eta is kg·m/s while power is watts, and
nothing objects, because g was absorbed. Units rule out nonsense; they will
not tell you a factor is missing.
And a dimensionless column is legal almost everywhere. Q / noise_7 is still
m³/s, and noise_3 + noise_5 adds one dimensionless column to another, so
noise can ride in even under a full labelling, and most of the certified set
still mentions one. What units removed is the whole class of violations —
adding a bare number to a physical quantity — not every appearance of an
irrelevant column.
Cover every column¶
Labelling the five real measurements and leaving the noise columns blank looks like the careful thing to do. It is not.
partial = {
"rho": "kg/m**3", "g": "m/s**2", "Q": "m**3/s", "H": "m",
"eta": "dimensionless",
}
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
half_gated = BeamFeatRegressor(
random_state=99, max_depth=3, beam_width=60, units=partial
).fit(X, y)
for entry in caught:
if "units cover" in str(entry.message):
print(str(entry.message)[:200])
break
print()
print(half_gated.equation())
beamfeat: units cover 5 of 13 columns; 8 are unlabelled (noise_0, noise_1, noise_2, noise_3, noise_4, ...) and are treated as dimensionally unconstrained, so expressions combining them with labelled c y = 9.799*(noise_0 + ((rho / eta) * (H * Q))) + 16.98 [1 of 60 certified terms; parsimony=None prints all 60]
noise_0 is back, added directly to a kg·m/s quantity — the exact violation
the units pass exists to catch. An unlabelled column is dimensionally
unconstrained, so it combines freely with everything, and the gate stops
binding on precisely the columns you did not vouch for. Units are all or
nothing; give the genuinely unitless columns "dimensionless".
The equation is not the certified set¶
equation() prints the parsimony subset, and its suffix says so. The guarantee
covers the larger screened set, which selection_report_ holds in full, with
a permutation p-value and its q-value per candidate.
report = deep.selection_report_
screened = [row for row in report if row["screened"]]
printed = [row for row in report if row["kept"]]
print(f"candidates screened: {len(report)}")
print(f"certified (guarantee applies here): {len(screened)}")
print(f"terms in equation(): {len(printed)}")
print(f"|S|/|S'|: {deep.fdp_inflation_:.2f}")
print(f"fdr_controlled_: {deep.fdr_controlled_} fdr_scope_: {deep.fdr_scope_!r}")
print()
for row in sorted(screened, key=lambda r: r["p_value"])[:3]:
formula = row["formula"]
shown = formula if len(formula) <= 62 else formula[:59] + "..."
print(f" {shown:62} p={row['p_value']:.2e} q={row['q_value']:.2e}")
candidates screened: 60 certified (guarantee applies here): 60 terms in equation(): 1 |S|/|S'|: 60.00 fdr_controlled_: True fdr_scope_: 'screened set' (noise_0 + ((rho / eta) * (H * Q))) p=1.78e-04 q=8.33e-04 (((H * Q) * (Q * rho)) + ((H * Q) * (H - noise_3))) p=1.78e-04 q=8.33e-04 (((H + noise_2) * (Q * rho)) + ((Q * rho) * (H - noise_6))) p=1.78e-04 q=8.33e-04
The gap matters. Parsimony picks a subset by greedy forward selection on the
same rows, and a data-dependent subset of an FDR-controlled set does not
inherit the guarantee: pruning cannot add false discoveries, but it can raise
the false discovery proportion, because the denominator shrinks faster than
the numerator, and fdp_inflation_ reports by how much. This is why
fdr_controlled_ and fdr_scope_ are two attributes rather than one: the
flag is True and the scope is the screened set, not the printed equation. What that costs in
fit is small and has been measured — about a thousandth of R^2 across 308
paired fits, held out in every study but one scored in-sample, in
benchmarks/PARSIMONY_COST.md. Report the screened set
when you need the guarantee; use the equation when you need something to read.
The equation at every size¶
The forward step adds terms one at a time and stops when the next would add
less than parsimony_tol to R^2. equations() continues it through the whole
screened set, one equation per number of terms, so you can see what the
stopping point traded away. On the default fit from the start:
print(model.equations(max_n_terms=4))
Forward path through the 50 screened terms. R^2 is in-sample, on the rows screening used; gain is the R^2 the line's last term adds. k complexity R^2 gain equation * 1 8 0.9996 0.9996 y ~ ((H * Q) / (eta / rho)) 2 15 0.9996 1.684e-05 y ~ ((H * Q) / (eta / rho)) + ((Q)^2 * (H - noise_7)) 3 23 0.9996 3.119e-06 y ~ ((H * Q) / (eta / rho)) + ((Q)^2 * (H - noise_7)) + ((noise_0 + noise_3) * (H * Q)) 4 30 0.9996 1.743e-06 y ~ ((H * Q) / (eta / rho)) + ((Q)^2 * (H - noise_7)) + ((noise_0 + noise_3) * (H * Q)) + (log(noise_4) * (H * Q)) ... * the fitted model (the forward step stops before the first gain below parsimony_tol=0.001). The FDR guarantee covers the screened set of 50 terms (line 50), not an equation chosen from this list.
Line 1, marked, is the fitted model. Lines 2 to 4 each add a term that pairs part of the core with a noise column and gains less than 1e-4 of R^2 — the noisy members of the fifty certified formulas, met one at a time, and the reason the forward step stopped after line 1. Complexity counts the nodes of each term's expression tree, plus one per term for its coefficient. The R^2 is in-sample, on the rows screening used, and the lines carry no coefficients because only the marked one has been fitted.
The last line of the output is the one to keep in mind. Every line is a subset
of the screened set chosen on the rows screening used, so picking line 3
because it reads well is the same kind of choice the forward step makes, and
the guarantee covers it no more than it covers line 1. It covers line 50, the
screened set itself, which is the equation parsimony=None fits. The records
behind the text are in equations_.
When nothing is selected¶
Two very different situations produce an empty selection, and they have different fixes. Here is the honest one — a target that is pure noise.
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
empty = BeamFeatRegressor(random_state=0).fit(X, rng.normal(0, 1, n))
print(f"features constructed: {empty.n_features_out_}")
print(f"fdr_controlled_: {empty.fdr_controlled_}")
for entry in caught:
print(f" warning: {str(entry.message)[:130]}")
features constructed: 0 fdr_controlled_: False warning: beamfeat: 1 of 13 columns are constant (g) and cannot be selected. They are ignored and cost nothing, but check whether they are m warning: beamfeat: the FDR-controlled screen rejected no null at target FDR 0.1 on the held-out split (on_no_discoveries='empty'). Returnin
An intercept-only model and a visible warning, which is the correct answer:
there was nothing to find, and the constructor declined to invent it.
fdr_controlled_ reads False here rather than True — no feature was
returned, so nothing carries the guarantee, and the flag describes what came
back rather than how hard the procedure tried.
The other case looks identical from the outside but is not. If the candidate pool is large enough that the multiplicity threshold falls below the smallest p-value the permutation budget can produce, the correction cannot reject anything, whatever the data say. The selector detects this and says so in its warning, naming the correction and what to change. So read the warning before concluding there is no signal: an empty selection with a budget warning means that no null could have been rejected at that budget, not that the data are silent.
Writing it down¶
latex() typesets equation(), with the same terms, coefficients and note. It
returns a string without math delimiters, which a notebook renders with
IPython.display.Math:
from IPython.display import Math
Math(model.latex())
print(model.latex(note=False))
print(model.latex_formulas())
y = 9.799 \frac{H Q \rho}{\eta} + 279.9
['\\frac{H Q \\rho}{\\eta}']
latex(note=False) leaves the note off, for pasting into a document. The
guarantee still covers the fifty screened terms, so say so wherever the
equation appears. latex_formulas() gives the features alone, and the
transformer has it too. Both need sympy (pip install "beamfeat[display]"), as
to_sympy() does.
Running it elsewhere¶
to_sympy() returns each feature as a sympy expression in real symbols named
after the columns, so sympy.lambdify turns the features into a function of
plain arrays. Fold the model's standardisation into its coefficients and that
reproduces predict:
import sympy
symbols = sympy.symbols(list(X.columns), real=True) # one per column, in order
features = sympy.lambdify(symbols, model.to_sympy(), modules="numpy")
raw = model.coef_ / model.scaler_.scale_
offset = model.intercept_ - raw @ model.scaler_.mean_
exported = np.column_stack(features(*X.to_numpy().T)) @ raw + offset
print(model.to_sympy())
print(f"agrees with predict(): {np.allclose(exported, model.predict(X))}")
[H*Q*rho/eta] agrees with predict(): True
modules="jax" or modules="torch" (sympy 1.14 or newer) gives the same
function on JAX or PyTorch arrays, with jnp.stack(..., axis=1) or torch.stack(..., dim=1) in place of
np.column_stack; the coefficients and offset are plain arrays to convert
once. Neither library is needed for this notebook, so only NumPy runs here. The
column names are valid identifiers, so the symbols carry them unchanged; other
names are sanitised, and the expressions' free_symbols show what they became.
Two differences from predict remain. sympy may rewrite an expression into an
equivalent form — (H * Q) / (eta / rho) came back as H*Q*rho/eta — so a
value can overflow in one and not the other. And a row outside a formula's
domain gives whatever the array library gives there, where predict gives NaN
and a warning.
A checklist¶
- Start at the defaults. Raise
beam_widthwhen an expected target is missed; raisemax_depthonly when the target genuinely needs the depth, and count composition levels, not variables. - An equation that grew noise terms is a sign you searched too deep, not that you need to search deeper.
fdr_controlled_ = Truesays the guarantee holds: on average at mosttarget_fdrof the certified formulas are noise. It does not say every column in a formula belongs;input_test=Truetests that.- On a noisy target the default equation can carry terms that each add a
little by fitting noise;
parsimony_alpha=0.05stops them, when you want an equation to read rather than the best prediction. - Supply units when you have them, for every column.
- A missing constant is usually in the coefficient.
- Quote
selection_report_when you need the guarantee; quoteequation()when you need a sentence. - An equation picked from
equations()carries no more of the guarantee thanequation()does, andlatex(note=False)drops the note, not the caveat. - Read the warnings. They distinguish states that look identical from outside.
What to read next¶
- 02: Search and scoring — beam width, depth and the scoring strategies, with the trace that shows where the cost went.
- 03: Selection and units — the calibration behind the guarantee, why the default is not knockoffs, and the dimensional analysis used above.