Skip to content

Model Selection

select_n_components

select_n_components(x: object, *, mask: object | None = None, components: Iterable[int] | None = None, config: SelectionConfig | None = None, **opts: object) -> tuple[int, dict[str, object], list[dict[str, object]], VBPCA | None]

Select capacity from samples-by-features observations and aligned probes.

Parameters:

Name Type Description Default
x object

Native samples-by-features numeric observations, including named tables or sparse stored-entry observations. NaNs are missing.

required
mask object | None

Optional aligned observation mask; numeric zeros remain observed.

None
components Iterable[int] | None

Nonnegative integral capacities within both dimensions. Omission retains the positive default grid; explicit zero is a closed-form mean-only candidate.

None
config SelectionConfig | None

Existing endpoint metric, stopping and diagnostic policy.

None
**opts object

Native fitting options. An explicit xprobe has the same samples-by-features layout and feature names as x. Warm-start payloads retain their documented low-level axes. Modern mode is the default; selection_verbose controls sweep logging.

{}

Returns:

Type Description
int

(best_k, best_metrics, trace, best_model). A requested positive-rank

dict[str, object]

best model is a native VBPCA with conditional new-data projection;

list[dict[str, object]]

rank zero retains the existing None model result. Requested dense

VBPCA | None

diagnostics use samples-by-features axes and the existing byte budget.

Invalid inputs, capacities, metrics or diagnostics raise ValueError. Cellwise PRMS/cost selection retains its existing target and fold/probe definitions. Row-wise sklearn scoring evaluates a different target. vbpca_py.legacy.select_n_components preserves feature-first callers.

cross_validate_components

cross_validate_components(x: object, *, mask: object | None = None, components: Iterable[int] | None = None, config: CVConfig | None = None, **opts: object) -> tuple[int, list[dict[str, object]]]

Select capacity using existing cellwise CV on samples-by-features input.

Parameters:

Name Type Description Default
x object

Dense samples-by-features numeric observations; NaNs are missing.

required
mask object | None

Optional aligned observation mask.

None
components Iterable[int] | None

Nonnegative integral capacities within both dimensions.

None
config CVConfig | None

Cellwise fold, metric and selection policy. Feature groups and encoding-schema columns refer to the input feature axis.

None
**opts object

Fitting options, with modern mode as the default. This helper constructs its own probes; do not supply xprobe or a positive xprobe_fraction. Warm starts retain their low-level axes.

{}

Returns:

Type Description
int

Selected capacity and the existing aggregate/per-fold metric records.

list[dict[str, object]]

Full-grid one-SE and optional first-minimum selection remain distinct.

Raises:

Type Description
ValueError

Inputs, capacities, fold support or metric rules are invalid.

This is cellwise capacity CV, separate from sklearn's row-wise CV and the estimator's marginal likelihood score. Use the explicit legacy helper for historical feature-first inputs and defaults.

cross_validate_raw_components

cross_validate_raw_components(x: InputArray, *, encoder_factory: Callable[[], AutoEncoder], mask: BoolArray | None = None, components: Iterable[int] | None = None, config: CVConfig | None = None, **opts: object) -> tuple[int, list[dict[str, object]], list[PreprocessedFold]]

Select capacity after fitting preprocessing within each raw cell fold.

Parameters:

Name Type Description Default
x InputArray

Dense samples-by-original-variables table.

required
encoder_factory Callable[[], AutoEncoder]

Fresh configured AutoEncoder per fold; see prepare_raw_cv_folds for vocabulary and unknown-level requirements.

required
mask BoolArray | None

Raw observation mask.

None
components Iterable[int] | None

Candidate capacities, optionally including zero. Default candidates fit every fold's encoded dimensions.

None
config CVConfig | None

CV metric/rule, fold count and seed; first-minimum early stopping reuses the same prepared encoders across candidate capacities.

None
**opts object

VBPCA fitting options, applied independently in each fold.

{}

Returns:

Type Description
int

Selected capacity, aggregate CV records and the prepared folds for

list[dict[str, object]]

audit. Categorical metrics use original levels; numeric RMSE is reported

list[PreprocessedFold]

per variable in continuous input units or ordinal level-index units.

tuple[int, list[dict[str, object]], list[PreprocessedFold]]

Probe RMS remains in encoded units. Numeric summaries use folds with

tuple[int, list[dict[str, object]], list[PreprocessedFold]]

observed holdouts and report their count.

Raises:

Type Description
ValueError

If raw folds cannot be prepared, capacities exceed a fold's dimensions, or an external probe conflicts with these holdouts.

prepare_raw_cv_folds

prepare_raw_cv_folds(x: InputArray, *, encoder_factory: Callable[[], AutoEncoder], mask: BoolArray | None = None, config: CVConfig | None = None) -> list[PreprocessedFold]

Construct raw variable-cell folds and fit each encoder once.

Parameters:

Name Type Description Default
x InputArray

Dense samples-by-original-variables table; strings are supported.

required
encoder_factory Callable[[], AutoEncoder]

