Preprocessing¶
Transformers validate nonempty 2-D input at fit and inference. Transforms check fitted feature counts and supplied string feature names/order; inverse transforms check encoded output width. Numeric transformers reject non-numeric input, infinity in observed entries and complex data. Dense categorical encoders also accept string/object labels. NaNs remain missing. See the 0.5 migration guide for changed errors, fitted-state handling and mask boundaries.
Sparse inputs use stored-entry observations, including stored zeros. Supported
CSR/CSC/COO matrices and arrays are validated before conversion; stored NaNs
are removed and duplicate coordinates are summed without modifying the input.
Sparse encoders and scalers reject extra masks. Sparse one-hot encoding supports
independent category blocks for multiple input columns, with flat
categories_ and output-to-input feature_groups_ metadata. Dense numeric
input to this encoder observes every non-NaN value, including zero; it returns
the same sparse indicator representation.
Use a leading ObservationMasker to consume explicit Boolean masks before
these transformers. It produces dense NaNs or sparse stored observations and
leaves downstream steps to infer missingness after any feature expansion.
Direct calls accept mask=...; Pipeline metadata routing uses the dedicated
observation_mask=... alias. Enable routing with
sklearn.config_context(enable_metadata_routing=True). Cross-validation and
GridSearchCV then slice masks for both fitting and scoring. Masks align by row
and column position, never by labels. Leave Pipeline.transform_input unset;
do not route original-variable masks to width-changing downstream steps.
Sparse-data masks may be dense or sparse Boolean arrays/matrices. A true mask entry declares an observation, including a zero absent from data storage; duplicate true entries form a union. Stored NaNs remain missing. Dense data require dense Boolean masks. Raw sparse buffers are validated before conversion, and observed infinity is rejected before duplicate aggregation. Inputs and masks are not modified. The masker stores feature metadata only and requires a fresh mask at inference when placeholders need exclusion. Masked dense outputs own their arrays; unmasked outputs may borrow validated input. Sparse normalization never creates a dense data/mask copy. Dense validation and mask application use bounded scratch blocks alongside the returned array, rather than another full observed-value or inverse-mask table.
The executable example covers mixed string/numeric input, feature expansion, row CV, GridSearchCV and new-row projection. This is ordinary row-wise scoring; original-cell holdouts use the separate raw-table component-selection API. See scikit-learn's routing guide for the opt-in and alias mechanism.
For masked projection after a grid search, call
search.best_estimator_.transform(X_new, observation_mask=new_mask).
The supported sklearn search wrapper's transform does not accept metadata;
fit and score route it, and the selected Pipeline handles new-row transforms.
ObservationMasker ¶
Bases: PreprocessorState
Normalize missingness before scaling or expanding original variables.
Dense false mask entries become NaNs; existing NaNs stay missing. Dense strings become object arrays when a mask is supplied. Sparse output is CSR: stored entries, including zeros, are observed unless excluded by a mask or NaN. A sparse-data mask can also request observed zeros absent from storage. Inputs and masks are never modified; no training mask/data is retained.
Direct calls use mask=... with Boolean samples-by-variables metadata,
aligned by position. With sklearn metadata routing enabled, a Pipeline
accepts the alias observation_mask=... for fit, transform and score.
This alias reaches only the masker, leaving downstream transformers to
infer missingness from their own feature layout. Leave transform_input
unset: entry masks must not undergo numerical feature transformations.
Without an explicit mask, dense output may borrow the validated input. Masked dense output owns its array; integer/Boolean input becomes float64 and floating input retains its dtype. Sparse normalization uses storage proportional to input/mask entries and never densifies a sparse mask.
Examples:
>>> import numpy as np
>>> from vbpca_py import ObservationMasker
>>> raw = np.array([["west", 10.0], ["placeholder", 20.0]], dtype=object)
>>> mask = np.array([[True, True], [False, True]])
>>> observed = ObservationMasker().fit_transform(raw, mask=mask)
>>> bool(np.isnan(observed[1, 0])), raw[1, 0]
(True, 'placeholder')
>>> bool(np.shares_memory(raw, observed))
False
Supply the original-variable mask to this first Pipeline step. The encoder and model then infer missingness in their own feature layout.
Create a masker without data or fitted state.
fit ¶
Validate original features and observations, retaining feature metadata.
Returns:
| Type | Description |
|---|---|
Self
|
This fitted masker. |
transform ¶
Consume a fresh mask for this table without reusing training metadata.
Returns:
| Type | Description |
|---|---|
InputMatrix
|
Dense NaN observations or a sparse CSR observation matrix. |
fit_transform ¶
Fit and apply the same mask once, including routed transform metadata.
Returns:
| Type | Description |
|---|---|
InputMatrix
|
Dense NaN observations or a sparse CSR observation matrix. |
The standard and min-max scalers use each finite, nonzero computed standard deviation or range, even when its magnitude is small. A change of measurement units therefore does not by itself classify a nonconstant column as constant. Exactly constant observed columns use a unit denominator; wholly missing columns retain NaN mean/variance or extrema and also use a unit denominator. Zero or nonfinite computed scales use the same fallback. These rules apply to dense observed entries and stored sparse observations, including stored zeros. Sparse standardization computes centered moments in bounded chunks of stored entries without making a dense copy of the data.
AutoEncoder ¶
AutoEncoder(*, cardinality_threshold: int = 20, continuous_scaler: Literal['standard', 'minmax'] = 'standard', handle_unknown: Literal['ignore', 'raise'] = 'ignore', mean_center_ohe: bool = False, column_types: Sequence[Literal['categorical', 'continuous', 'ordinal']] | None = None, binary: Literal['single', 'both'] = 'single', drop: Literal['first'] | None = None, block_weighting: Literal['none', 'equal_variance'] = 'none', column_levels: Sequence[Sequence[object] | None] | None = None)
Bases: PreprocessorState
Column-wise router that applies missing-aware OHE or scaling.
After fitting, feature_groups_ gives the input column of every
output column and feature_kinds_ the kind of every input column
("categorical", "continuous" or "ordinal"). Ordinal columns
are never inferred: list them in column_types, and they are coded as
scaled numeric scores (see :class:MissingAwareOrdinalEncoder) with the
continuous_scaler. binary, drop and
block_weighting are passed to the dense one-hot encoder (see
:class:MissingAwareOneHotEncoder).
Dense fits expose encoding_schema_ for encoding-aware categorical CV;
sparse fits leave it None (component CV accepts dense input only).
column_levels declares external nominal vocabularies or ordinal level
orders; leave continuous columns and training-inferred vocabularies None.
Examples:
>>> import numpy as np
>>> from vbpca_py import AutoEncoder
>>> raw = np.array(
... [["west", 10.0], ["east", 20.0], ["north", 30.0], ["west", np.nan]],
... dtype=object,
... )
>>> encoder = AutoEncoder(column_types=["categorical", "continuous"])
>>> encoded = encoder.fit_transform(raw)
>>> encoded.shape, encoded.dtype.name
((4, 4), 'float64')
>>> len(encoder.get_feature_names_out())
4
>>> schema = encoder.encoding_schema_
>>> schema.validate(encoded.shape[1], strict_numeric=True)
>>> [variable.kind for variable in schema.variables]
['categorical', 'continuous']
>>> bool(np.isnan(encoded[3, 3]))
True
>>> decoded = encoder.inverse_transform(encoded)
>>> decoded.shape
(4, 2)
>>> np.testing.assert_allclose(
... decoded[:3, 1].astype(float), [10.0, 20.0, 30.0]
... )
schema describes this fit. For raw-cell validation, fit a fresh
encoder within every training fold; a schema alone does not prevent
preprocessing leakage.
MissingAwareOneHotEncoder ¶
MissingAwareOneHotEncoder(*, handle_unknown: Literal['ignore', 'raise'] = 'ignore', mean_center: bool = False, dtype: type = float, binary: Literal['single', 'both'] = 'single', drop: Literal['first'] | None = None, block_weighting: Literal['none', 'equal_variance'] = 'none', categories: Sequence[Sequence[object] | None] | None = None)
Bases: PreprocessorState
One-hot encode categorical columns while respecting missing values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handle_unknown
|
Literal['ignore', 'raise']
|
|
'ignore'
|
mean_center
|
bool
|
Subtract each output column's observed mean. |
False
|
dtype
|
type
|
Output dtype. |
float
|
binary
|
Literal['single', 'both']
|
|
'single'
|
drop
|
Literal['first'] | None
|
|
None
|
block_weighting
|
Literal['none', 'equal_variance']
|
|
'none'
|
categories
|
Sequence[Sequence[object] | None] | None
|
Optional externally declared category order per column;
|
None
|
After fitting, feature_groups_ gives the input column of every
output column and feature_kinds_ the kind of every input column, so
model selection can hold out whole variables.
encoding_schema_ also records category order, reference drop, fitted
means and weights for categorical decoding and scoring. Centering
is fitted once; transforming new data retains those means.
MissingAwareSparseOneHotEncoder ¶
MissingAwareSparseOneHotEncoder(*, handle_unknown: Literal['ignore', 'raise'] = 'ignore', mean_center: bool = False, dtype: type = float)
Bases: PreprocessorState
Encode numeric categorical columns into sparse indicator blocks.
CSR/CSC/COO input stores observations explicitly, including zeros; absent
entries and stored NaNs are missing. Dense input treats every non-NaN
value as observed, including zero. Each input column has its own sorted
category block, with no reference drop. categories_ retains the flat
output-column category list; feature_groups_ maps each output column
to its input variable. Missing/ignored unknown values have no stored
indicator. Centering adjusts stored indicators without densifying.
MissingAwareOrdinalEncoder ¶
MissingAwareOrdinalEncoder(*, levels: Sequence[Sequence[object]] | None = None, scaler: Literal['standard', 'minmax'] = 'standard', handle_unknown: Literal['ignore', 'raise'] = 'raise')
Bases: PreprocessorState
Code ordered categorical columns as scaled numeric scores.
Each column's levels map to equally spaced scores 0, 1, ..., L - 1 in
their order, which are then scaled like a continuous column, so an
ordinal variable enters the model as one numeric column rather than a
one-hot block. inverse_transform maps scores back to the nearest
level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
levels
|
Sequence[Sequence[object]] | None
|
The level order of every column. By default each column's sorted observed values. |
None
|
scaler
|
Literal['standard', 'minmax']
|
|
'standard'
|
handle_unknown
|
Literal['ignore', 'raise']
|
|
'raise'
|
After fitting, levels_ holds each column's level order,
feature_groups_ maps each output column to its input column and
feature_kinds_ is "ordinal" for every column.
MissingAwareStandardScaler ¶
Bases: _BaseScaler
Standardize continuous columns ignoring missing entries.
Use every finite, nonzero computed standard deviation without an absolute near-zero cutoff. Exactly constant observed columns have zero variance and use a unit denominator. Zero or nonfinite computed deviations also use a unit denominator; wholly missing columns retain NaN moments.
Examples:
>>> import numpy as np
>>> from vbpca_py import MissingAwareStandardScaler
>>> x = np.array([[1.0, 10.0], [3.0, np.nan], [5.0, 16.0]])
>>> scaler = MissingAwareStandardScaler().fit(x)
>>> scaler.mean_.tolist()
[3.0, 13.0]
>>> encoded = scaler.transform(x)
>>> encoded.shape, encoded.dtype.name
((3, 2), 'float64')
>>> bool(np.isnan(encoded[1, 1]))
True
>>> np.testing.assert_allclose(scaler.inverse_transform(encoded), x)
MissingAwareMinMaxScaler ¶
Bases: _BaseScaler
Scale features to [0, 1] range while ignoring missing entries.
Use every finite, nonzero observed range without an absolute near-zero cutoff. Zero or nonfinite ranges use a unit denominator. Wholly missing columns retain NaN extrema.
MissingAwareLogTransformer ¶
Bases: PreprocessorState
Apply log1p (or log(x + offset)) while preserving NaN entries.
This is a pre-scaling transform: compress right-skewed features before standardisation so that the standard deviation better reflects the bulk of the data rather than extreme tails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offset
|
float
|
Additive constant before taking the log. The default
|
1.0
|
MissingAwarePowerTransformer ¶
Bases: PreprocessorState
Yeo-Johnson variance-stabilising transform preserving NaN entries.
Supports mixed-sign data. The transform is applied element-wise
with a per-column lmbda parameter estimated by maximum
likelihood on observed values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
standardize
|
bool
|
If |
True
|
MissingAwareWinsorizer ¶
Bases: PreprocessorState
Clip features at fitted percentiles while preserving NaN entries.
Winsorization prevents outlier-driven variance inflation before scaling, so that z-scoring better equalises feature scales.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lower_quantile
|
float
|
Lower clipping quantile (default |
0.01
|
upper_quantile
|
float
|
Upper clipping quantile (default |
0.99
|
Note
This transform is lossy — inverse_transform is a no-op
(returns data unchanged) because the original tail values
cannot be recovered.
check_data ¶
check_data(x: InputArray, *, mask: Mask | None = None, column_names: Sequence[str] | None = None, skewness_threshold: float = 2.0, outlier_mad_threshold: float = 5.0, near_zero_var_eps: float = 1e-10, missing_fraction_warn: float = 0.5, warn: bool = False, mcar_test: bool = False) -> DataReport
Run preflight diagnostics on a data matrix before VBPCA fitting.
Checks focus on scale comparability — conditions that cause
individual features to dominate the decomposition — rather than
distributional shape. Categorical encodings are also checked: one-hot
blocks are detected (see suggested_feature_groups), and rare levels,
single-indicator binary variables and ordinal-looking integer codes are
flagged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
InputArray
|
Data matrix of shape |
required |
mask
|
Mask | None
|
Optional boolean observation mask with the same shape as |
None
|
column_names
|
Sequence[str] | None
|
Optional feature names for readable messages. |
None
|
skewness_threshold
|
float
|
Absolute skewness above which a feature is
flagged (default |
2.0
|
outlier_mad_threshold
|
float
|
Number of MADs from the median beyond
which an entry is considered an outlier (default |
5.0
|
near_zero_var_eps
|
float
|
Variance threshold below which a feature is
flagged as near-zero-variance (default |
1e-10
|
missing_fraction_warn
|
float
|
Per-feature and per-row missing fraction
above which a warning is emitted (default |
0.5
|
warn
|
bool
|
If |
False
|
mcar_test
|
bool
|
If |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
DataReport
|
class: |
DataReport
|
suggested pre-transforms. |
DataReport
dataclass
¶
DataReport(warnings: list[str] = list(), summary: dict[str, dict[str, float]] = dict(), suggested_pretransforms: dict[str | int, str] = dict(), passed: bool = True, suggested_feature_groups: list[int] | None = None, missingness: dict[str, object] = dict())
Mutable report assembled by :func:check_data preflight validation.
Attributes:
| Name | Type | Description |
|---|---|---|
warnings |
list[str]
|
Human-readable diagnostic messages. |
summary |
dict[str, dict[str, float]]
|
Per-feature statistics dictionary. |
suggested_pretransforms |
dict[str | int, str]
|
Mapping of column index (or name) to a
suggested transform string (e.g. |
passed |
bool
|
|
suggested_feature_groups |
list[int] | None
|
Variable label per column when one-hot
blocks were detected (pass as |
missingness |
dict[str, object]
|
Overall and per-row missing fractions, complete rows,
the number of distinct missingness patterns, rows above the
missing-fraction threshold and, with |
Feature names and output containers¶
All ten preprocessing transformers and native VBPCA implement
get_feature_names_out(input_features=None). String input names are captured
at fit and checked in order. Unnamed inputs and tables with wholly non-string
column labels use positional x0, x1, ... names. Mixed string/non-string
labels and duplicate table columns are rejected. Supplied input_features
must be a unique one-dimensional string sequence matching fitted names when
present. Returned arrays own their name membership.
Scalers, ordinal encoding and the masker preserve the validated input names.
One-hot names follow fitted category order and reference drops; AutoEncoder
uses the original variable's name for each fitted plan. Generated collisions
receive stable __<output-position> suffixes, incremented if necessary.
Existing encoder feature_names_out_ lists agree with default method output
and no longer change during transform. For unnamed fits, the older col0
display prefix becomes x0. VBPCA names use fitted rank, including zero,
rather than later parameter changes. Refit after changing encoding parameters.
Use native sklearn set_output(transform="pandas") or global
config_context(transform_output="pandas") for dense table output. Install
vbpca_py[data] for pandas. Polars 2.x is qualified through
vbpca_py[polars] and transform="polars". Pandas preserves the input index,
including duplicate index labels; Polars preserves row order without adding
an index column. Zero-column dense outputs retain their row count in both
qualified containers. Default NumPy/SciPy outputs and all numerical operations
remain unchanged. Type annotations describe the default numerical return;
configured table output is applied by sklearn's wrapping layer. Inverse
transforms and transform_posterior retain their existing array/record output.
Sparse output cannot be wrapped as a dense pandas/Polars table and raises a clear error without densification. This applies to the sparse one-hot encoder and sparse paths of scalers, AutoEncoder and ObservationMasker. Explicit complex indicator storage retains its real-indicator meaning; Polars can store those values as object columns. Inverse validation still refuses nonzero imaginary components rather than enabling complex-valued model inputs.
For raw mixed string/NaN data, keep the leading masker in pandas mode when the remaining Pipeline uses Polars:
pipeline.set_output(transform="polars")
pipeline.named_steps["observe"].set_output(transform="pandas")
ObservationMasker explicitly refuses raw object output in Polars mode because the native adapter's inference cannot safely represent those buffers. Numeric masker output and subsequent encoded/projection outputs support Polars. Polars input nulls in object columns are converted to canonical NaNs before encoding; this can require an owned input copy. It does not reinterpret ordinary NumPy/Pandas object-category values. AutoEncoder's private nested encoders stay in default mode, avoiding repeated internal table wrapping. The executed example demonstrates names, indices and matching numerical results with both outputs. These behaviors use the native sklearn output API.
Fitted encoding metadata¶
For a complete fit/search/new-data/reconstruction workflow, see the missing-aware Pipeline tutorial. Its inverse uses the fitted model/encoder portion of the Pipeline; the leading masker cannot reconstruct excluded input values or an original observation mask.
schema.validate(n_features) checks feature coverage and categorical decoding
metadata. For a mixed schema, use
schema.validate(n_features, strict_numeric=True) to also check numeric inverse
maps. Each continuous or ordinal variable must have exactly one encoded column,
one finite real scalar fitted offset and a positive finite real scalar weight.
decode_numeric applies
the same numeric checks and returns continuous input units or unrounded ordinal
level-index units. Raw-cell CV validates mixed schemas before model fitting.
A wholly missing numeric training column retains a NaN offset in its fitted schema. It cannot pass strict validation or numeric decoding; declaring ordinal levels does not supply the missing scaling observations. The default validation mode still permits numeric descriptors without affine metadata when only categorical scoring is required.
EncodingSchema
dataclass
¶
Snapshot of dense encoding metadata, in original variable order.
Obtain this from a fitted encoder's encoding_schema_. Category order,
centering and weighting belong to that fit and must match the encoded data
supplied to component CV. This schema does not fit preprocessing per fold.
Attributes:
| Name | Type | Description |
|---|---|---|
variables |
tuple[EncodedVariable, ...]
|
One description per original variable, including numeric variables that are excluded from nominal categorical scoring. |
feature_groups
property
¶
Original variable index of each encoded feature.
validate ¶
Check that metadata describes every encoded feature exactly once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_features
|
int
|
Number of encoded features (columns in native samples-by-features input). |
required |
strict_numeric
|
bool
|
Also require continuous and ordinal variables to have exactly one column, one finite real scalar fitted offset and a positive finite real scalar weight. The default checks their feature coverage only, retaining compatibility with categorical-only scoring schemas. Wholly missing numeric training columns have no fitted offset and cannot pass strict validation. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If columns, kind, category dimensions or affine metadata are inconsistent with the supplied matrix. |
EncodedVariable
dataclass
¶
EncodedVariable(kind: Literal['categorical', 'continuous', 'ordinal'], columns: tuple[int, ...], categories: tuple[object, ...] = (), reference: int | None = None, offset: tuple[float, ...] = (), weight: float = 1.0)
Describe one original variable in an encoded feature matrix.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
Literal['categorical', 'continuous', 'ordinal']
|
Original variable kind; only categorical variables receive nominal categorical scores. |
columns |
tuple[int, ...]
|
Encoded feature indices, in category order with the reference omitted when applicable. |
categories |
tuple[object, ...]
|
Fitted nominal category or ordinal level order. |
reference |
int | None
|
Index of an omitted category, or |
offset |
tuple[float, ...]
|
Unweighted means (or numeric minima) subtracted before scaling. |
weight |
float
|
Positive multiplier applied to the block or numeric column. |
__post_init__ ¶
Own sequence membership while borrowing category label objects.
decode ¶
Undo a categorical block's affine encoding and reference drop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
Float64Array
|
Encoded features-by-samples values for this variable. |
required |
Returns:
| Type | Description |
|---|---|
Float64Array
|
Full category-by-samples values before clipping or normalization. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the variable is not categorical or dimensions differ. |
decode_numeric ¶
Restore continuous values or unrounded ordinal level-index scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
Float64Array
|
Encoded features-by-samples values for this numeric variable. |
required |
Returns:
| Type | Description |
|---|---|
Float64Array
|
Values in continuous input units or ordinal level-index units. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If numeric affine metadata or dimensions are unavailable. |