Understand your data and choose a model family (discovery)

Most modelling projects that go wrong do so before any training starts: a column that leaks the outcome, rows from the same customer on both sides of the validation split, a time series validated as if it were shuffled, or a model family that does not fit the problem. tensor_optix.discovery looks at your dataset with statistics before you commit to a model, and tells you what it found, how sure it is, which model family to use and why.

from tensor_optix.discovery import discover

report = discover(df, target="churned")
report.to_html("discovery.html")      # a static, self-contained report
print(report.summary())               # the same content as text

Discovery advises; it never changes anything on its own. Every finding has a stable id that you accept or reject, and only accepted findings are applied when you build a model from the report.

What a run does

  1. Profiles the target: task type (binary / multiclass / regression / count), class balance, skew, and the metric families are compared on (AUC, macro AUC or RMSE by default).
  2. Profiles the features: inferred type per column (numeric, categorical, datetime, identifier, text, numbers stored as text ...), missingness, constants, duplicates, collinearity, outliers.
  3. Finds the structure that decides how you must validate:
    • grouped rows (several rows per customer / patient / device), detected by comparing a random split with a group split on the same model -- a random split that scores better than a group split is memorising the group;
    • temporal data, detected by comparing a model trained on the past with one trained on an equal-size random sample, on the same future rows (a Diebold-Mariano test);
    • a row order that carries the target (a file sorted by outcome).
  4. Keeps a confirmation holdout (15% by default), cut with that structure -- whole groups, or the most recent rows -- before any model is chosen, and touched once at the end.
  5. Looks for leakage: a single feature that predicts the target almost perfectly, an identifier that predicts it, missingness that predicts it, a feature equal to a future value of the target.
  6. Checks for distribution shift: train vs test= rows (adversarial validation plus per-feature tests) and early vs late data.
  7. Runs cheap reference models (dummy, linear, stump, depth-3 tree, k-NN, naive Bayes, LDA) whose relative scores describe the problem: is there signal at all, is it non-linear, does it involve interactions.
  8. Tries candidate families on identical folds -- linear, naive Bayes, k-NN, a neural network (MLP, trained by tensor-optix until convergence) and boosted trees (LightGBM and XGBoost when installed, otherwise tensor-optix's native implementation) -- and keeps adding CV repeats for the leaders while they cannot be told apart.
  9. Recommends the simplest family that is not worse than the best one, scores it once on the holdout, and writes a plan.
  10. Looks for feature opportunities: kinds of features worth engineering and a better scaler, each kept only if it improves the recommended family on the same folds (see below).

Reading the report

Open a sample report (a churn dataset with a leaked column; generated by benchmarks/validate_discovery.py's churn_with_leak). The HTML report has the same sections as report.summary():

Section What it tells you
Summary the recommendation, its verdict, the holdout estimate with its interval, and the findings that need a decision
Data understanding the profile: columns and their inferred types, the target, the structure, quality
Risks one card per finding: what was found, the evidence (test, statistic, interval, p-value), the suggested action and the exact report.reject(...) line to undo it
Feature opportunities feature families and scalers that measurably improve the model, the ones tested without gain, and the ones not tried (and why)
Families tried every experiment with its mean score and 95% interval, and every paired comparison
Recommendation the family, its configuration, why it was chosen, and the conditions it depends on
Plan the steps to train it: split, preprocessing, family, monitoring
Limitations what discovery could not do (budget cuts, missing optional families, no holdout)

The JSON of the whole report is embedded in the HTML, so a saved report reloads exactly:

from tensor_optix.discovery import DiscoveryReport
report = DiscoveryReport.from_html("discovery.html")

The recommendation verdicts

Verdict Meaning
clear_winner the recommended family beats every other family tried by more than the practical threshold
tie_simplest_chosen a simpler family is equivalent to the best-scoring one (the whole interval of their difference lies inside the practical threshold), so the simpler one is recommended
undetermined the best-scoring family is recommended, but some others could not be separated from it with the data and budget; they are listed as alternatives
abstain no family beats predicting the mean / class prior by a margin that matters -- or the evidence that one does is inconclusive (the report says which). report.build(family=...) still builds any family you choose

Findings and decisions

Each finding has a severity -- info, advisory, warning, critical -- and, when there is something to do about it, a suggested action from a fixed set (drop_column, set_column_type, use_split, dedupe, set_metric, ...).

Some findings are applied by default inside discovery's own experiments (default_applied), because ignoring them would make every later number wrong: a detected group structure switches discovery's evaluation to a group split, a suspected leak is excluded from its experiments. That only affects how discovery measures; your model is built from the findings you accept.

report.pending("warning")                    # findings at warning or above still undecided
report.accept("structure.grouped:col=customer_id")
report.reject("leakage.single_feature:col=refund_flag", note="known at prediction time")
report.accept_where(category="structure")    # bulk-accept by category / minimum severity

There is deliberately no accept_all().

To re-measure with your decisions in force (for example after rejecting a leak finding you know is fine), pass them back:

report2 = discover(df, target="churned", decisions=report.decisions())

Feature opportunities

Discovery does not invent features; it tells you which kinds of features are worth engineering for this data, with evidence. Each family is tried only when a property of the data suggests it, and recommended only when adding it improves the recommended family on the same folds by more than the practical threshold (Holm-adjusted across the families tried):

Property detected Feature family What it adds
the target is persistent over time (Ljung-Box) target_lags lagged targets and past rolling means
volatility clusters (McLeod-Li) volatility past rolling volatility of the target
features are persistent over time rolling_features rolling means / standard deviations and differences
a datetime column calendar_cycles sine / cosine of day of week, month, day of year (and hour)
heavily skewed features (scale-sensitive models only) log_transform signed log transforms
interactions, with an additive model (linear, naive Bayes) interactions pairwise products of the strongest features
rows grouped by an entity group_aggregates per-entity means, spreads and deviations

The same stage recommends a scaler for models that depend on feature scale (linear, k-NN, naive Bayes, MLP): robust scaling for outlier-heavy columns, or a quantile (rank-to-normal) transform for heavy-tailed ones, each compared with the default standard scaling. For tree models the report notes that the scaler does not matter.

Temporal families run whenever the rows have a time order (a declared time, a datetime column, or detected temporal structure); with groups=, each entity is its own series. Every feature is computed from the row itself and earlier rows of its series only -- target lags start at lag 1 -- and when timestamps tie within a series, past-only features are undefined, so those families are not tried (the report says so).

Findings are advisory, never applied by default. Accept the ones you want and build() computes the same features at fit and predict time:

report.accept("features.calendar_cycles")
report.accept("preprocess.scaler:method=quantile")
solution = report.build()
solution.fit(df, target="sales")
solution.predict(new_rows)

Families that use past target values (target_lags, volatility) assume the target of earlier rows is known when you predict (one-step-ahead forecasting); pass that history with predict(new_rows, target=history), with NaN for the rows to predict.

Expression discovery

Feature opportunities test a fixed list of feature families. Expression discovery goes further: it searches for feature expressions nobody listed -- log1p(x0) * x1, diff2(price), rstd10(volume) / rmean20(volume) -- built from a typed grammar, and keeps one only when it is confirmed on data the search never saw.

report = discover(df, target="y", expressions=True)                      # opt-in
report = discover(df, target="y", expressions=True, expression_effort="thorough",
                  units={"open": "price", "close": "price", "volume": "shares"})

How it works:

  1. A sealed confirmation carve (20% of the development rows, cut with the detected structure -- the most recent rows, whole groups, or a stratified sample) is set aside before any search. The recommendation holdout is never touched. If the carve is too small the stage stops with insufficient_confirmation_data instead of reusing other data.
  2. A typed grammar: arithmetic (+ - * /, min, max), signed log1p / sqrt, tanh, square, abs, and -- when the rows have a time order -- lag, diff and trailing rmean / rstd / rmin / rmax windows that read only earlier rows of the same series. There is no target leaf and no way to read the future, so leaky expressions cannot be built. Declared units make price + shares impossible.
  3. Cheap screening: the recommended family's out-of-fold residuals on the search rows; each candidate is first projected onto the existing features (so only new information counts) and scored by rank correlation and a correlation ratio that catches thresholds and U-shapes.
  4. Guided search: genetic programming seeded by what discovery already measured (time order, changing variance, non-linearity, interactions), with canonical forms and numerical fingerprints removing duplicates (x + x is 2 * x is already x), a bandit over operator families, and a final pass that tries every simpler sub-expression of the best candidates.
  5. Successive halving: screening, then paired refits on a few folds, then on all search folds -- with a per-family diversity quota and the simplest equivalent of each survivor brought into the last rung.
  6. One-time confirmation on the sealed rows: paired test vs the model without the expression, Holm across finalists, gain above the practical threshold, positive in at least 3 of 4 confirmation blocks; look-alikes are grouped (the simplest equivalent represents them) and every further expression must still help the model that already has the stronger ones.

Confirmed expressions become features.expression:<hash> findings (advisory, never applied by default); accepted ones are computed by build() at fit and predict time. Each finalist that is not confirmed states why (not above the threshold, not significant after correction, unstable across blocks, or adding nothing beyond a stronger expression). A confirmed expression is a predictive transformation, not a claim about how the data were generated.

For environments, discover(env, expressions=True) screens expressions over the observation history of each episode against what a value baseline leaves unexplained of the returns-to-go, then confirms finalists by training the recommended algorithm with and without the expression appended to the observation, on fresh seeds never used before (rl.expression:<hash> findings; RLSolution appends accepted expressions through a wrapper).

Building a model from the report

solution = report.build()          # applies ACCEPTED findings only
solution.fit(df, target="churned")
solution.predict(new_rows)         # original labels
solution.predict_proba(new_rows)
solution.cross_validate(df, target="churned")   # re-measure with the built split

build():

  • refuses while any critical finding is still pending (build(acknowledge_pending=True) to override);
  • warns, and lists the ids in solution.evidence_mismatch, when the findings it applies differ from the ones discovery's experiments applied -- the report's scores then do not describe this setup; re-run with decisions=;
  • needs build(family=...) when the report abstained.

The solution uses the same fold-safe preprocessing discovery used: every imputation, scaling and encoding statistic is learned from training rows only, and high-cardinality target encoding is computed out-of-fold.

Inputs

discover(df, target="y")                          # pandas DataFrame (pandas is optional)
discover({"age": ..., "plan": ...}, target=y)     # dict of columns
discover(X, y, column_names=["a", "b", "c"])      # numpy arrays
discover(df, target="y", groups="customer_id")    # declare groups you know about
discover(df, target="y", time="order_date")       # declare the time column
discover(df, target="y", test=df_to_score)        # the rows the model will be used on
discover(df, target="y", column_types={"zip": "categorical_high"})
discover(df, target="y", task="regression", metric="mae")
discover(df, target="y", families=["linear", "lightgbm"])
Argument Default
budget Budget.default_for_rows(n) (about 60 s at 10k rows) Budget(time_s=..., max_rows=..., max_fits=...); discovery never silently overruns -- each cut is reported as a budget finding
holdout 0.15 fraction kept aside to confirm the recommendation; 0 disables it
seed 0 the run is reproducible given the seed
store None an ExperimentStore (or a ledger path) to record the run in
verbose False print progress

Install the optional pieces as needed:

pip install "tensor-optix[pandas]"            # DataFrame input
pip install "tensor-optix[discovery-boost]"   # LightGBM and XGBoost candidates

Without LightGBM / XGBoost, boosted trees are still tried with tensor-optix's native implementation (gbdt; same accuracy on the benchmark, slower), and the report notes it.

Recording runs in the ledger

from tensor_optix.ledger import ExperimentStore
report = discover(df, target="churned", store=ExperimentStore("runs.db"))
report.ledger_refs     # {"experiment_id": ..., "trials": {...}}

A parent experiment (algorithm="discovery") with one child per family trial, plus events for the profile (versioned meta-features), every finding, the decisions, the recommendation and the budget. These records live under their own discovery:<data fingerprint> task name, so they never count as evidence for other tasks, and discovery never reads ledger history to make a decision.

Environments (reinforcement learning)

The same entry point profiles a Gymnasium environment and compares RL algorithms on it:

import gymnasium as gym
from tensor_optix.discovery import discover, Budget

report = discover(gym.make("CartPole-v1"))                       # auto-detected
report = discover(make_my_env, kind="rl")                        # a zero-argument factory
report = discover("Pendulum-v1", kind="rl", budget=Budget(env_steps=300_000))
report.to_html("discovery.html")

What it does:

  1. Probes the environment with a random policy: spaces and bounds, episode lengths and returns, reward sparsity and scale, observation scale, determinism under a fixed seed, and partial observability (does the previous observation improve prediction of how the observation changes?).
  2. Trains every applicable algorithm for the same number of steps on the same seeds -- PPO and DQN for discrete actions; SAC, TD3 and PPO for continuous ones -- with tensor-optix's own loop, default hyperparameters and no online tuning, then evaluates each on fixed evaluation episodes.
  3. Tries the variants the probes motivate on the leading algorithm -- observation normalisation, an RND exploration bonus, a recurrent (GRU) policy -- each kept only when it beats its base by more than the practical threshold over the same seeds.
  4. Adds seeds while the leader cannot be separated from another algorithm (up to 5).
  5. Recommends with the same rule as for datasets, on mean evaluation return; the practical threshold is 5% of the gap between the random policy and the leader.

Actions of continuous-control environments are rescaled to [-1, 1] in the trials when their bounds differ (tanh-squashed policies emit that range); the env.action_rescale finding records it.

report.accept("env.action_rescale")
solution = report.build()                  # RLSolution: algorithm + accepted wrappers / add-ons
agent, run = solution.fit(gym.make("Pendulum-v1"))   # full training: convergence stopping, online tuning

The default budget is Budget(time_s=900, env_steps=200_000). Trial results describe short training; the report says so, and longer training can change the ranking, particularly for off-policy methods.

What discovery does not do (yet)

  • Multi-agent (PettingZoo) environments are profiled but algorithms are not compared.
  • Image and dict observations are profiled but not trialled.
  • Unsupervised data (no target).

See Discovery statistics for exactly how each test and comparison works, and the reference for the full API.