Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/core_concepts/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,8 @@ Within a structured entry, inheritance is per field, not an all-or-nothing repla
Omission is different from an explicit value. For example, a local
`params={"random_state": None}` overrides an inherited seed where the method accepts it.
Passing `None` is valid only for options that accept it; it does not mean "inherit".
Constructor settings may be NumPy scalars, such as the `np.int64` values of a `GridSearchCV`
grid built with `np.arange`; an entry inherits them as the equal Python values.

```{warning}
Value construction validates portable data and field types. `get_resolved_config()` and
Expand Down
19 changes: 17 additions & 2 deletions pretab/compose/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
from re import fullmatch
from typing import Any

import numpy as np

from ..core.dependencies import _check_optional_dependency
from ..core.parameters import UNSET, _Unset, validate_placement, validate_task
from ..exceptions import IncompatibleParamsError, InvalidParamError, invalid_param_error
Expand Down Expand Up @@ -95,6 +97,16 @@ def _freeze_config_value(value: Any, path: str, active: set[int]) -> Any:
active.remove(identity)


def _builtin_setting(value: Any) -> Any:
"""Return a NumPy scalar setting as the equal Python value; leave others unchanged.

``Preprocessor`` accepts NumPy scalars for its shared settings (for example
``np.int64`` values drawn from a ``GridSearchCV`` grid), while a
:class:`RepresentationConfig` stores only JSON-compatible builtins.
"""
return value.item() if isinstance(value, np.generic) else value


def _config_value_to_json(value: Any) -> Any:
if isinstance(value, Mapping):
return {key: _config_value_to_json(item) for key, item in value.items()}
Expand Down Expand Up @@ -672,9 +684,12 @@ def _resolve_representation(self, raw, *, is_numerical: bool, path: str, is_grou
inherited["min_output_dim"] = self.min_output_dim
inherited["max_output_dim"] = self.max_output_dim
shared = {"degree": self.degree, "task": self.task, **self.seed_kwargs}
params = {key: value for key, value in shared.items() if key in spec.allowed_args}
# Inherited Preprocessor settings may be NumPy scalars; the config stores builtins.
params = {key: _builtin_setting(value) for key, value in shared.items() if key in spec.allowed_args}
params.update(requested.params)
settings = {key: value for key, value in inherited.items() if getattr(requested, key) is UNSET}
settings = {
key: _builtin_setting(value) for key, value in inherited.items() if getattr(requested, key) is UNSET
}
resolved = replace(requested, **settings, params=params)
return _normalize_representation_config(resolved, is_numerical=is_numerical, path=path, is_group=is_group)

Expand Down
70 changes: 70 additions & 0 deletions tests/compose/test_representation_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from types import MappingProxyType
from typing import Any, cast

import numpy as np
import pandas as pd
import pytest
from sklearn.base import clone

Expand Down Expand Up @@ -568,3 +570,71 @@ def unexpected(*args, **kwargs):

monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", unexpected)
assert _normalize_representation_config("rbf", is_numerical=True).target_aware is UNSET


_NUMPY_SETTINGS = [
({"output_dim": np.int64(5)}, {"output_dim": 5}),
({"random_state": np.int64(3)}, {"random_state": 3}),
({"degree": np.int32(2)}, {"degree": 2}),
(
{"target_aware": np.bool_(False), "placement_strategy": np.str_("uniform"), "numerical_method": "minmax"},
{"target_aware": False, "placement_strategy": "uniform", "numerical_method": "minmax"},
),
(
{"adaptive": np.bool_(True), "min_output_dim": np.int64(4), "max_output_dim": np.int64(9)},
{"adaptive": True, "min_output_dim": 4, "max_output_dim": 9},
),
]


@pytest.mark.parametrize(("numpy_settings", "python_settings"), _NUMPY_SETTINGS)
@pytest.mark.parametrize("override", ["rbf", "bspline", "value"])
def test_numpy_scalar_settings_are_inherited_by_overrides(numpy_settings, python_settings, override):
"""A NumPy scalar setting (e.g. from a GridSearchCV grid) failed the builtin-only
RepresentationConfig check as soon as a per-feature override inherited it."""
rng = np.random.default_rng(1)
frame = pd.DataFrame({"x": rng.uniform(0.5, 3, 120), "z": rng.normal(size=120)})
target = np.sin(2 * frame["x"].to_numpy()) + rng.normal(scale=0.1, size=120)
requested = RepresentationConfig("rbf") if override == "value" else override

from_numpy = Preprocessor(feature_preprocessing={"x": requested}, **numpy_settings).fit(frame, target)
from_python = Preprocessor(feature_preprocessing={"x": requested}, **python_settings).fit(frame, target)

np.testing.assert_array_equal(
from_numpy.transform(frame, return_array=True), from_python.transform(frame, return_array=True)
)
assert from_numpy.get_resolved_config() == from_python.get_resolved_config()
json.dumps(from_numpy.to_spec(), allow_nan=False)


def test_numpy_scalar_settings_are_inherited_by_feature_groups():
rng = np.random.default_rng(2)
frame = pd.DataFrame({"x": rng.normal(size=80), "z": rng.normal(size=80)})
group = FeatureGroup("pair", ["x", "z"], RepresentationConfig("tensorspline", output_dim=4))

from_numpy = Preprocessor(feature_groups=[group], degree=cast(Any, np.int64(2)), random_state=np.int64(0)).fit(
frame
)
from_python = Preprocessor(feature_groups=[group], degree=2, random_state=0).fit(frame)

np.testing.assert_array_equal(from_numpy.transform(frame), from_python.transform(frame))


def test_grid_search_over_numpy_output_dims_with_an_override():
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline

rng = np.random.default_rng(3)
frame = pd.DataFrame({"x": rng.uniform(0, 3, 90), "z": rng.normal(size=90)})
target = np.sin(2 * frame["x"].to_numpy()) + rng.normal(scale=0.1, size=90)
processor = Preprocessor(
numerical_method="rbf", feature_preprocessing={"z": "bspline"}, target_aware=False, placement_strategy="uniform"
)
search = GridSearchCV(
Pipeline([("pre", processor), ("model", Ridge())]), {"pre__output_dim": np.arange(4, 8, 3)}, cv=2
)
search.set_params(error_score="raise")
search.fit(frame, target)

assert search.best_params_["pre__output_dim"] in (4, 7)
Loading