Return a fresh AutoEncoder with explicit column_types and handle_unknown="raise". Optional column_levels must describe external vocabularies, rather than levels learned from holdouts.

required
mask BoolArray | None

Raw observation mask; NaNs are always missing.

None
config CVConfig | None

Fold count and seed. Encoded groups/schemas are not accepted.

None

Returns:

Type Description
list[PreprocessedFold]

Deterministic folds retaining training support in each variable/sample.

Raises:

Type Description
ValueError

If inputs/configuration are invalid, an encoder is reused, a held-out level is unknown, or training support is insufficient.

PreprocessedFold dataclass

PreprocessedFold(encoder: AutoEncoder, training_mask: BoolArray, heldout_mask: BoolArray, training: Float64Array, held_out: Float64Array, raw: InputArray)

One raw-table holdout and its training-fitted preprocessing.

Attributes:

Name Type Description
encoder AutoEncoder

Fresh encoder fitted on training observations only.

training_mask BoolArray

Samples-by-variables training observation mask.

heldout_mask BoolArray

Samples-by-variables held-out observation mask.

training Float64Array

Samples-by-encoded-features training matrix.

held_out Float64Array

Samples-by-encoded-features probe matrix.

raw InputArray

Raw samples-by-variables values, with unobserved cells masked.

schema property

schema: EncodingSchema

Fitted metadata for this fold's encoded matrix.

Raises:

Type Description
ValueError

If the encoder no longer has a fitted dense schema.

__post_init__

__post_init__() -> None

Require the declared sample axis without inferring an orientation.

Raises:

Type Description
ValueError

Encoded arrays or masks do not match the raw/schema axes.

__getstate__

__getstate__() -> dict[str, object]

Record the fold layout explicitly for serialization.

Returns:

Type Description
dict[str, object]

Named fold state with the native layout version.

__setstate__

__setstate__(state: object) -> None

Restore native folds; old feature-first artifacts must be rebuilt.

Raises:

Type Description
ValueError

The layout marker is absent or incompatible.

numeric_scores

numeric_scores(prediction: Float64Array) -> dict[str, float]

Score each numeric variable in input or ordinal-index units.

Parameters:

Name Type Description Default
prediction Float64Array

Samples-by-encoded-features predicted means.

required

Returns:

Type Description
dict[str, float]

rmse_variable_j for each continuous or ordinal input column.

dict[str, float]

NaN when the fold holds out no cells of that variable.

Raises:

Type Description
ValueError

Prediction shape is invalid or a held-out numeric prediction is not finite.

SelectionConfig dataclass

SelectionConfig(metric: _Metric = 'prms', stop_on_metric_reversal: bool = False, patience: int | None = None, max_trials: int | None = None, compute_explained_variance: bool = True, return_best_model: bool = False, reuse_runtime_policy: bool = True, cost_diagnostics: Literal['trace', 'endpoint'] = 'trace')

Configuration for component selection.

cost_diagnostics='trace' preserves full per-iteration cost recording. Opt-in 'endpoint' evaluates only the returned iteration, provided the selection metric and enabled stopping events do not consume cost traces. Requested record_cost=True is incompatible with endpoint mode.

CVConfig dataclass

CVConfig(metric: _CVMetric = 'prms', n_splits: int = 5, one_se_rule: bool = True, seed: int = 0, feature_groups: Sequence[object] | None = None, selection_rule: Literal['one_se', 'minimum', 'first_minimum'] | None = None, early_stop: bool = False, encoding_schema: EncodingSchema | None = None)

Configuration for K-fold cross-validated component selection.

Attributes:

Name Type Description
metric _CVMetric

Held-out selection metric: "prms" (per-indicator probe RMS), or with feature_groups the categorical "brier" or "log_score" (lower is better). With feature_groups every result also reports brier, log_score and accuracy.

n_splits int

Number of cross-validation folds.

one_se_rule bool

If True, select the smallest k whose mean metric is within one standard error of the global minimum. Ignored when selection_rule is set.

seed int

Random seed for fold partitioning and model fitting.

feature_groups Sequence[object] | None

Optional variable label for every input feature, for example an encoder's feature_groups_. Folds then hold out (variable, sample) cells, so every indicator of a one-hot encoded variable is held out together.

selection_rule Literal['one_se', 'minimum', 'first_minimum'] | None

"one_se", "minimum" or "first_minimum". "first_minimum" selects the smallest k whose successor does not lower the mean metric by more than the successor's standard error. None follows one_se_rule.

early_stop bool

With selection_rule="first_minimum", evaluate capacities in increasing order across all folds and stop as soon as the rule triggers, skipping every larger capacity.

encoding_schema EncodingSchema | None

Fitted dense encoder metadata for categorical decoding. Groups are derived from it unless explicitly supplied; an explicit group list must match. Learned preprocessing is still external to this encoded-array CV API.

resolved_rule

resolved_rule() -> str

Return the selection rule in effect.

Returns:

Type Description
str

selection_rule, or the rule implied by one_se_rule.

Raises:

Type Description
ValueError

If the rule is unknown or early_stop is requested for a rule that needs the full sweep.