From bc88d2379f5277a3c575749e60cf4726c6051a97 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 9 Nov 2026 22:26:24 +0100 Subject: [PATCH 01/86] feat(python): require Python 3.11 --- .github/workflows/build-check.yml | 2 +- .github/workflows/ci.yml | 12 +- .github/workflows/publish-pypi.yml | 2 +- .github/workflows/publish-testpypi.yml | 4 +- CHANGELOG.md | 9 + README.md | 4 +- docs/developer_guide/contributing.md | 2 +- docs/developer_guide/release.md | 2 +- docs/getting_started/installation.md | 20 +- examples/pretab-chebyshev/pyproject.toml | 2 +- poetry.lock | 433 +---------------------- pretab/extension.py | 5 +- pyproject.toml | 6 +- 13 files changed, 56 insertions(+), 447 deletions(-) diff --git a/.github/workflows/build-check.yml b/.github/workflows/build-check.yml index 5507358..05bc1e9 100644 --- a/.github/workflows/build-check.yml +++ b/.github/workflows/build-check.yml @@ -22,7 +22,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d5412d..0b0def5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -64,7 +64,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -95,7 +95,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -127,7 +127,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] - python-version: ["3.10", "3.11", "3.12", "3.13"] + python-version: ["3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 @@ -158,13 +158,13 @@ jobs: run: poetry run pytest tests/ -v minimum-deps: - name: Minimum dependencies (Python 3.10) + name: Minimum dependencies (Python 3.11) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install with minimum supported dependency series run: >- python -m pip install . pytest pytest-cov diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index ada08e2..0a0b5f9 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -44,7 +44,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry diff --git a/.github/workflows/publish-testpypi.yml b/.github/workflows/publish-testpypi.yml index f50e178..cd5b48f 100644 --- a/.github/workflows/publish-testpypi.yml +++ b/.github/workflows/publish-testpypi.yml @@ -39,7 +39,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -107,7 +107,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install from TestPyPI (with retry) run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 2768894..4d4af5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ This project adheres to [Semantic Versioning](https://semver.org/) and uses Going forward, this file is updated automatically by `cz bump` on each release. +## Unreleased + +### Removed + +- Python 3.10 support. PreTab 1.1 requires Python 3.11 to 3.13 + (`>=3.11,<3.14`), matching DeepTab 2.1. PreTab 1.0.0 is the final release + for Python 3.10; install `pretab<1.1` if you cannot upgrade Python. See the + [migration guidance](docs/getting_started/installation.md#python-310-migration). + ## v1.0.0 (2026-09-06) First stable release, consolidating the release-candidate cycle (`rc1`-`rc5`) below into one diff --git a/README.md b/README.md index e6c38ce..914f217 100644 --- a/README.md +++ b/README.md @@ -179,7 +179,9 @@ pip install "pretab[all]" # both of the above ``` > **Note:** The core install has no heavy dependencies. Each extra is opt-in and only -> needed if you use the corresponding strategy. PreTab requires Python 3.10 to 3.13. +> needed if you use the corresponding strategy. PreTab 1.1 requires Python 3.11 to 3.13. +> Python 3.10 users must stay on `pretab<1.1`; see the +> [migration guidance](docs/getting_started/installation.md#python-310-migration). **From source:** diff --git a/docs/developer_guide/contributing.md b/docs/developer_guide/contributing.md index 5054dfd..d09e0b4 100644 --- a/docs/developer_guide/contributing.md +++ b/docs/developer_guide/contributing.md @@ -203,7 +203,7 @@ your test suite keeps a future refactor from silently breaking compatibility wit ### Before you push Run `just check` and `just test` locally; together they cover most of what CI checks, though -CI additionally runs across the full Python 3.10-3.13 matrix, builds the package, and +CI additionally runs across the full Python 3.11-3.13 matrix, builds the package, and enforces a branch-coverage threshold. ```bash diff --git a/docs/developer_guide/release.md b/docs/developer_guide/release.md index 30cbe1a..cca20ec 100644 --- a/docs/developer_guide/release.md +++ b/docs/developer_guide/release.md @@ -42,7 +42,7 @@ commit before anything is uploaded, rather than trusting whatever last passed on | Lint (`ruff check`, `ruff format --check`) | `lint` | | Type checking (`pyright`) | `typecheck` | | Package build + `twine check` | `build` | -| Full test matrix (3.10-3.13, 3 OSes) | `tests` | +| Full test matrix (3.11-3.13, 3 OSes) | `tests` | | Minimum supported dependency versions | `minimum-deps` | | Smoke test + quickstart script | `smoke` | | Coverage (fails under 90%) | `coverage` | diff --git a/docs/getting_started/installation.md b/docs/getting_started/installation.md index 184e5df..fb21ee9 100644 --- a/docs/getting_started/installation.md +++ b/docs/getting_started/installation.md @@ -1,6 +1,6 @@ # Installation -pretab supports Python 3.10 to 3.13, with the following minimum core dependency versions: +PreTab 1.1 supports Python 3.11 to 3.13, with the following minimum core dependency versions: | Dependency | Minimum | | -------------- | ------- | @@ -25,6 +25,24 @@ estimator-tag APIs used by PreTab. pip install pretab ``` +### Python 3.10 migration + +Starting with PreTab 1.1, the supported Python range is `>=3.11,<3.14`. +Upgrade to Python 3.11, 3.12, or 3.13 before installing PreTab 1.1. The minimum +NumPy, pandas, SciPy, and scikit-learn versions have not changed. + +If you must keep Python 3.10, install the last compatible release: + +```bash +pip install "pretab<1.1" +``` + +```{warning} +PreTab 1.0.0 is the final release supporting Python 3.10. It does not include +the fixes or features in 1.1. Python 3.10 reached end of life in October 2026; +staying on an older PreTab release does not provide Python security updates. +``` + ### Optional extras Language-embedding features depend on diff --git a/examples/pretab-chebyshev/pyproject.toml b/examples/pretab-chebyshev/pyproject.toml index 7849367..ad9b3f4 100644 --- a/examples/pretab-chebyshev/pyproject.toml +++ b/examples/pretab-chebyshev/pyproject.toml @@ -7,7 +7,7 @@ name = "pretab-chebyshev" version = "0.1.0" description = "Example PreTab extension: a Chebyshev polynomial feature representation." readme = "README.md" -requires-python = ">=3.10" +requires-python = ">=3.11" license = { text = "MIT" } dependencies = [ "pretab", diff --git a/poetry.lock b/poetry.lock index aa4f1d2..5aa55be 100644 --- a/poetry.lock +++ b/poetry.lock @@ -58,7 +58,6 @@ files = [ ] [package.dependencies] -exceptiongroup = {version = ">=1.0.2", markers = "python_version < \"3.11\""} idna = ">=2.8" typing_extensions = {version = ">=4.5", markers = "python_version < \"3.13\""} @@ -131,7 +130,7 @@ description = "Backport of CPython tarfile module" optional = false python-versions = ">=3.8" groups = ["dev"] -markers = "python_version < \"3.12\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\") or python_version < \"3.12\" and platform_machine != \"ppc64le\" and platform_machine != \"s390x\"" +markers = "python_version == \"3.11\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\" or platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34"}, {file = "backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991"}, @@ -615,9 +614,6 @@ files = [ {file = "coverage-7.15.1.tar.gz", hash = "sha256:165e9949eaf222ef1f018635d0d7f368a23bfe0212af558534c40d8c04686d67"}, ] -[package.dependencies] -tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""} - [package.extras] toml = ["tomli ; python_full_version <= \"3.11.0a6\""] @@ -680,7 +676,6 @@ files = [ [package.dependencies] cffi = {version = ">=2.0.0", markers = "platform_python_implementation != \"PyPy\""} -typing-extensions = {version = ">=4.13.2", markers = "python_full_version < \"3.11.0\""} [package.extras] ssh = ["bcrypt (>=3.1.5)"] @@ -897,19 +892,6 @@ files = [ {file = "distlib-0.4.3.tar.gz", hash = "sha256:f152097224a0ae24be5a0f6bae1b9359af82133bce63f98a95f86cae1aede9ed"}, ] -[[package]] -name = "docutils" -version = "0.21.2" -description = "Docutils -- Python Documentation Utilities" -optional = false -python-versions = ">=3.9" -groups = ["dev", "docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2"}, - {file = "docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f"}, -] - [[package]] name = "docutils" version = "0.22.4" @@ -917,31 +899,11 @@ description = "Docutils -- Python Documentation Utilities" optional = false python-versions = ">=3.9" groups = ["dev", "docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "docutils-0.22.4-py3-none-any.whl", hash = "sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de"}, {file = "docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968"}, ] -[[package]] -name = "exceptiongroup" -version = "1.3.1" -description = "Backport of PEP 654 (exception groups)" -optional = false -python-versions = ">=3.7" -groups = ["main", "dev"] -files = [ - {file = "exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598"}, - {file = "exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219"}, -] -markers = {main = "python_version == \"3.10\" and (extra == \"embeddings\" or extra == \"all\")", dev = "python_version == \"3.10\""} - -[package.dependencies] -typing-extensions = {version = ">=4.6.0", markers = "python_version < \"3.13\""} - -[package.extras] -test = ["pytest (>=6)"] - [[package]] name = "executing" version = "2.2.1" @@ -1219,7 +1181,7 @@ description = "Read metadata from Python packages" optional = false python-versions = ">=3.10" groups = ["dev"] -markers = "python_version < \"3.12\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\") or python_version < \"3.12\" and platform_machine != \"ppc64le\" and platform_machine != \"s390x\"" +markers = "python_version == \"3.11\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\" or platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "importlib_metadata-9.0.0-py3-none-any.whl", hash = "sha256:2d21d1cc5a017bd0559e36150c21c830ab1dc304dedd1b7ea85d20f45ef3edd7"}, {file = "importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc"}, @@ -1283,46 +1245,6 @@ pyqt5 = ["pyqt5"] pyside6 = ["pyside6"] test = ["flaky", "ipyparallel", "pre-commit", "pytest (>=7.0,<10)", "pytest-asyncio (>=0.23.5)", "pytest-cov", "pytest-timeout"] -[[package]] -name = "ipython" -version = "8.39.0" -description = "IPython: Productive Interactive Computing" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -markers = "python_version == \"3.10\"" -files = [ - {file = "ipython-8.39.0-py3-none-any.whl", hash = "sha256:bb3c51c4fa8148ab1dea07a79584d1c854e234ea44aa1283bcb37bc75054651f"}, - {file = "ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624"}, -] - -[package.dependencies] -colorama = {version = "*", markers = "sys_platform == \"win32\""} -decorator = "*" -exceptiongroup = {version = "*", markers = "python_version < \"3.11\""} -jedi = ">=0.16" -matplotlib-inline = "*" -pexpect = {version = ">4.3", markers = "sys_platform != \"win32\" and sys_platform != \"emscripten\""} -prompt_toolkit = ">=3.0.41,<3.1.0" -pygments = ">=2.4.0" -stack_data = "*" -traitlets = ">=5.13.0" -typing_extensions = {version = ">=4.6", markers = "python_version < \"3.12\""} - -[package.extras] -all = ["ipython[black,doc,kernel,matplotlib,nbconvert,nbformat,notebook,parallel,qtconsole]", "ipython[test,test-extra]"] -black = ["black"] -doc = ["docrepr", "exceptiongroup", "intersphinx_registry", "ipykernel", "ipython[test]", "matplotlib", "setuptools (>=18.5)", "sphinx (>=1.3)", "sphinx-rtd-theme", "sphinxcontrib-jquery", "tomli ; python_version < \"3.11\"", "typing_extensions"] -kernel = ["ipykernel"] -matplotlib = ["matplotlib"] -nbconvert = ["nbconvert"] -nbformat = ["nbformat"] -notebook = ["ipywidgets", "notebook"] -parallel = ["ipyparallel"] -qtconsole = ["qtconsole"] -test = ["packaging", "pickleshare", "pytest", "pytest-asyncio (<0.22)", "testpath"] -test-extra = ["curio", "ipython[test]", "jupyter_ai", "matplotlib (!=3.2.0)", "nbformat", "numpy (>=1.23)", "pandas", "trio"] - [[package]] name = "ipython" version = "9.15.0" @@ -1330,7 +1252,6 @@ description = "IPython: Productive Interactive Computing" optional = false python-versions = ">=3.11" groups = ["dev"] -markers = "python_version >= \"3.11\"" files = [ {file = "ipython-9.15.0-py3-none-any.whl", hash = "sha256:515ad9c3cdf0c932a5a9f6245419e8aba706b7bd03c3e1d3a1c83d9351d6aa6e"}, {file = "ipython-9.15.0.tar.gz", hash = "sha256:da2819ce2aa83135257df830660b1176d986c3d2876db24df01974fa955b2756"}, @@ -1365,7 +1286,6 @@ description = "Defines a variety of Pygments lexers for highlighting IPython cod optional = false python-versions = ">=3.8" groups = ["dev"] -markers = "python_version >= \"3.11\"" files = [ {file = "ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c"}, {file = "ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81"}, @@ -1630,32 +1550,6 @@ dask = ["dask[array,dataframe,distributed] (>=2.0.0)", "pandas (>=0.24.0)"] pandas = ["pandas (>=0.24.0)"] scikit-learn = ["scikit-learn (>=0.24.2)"] -[[package]] -name = "markdown-it-py" -version = "3.0.0" -description = "Python port of markdown-it. Markdown parsing, done right!" -optional = false -python-versions = ">=3.8" -groups = ["main", "dev", "docs"] -files = [ - {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"}, - {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"}, -] -markers = {main = "python_version == \"3.10\" and (extra == \"embeddings\" or extra == \"all\")", dev = "python_version == \"3.10\"", docs = "python_version == \"3.10\""} - -[package.dependencies] -mdurl = ">=0.1,<1.0" - -[package.extras] -benchmarking = ["psutil", "pytest", "pytest-benchmark"] -code-style = ["pre-commit (>=3.0,<4.0)"] -compare = ["commonmark (>=0.9,<1.0)", "markdown (>=3.4,<4.0)", "mistletoe (>=1.0,<2.0)", "mistune (>=2.0,<3.0)", "panflute (>=2.3,<3.0)"] -linkify = ["linkify-it-py (>=1,<3)"] -plugins = ["mdit-py-plugins"] -profiling = ["gprof2dot"] -rtd = ["jupyter_sphinx", "mdit-py-plugins", "myst-parser", "pyyaml", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx_book_theme"] -testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"] - [[package]] name = "markdown-it-py" version = "4.2.0" @@ -1667,7 +1561,7 @@ files = [ {file = "markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a"}, {file = "markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49"}, ] -markers = {main = "python_version >= \"3.11\" and (extra == \"embeddings\" or extra == \"all\")", dev = "python_version >= \"3.11\"", docs = "python_version >= \"3.11\""} +markers = {main = "extra == \"embeddings\" or extra == \"all\""} [package.dependencies] mdurl = ">=0.1,<1.0" @@ -1940,34 +1834,6 @@ files = [ {file = "msgpack-1.2.1.tar.gz", hash = "sha256:04c721c2c7448767e9e3f2520a475663d8ee0f09c31890f6d2bd70fd636a9647"}, ] -[[package]] -name = "myst-parser" -version = "4.0.1" -description = "An extended [CommonMark](https://spec.commonmark.org/) compliant parser," -optional = false -python-versions = ">=3.10" -groups = ["docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "myst_parser-4.0.1-py3-none-any.whl", hash = "sha256:9134e88959ec3b5780aedf8a99680ea242869d012e8821db3126d427edc9c95d"}, - {file = "myst_parser-4.0.1.tar.gz", hash = "sha256:5cfea715e4f3574138aecbf7d54132296bfd72bb614d31168f48c477a830a7c4"}, -] - -[package.dependencies] -docutils = ">=0.19,<0.22" -jinja2 = "*" -markdown-it-py = ">=3.0,<4.0" -mdit-py-plugins = ">=0.4.1,<1.0" -pyyaml = "*" -sphinx = ">=7,<9" - -[package.extras] -code-style = ["pre-commit (>=4.0,<5.0)"] -linkify = ["linkify-it-py (>=2.0,<3.0)"] -rtd = ["ipython", "sphinx (>=7)", "sphinx-autodoc2 (>=0.5.0,<0.6.0)", "sphinx-book-theme (>=1.1,<2.0)", "sphinx-copybutton", "sphinx-design", "sphinx-pyscript", "sphinx-tippy (>=0.4.3)", "sphinx-togglebutton", "sphinxext-opengraph (>=0.9.0,<0.10.0)", "sphinxext-rediraffe (>=0.2.7,<0.3.0)"] -testing = ["beautifulsoup4", "coverage[toml]", "defusedxml", "pygments (<2.19)", "pytest (>=8,<9)", "pytest-cov", "pytest-param-files (>=0.6.0,<0.7.0)", "pytest-regressions", "sphinx-pytest"] -testing-docutils = ["pygments", "pytest (>=8,<9)", "pytest-param-files (>=0.6.0,<0.7.0)"] - [[package]] name = "myst-parser" version = "5.1.0" @@ -1975,7 +1841,6 @@ description = "An extended [CommonMark](https://spec.commonmark.org/) compliant optional = false python-versions = ">=3.11" groups = ["docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "myst_parser-5.1.0-py3-none-any.whl", hash = "sha256:9c91c52b3cdb4d94a6506e4fab4e2f296c7623a0da0dcbe6de1565c3dad67a8a"}, {file = "myst_parser-5.1.0.tar.gz", hash = "sha256:ab69322dc6719dcc7f296479dbb70181b66df6ed315064f92dbc85c0e1bf2f02"}, @@ -2003,7 +1868,6 @@ description = "Extremely lightweight compatibility layer between dataframe libra optional = false python-versions = ">=3.10" groups = ["main"] -markers = "python_version >= \"3.11\"" files = [ {file = "narwhals-2.24.0-py3-none-any.whl", hash = "sha256:42fdedf44e5b2ca7505630d45b4ac3058f38d8485cba9fe1652ca23152df7489"}, {file = "narwhals-2.24.0.tar.gz", hash = "sha256:b5c0f684ccd9d7475b564111e319a4964abcf2baf79d3cf6b1003d06ac9b828d"}, @@ -2035,27 +1899,6 @@ files = [ {file = "nest_asyncio2-1.7.2.tar.gz", hash = "sha256:1921d70b92cc4612c374928d081552efb59b83d91b2b789d935c665fa01729a8"}, ] -[[package]] -name = "networkx" -version = "3.4.2" -description = "Python package for creating and manipulating graphs and networks" -optional = true -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\" and (extra == \"embeddings\" or extra == \"all\")" -files = [ - {file = "networkx-3.4.2-py3-none-any.whl", hash = "sha256:df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f"}, - {file = "networkx-3.4.2.tar.gz", hash = "sha256:307c3669428c5362aab27c8a1260aa8f47c4e91d3891f48be0141738d8d053e1"}, -] - -[package.extras] -default = ["matplotlib (>=3.7)", "numpy (>=1.24)", "pandas (>=2.0)", "scipy (>=1.10,!=1.11.0,!=1.11.1)"] -developer = ["changelist (==0.5)", "mypy (>=1.1)", "pre-commit (>=3.2)", "rtoml"] -doc = ["intersphinx-registry", "myst-nb (>=1.1)", "numpydoc (>=1.8.0)", "pillow (>=9.4)", "pydata-sphinx-theme (>=0.15)", "sphinx (>=7.3)", "sphinx-gallery (>=0.16)", "texext (>=0.6.7)"] -example = ["cairocffi (>=1.7)", "contextily (>=1.6)", "igraph (>=0.11)", "momepy (>=0.7.2)", "osmnx (>=1.9)", "scikit-learn (>=1.5)", "seaborn (>=0.13)"] -extra = ["lxml (>=4.6)", "pydot (>=3.0.1)", "pygraphviz (>=1.14)", "sympy (>=1.10)"] -test = ["pytest (>=7.2)", "pytest-cov (>=4.0)"] - [[package]] name = "networkx" version = "3.6.1" @@ -2063,7 +1906,7 @@ description = "Python package for creating and manipulating graphs and networks" optional = true python-versions = "!=3.14.1,>=3.11" groups = ["main"] -markers = "python_version >= \"3.11\" and (extra == \"embeddings\" or extra == \"all\")" +markers = "extra == \"embeddings\" or extra == \"all\"" files = [ {file = "networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762"}, {file = "networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509"}, @@ -2129,72 +1972,6 @@ files = [ {file = "nodeenv-1.10.0.tar.gz", hash = "sha256:996c191ad80897d076bdfba80a41994c2b47c68e224c542b48feba42ba00f8bb"}, ] -[[package]] -name = "numpy" -version = "2.2.6" -description = "Fundamental package for array computing in Python" -optional = false -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\"" -files = [ - {file = "numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb"}, - {file = "numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90"}, - {file = "numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163"}, - {file = "numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf"}, - {file = "numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83"}, - {file = "numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915"}, - {file = "numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680"}, - {file = "numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289"}, - {file = "numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d"}, - {file = "numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491"}, - {file = "numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a"}, - {file = "numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf"}, - {file = "numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1"}, - {file = "numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab"}, - {file = "numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47"}, - {file = "numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282"}, - {file = "numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87"}, - {file = "numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249"}, - {file = "numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49"}, - {file = "numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de"}, - {file = "numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4"}, - {file = "numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566"}, - {file = "numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f"}, - {file = "numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f"}, - {file = "numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868"}, - {file = "numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d"}, - {file = "numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd"}, - {file = "numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8"}, - {file = "numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f"}, - {file = "numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa"}, - {file = "numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571"}, - {file = "numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1"}, - {file = "numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff"}, - {file = "numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00"}, - {file = "numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd"}, -] - [[package]] name = "numpy" version = "2.4.6" @@ -2703,7 +2480,6 @@ files = [ [package.dependencies] numpy = [ - {version = ">=1.22.4", markers = "python_version < \"3.11\""}, {version = ">=1.23.2", markers = "python_version == \"3.11\""}, {version = ">=1.26.0", markers = "python_version >= \"3.12\""}, ] @@ -3130,12 +2906,10 @@ files = [ [package.dependencies] colorama = {version = ">=0.4", markers = "sys_platform == \"win32\""} -exceptiongroup = {version = ">=1", markers = "python_version < \"3.11\""} iniconfig = ">=1.0.1" packaging = ">=22" pluggy = ">=1.5,<2" pygments = ">=2.7.2" -tomli = {version = ">=1", markers = "python_version < \"3.11\""} [package.extras] dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "requests", "setuptools", "xmlschema"] @@ -3647,7 +3421,6 @@ description = "Manipulate well-formed Roman numerals" optional = false python-versions = ">=3.10" groups = ["docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "roman_numerals-4.1.0-py3-none-any.whl", hash = "sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7"}, {file = "roman_numerals-4.1.0.tar.gz", hash = "sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2"}, @@ -3724,63 +3497,6 @@ testing = ["fsspec (>=2024.6.0)", "h5py (>=3.7.0)", "hypothesis (>=6.70.2)", "py tf-nightly = ["safetensors[numpy]", "tf-nightly"] torch = ["safetensors[numpy]", "torch (>=2.4)"] -[[package]] -name = "scikit-learn" -version = "1.7.2" -description = "A set of python modules for machine learning and data mining" -optional = false -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\"" -files = [ - {file = "scikit_learn-1.7.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6b33579c10a3081d076ab403df4a4190da4f4432d443521674637677dc91e61f"}, - {file = "scikit_learn-1.7.2-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:36749fb62b3d961b1ce4fedf08fa57a1986cd409eff2d783bca5d4b9b5fce51c"}, - {file = "scikit_learn-1.7.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7a58814265dfc52b3295b1900cfb5701589d30a8bb026c7540f1e9d3499d5ec8"}, - {file = "scikit_learn-1.7.2-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a847fea807e278f821a0406ca01e387f97653e284ecbd9750e3ee7c90347f18"}, - {file = "scikit_learn-1.7.2-cp310-cp310-win_amd64.whl", hash = "sha256:ca250e6836d10e6f402436d6463d6c0e4d8e0234cfb6a9a47835bd392b852ce5"}, - {file = "scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e"}, - {file = "scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1"}, - {file = "scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d"}, - {file = "scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1"}, - {file = "scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1"}, - {file = "scikit_learn-1.7.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8d91a97fa2b706943822398ab943cde71858a50245e31bc71dba62aab1d60a96"}, - {file = "scikit_learn-1.7.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:acbc0f5fd2edd3432a22c69bed78e837c70cf896cd7993d71d51ba6708507476"}, - {file = "scikit_learn-1.7.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e5bf3d930aee75a65478df91ac1225ff89cd28e9ac7bd1196853a9229b6adb0b"}, - {file = "scikit_learn-1.7.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4d6e9deed1a47aca9fe2f267ab8e8fe82ee20b4526b2c0cd9e135cea10feb44"}, - {file = "scikit_learn-1.7.2-cp312-cp312-win_amd64.whl", hash = "sha256:6088aa475f0785e01bcf8529f55280a3d7d298679f50c0bb70a2364a82d0b290"}, - {file = "scikit_learn-1.7.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0b7dacaa05e5d76759fb071558a8b5130f4845166d88654a0f9bdf3eb57851b7"}, - {file = "scikit_learn-1.7.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:abebbd61ad9e1deed54cca45caea8ad5f79e1b93173dece40bb8e0c658dbe6fe"}, - {file = "scikit_learn-1.7.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:502c18e39849c0ea1a5d681af1dbcf15f6cce601aebb657aabbfe84133c1907f"}, - {file = "scikit_learn-1.7.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a4c328a71785382fe3fe676a9ecf2c86189249beff90bf85e22bdb7efaf9ae0"}, - {file = "scikit_learn-1.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:63a9afd6f7b229aad94618c01c252ce9e6fa97918c5ca19c9a17a087d819440c"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9acb6c5e867447b4e1390930e3944a005e2cb115922e693c08a323421a6966e8"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:2a41e2a0ef45063e654152ec9d8bcfc39f7afce35b08902bfe290c2498a67a6a"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98335fb98509b73385b3ab2bd0639b1f610541d3988ee675c670371d6a87aa7c"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:191e5550980d45449126e23ed1d5e9e24b2c68329ee1f691a3987476e115e09c"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-win_amd64.whl", hash = "sha256:57dc4deb1d3762c75d685507fbd0bc17160144b2f2ba4ccea5dc285ab0d0e973"}, - {file = "scikit_learn-1.7.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fa8f63940e29c82d1e67a45d5297bdebbcb585f5a5a50c4914cc2e852ab77f33"}, - {file = "scikit_learn-1.7.2-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:f95dc55b7902b91331fa4e5845dd5bde0580c9cd9612b1b2791b7e80c3d32615"}, - {file = "scikit_learn-1.7.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9656e4a53e54578ad10a434dc1f993330568cfee176dff07112b8785fb413106"}, - {file = "scikit_learn-1.7.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96dc05a854add0e50d3f47a1ef21a10a595016da5b007c7d9cd9d0bffd1fcc61"}, - {file = "scikit_learn-1.7.2-cp314-cp314-win_amd64.whl", hash = "sha256:bb24510ed3f9f61476181e4db51ce801e2ba37541def12dc9333b946fc7a9cf8"}, - {file = "scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda"}, -] - -[package.dependencies] -joblib = ">=1.2.0" -numpy = ">=1.22.0" -scipy = ">=1.8.0" -threadpoolctl = ">=3.1.0" - -[package.extras] -benchmark = ["matplotlib (>=3.5.0)", "memory_profiler (>=0.57.0)", "pandas (>=1.4.0)"] -build = ["cython (>=3.0.10)", "meson-python (>=0.17.1)", "numpy (>=1.22.0)", "scipy (>=1.8.0)"] -docs = ["Pillow (>=8.4.0)", "matplotlib (>=3.5.0)", "memory_profiler (>=0.57.0)", "numpydoc (>=1.2.0)", "pandas (>=1.4.0)", "plotly (>=5.14.0)", "polars (>=0.20.30)", "pooch (>=1.6.0)", "pydata-sphinx-theme (>=0.15.3)", "scikit-image (>=0.19.0)", "seaborn (>=0.9.0)", "sphinx (>=7.3.7)", "sphinx-copybutton (>=0.5.2)", "sphinx-design (>=0.5.0)", "sphinx-design (>=0.6.0)", "sphinx-gallery (>=0.17.1)", "sphinx-prompt (>=1.4.0)", "sphinx-remove-toctrees (>=1.0.0.post1)", "sphinxcontrib-sass (>=0.3.4)", "sphinxext-opengraph (>=0.9.1)", "towncrier (>=24.8.0)"] -examples = ["matplotlib (>=3.5.0)", "pandas (>=1.4.0)", "plotly (>=5.14.0)", "pooch (>=1.6.0)", "scikit-image (>=0.19.0)", "seaborn (>=0.9.0)"] -install = ["joblib (>=1.2.0)", "numpy (>=1.22.0)", "scipy (>=1.8.0)", "threadpoolctl (>=3.1.0)"] -maintenance = ["conda-lock (==3.0.1)"] -tests = ["matplotlib (>=3.5.0)", "mypy (>=1.15)", "numpydoc (>=1.2.0)", "pandas (>=1.4.0)", "polars (>=0.20.30)", "pooch (>=1.6.0)", "pyamg (>=4.2.1)", "pyarrow (>=12.0.0)", "pytest (>=7.1.2)", "pytest-cov (>=2.9.0)", "ruff (>=0.11.7)", "scikit-image (>=0.19.0)"] - [[package]] name = "scikit-learn" version = "1.9.0" @@ -3788,7 +3504,6 @@ description = "A set of python modules for machine learning and data mining" optional = false python-versions = ">=3.11" groups = ["main"] -markers = "python_version >= \"3.11\"" files = [ {file = "scikit_learn-1.9.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9db6f4d34e68c8899e4cab27fdf8eafe6ed21f2ba52ceb25ea250cd237f8e47b"}, {file = "scikit_learn-1.9.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:f401448645a3e7bc115aa3c094097865155b34bff1cba8101857d9104e99074c"}, @@ -3839,71 +3554,6 @@ install = ["joblib (>=1.4.0)", "narwhals (>=2.0.1)", "numpy (>=1.24.1)", "scipy maintenance = ["conda-lock (==3.0.1)"] tests = ["matplotlib (>=3.6.1)", "mypy (>=1.15)", "numpydoc (>=1.2.0)", "pandas (>=1.5.0)", "polars (>=0.20.30)", "pooch (>=1.8.0)", "pyamg (>=5.0.0)", "pyarrow (>=13.0.0)", "pytest (>=7.1.2)", "pytest-cov (>=2.9.0)", "rich (>=14.1.0)", "ruff (>=0.12.2)"] -[[package]] -name = "scipy" -version = "1.15.3" -description = "Fundamental algorithms for scientific computing in Python" -optional = false -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\"" -files = [ - {file = "scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c"}, - {file = "scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253"}, - {file = "scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f"}, - {file = "scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92"}, - {file = "scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82"}, - {file = "scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40"}, - {file = "scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e"}, - {file = "scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c"}, - {file = "scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1"}, - {file = "scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889"}, - {file = "scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982"}, - {file = "scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9"}, - {file = "scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594"}, - {file = "scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c"}, - {file = "scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45"}, - {file = "scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49"}, - {file = "scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e"}, - {file = "scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539"}, - {file = "scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730"}, - {file = "scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825"}, - {file = "scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7"}, - {file = "scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11"}, - {file = "scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126"}, - {file = "scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb"}, - {file = "scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723"}, - {file = "scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb"}, - {file = "scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4"}, - {file = "scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5"}, - {file = "scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca"}, - {file = "scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf"}, -] - -[package.dependencies] -numpy = ">=1.23.5,<2.5" - -[package.extras] -dev = ["cython-lint (>=0.12.2)", "doit (>=0.36.0)", "mypy (==1.10.0)", "pycodestyle", "pydevtool", "rich-click", "ruff (>=0.0.292)", "types-psutil", "typing_extensions"] -doc = ["intersphinx_registry", "jupyterlite-pyodide-kernel", "jupyterlite-sphinx (>=0.19.1)", "jupytext", "matplotlib (>=3.5)", "myst-nb", "numpydoc", "pooch", "pydata-sphinx-theme (>=0.15.2)", "sphinx (>=5.0.0,<8.0.0)", "sphinx-copybutton", "sphinx-design (>=0.4.0)"] -test = ["Cython", "array-api-strict (>=2.0,<2.1.1)", "asv", "gmpy2", "hypothesis (>=6.30)", "meson", "mpmath", "ninja ; sys_platform != \"emscripten\"", "pooch", "pytest", "pytest-cov", "pytest-timeout", "pytest-xdist", "scikit-umfpack", "threadpoolctl"] - [[package]] name = "scipy" version = "1.17.1" @@ -4177,43 +3827,6 @@ files = [ {file = "soupsieve-2.8.4.tar.gz", hash = "sha256:e121fd02e975c695e4e9e8774a5ee35d74714b59307868dcc5319ad2d9e3328e"}, ] -[[package]] -name = "sphinx" -version = "8.1.3" -description = "Python documentation generator" -optional = false -python-versions = ">=3.10" -groups = ["docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "sphinx-8.1.3-py3-none-any.whl", hash = "sha256:09719015511837b76bf6e03e42eb7595ac8c2e41eeb9c29c5b755c6b677992a2"}, - {file = "sphinx-8.1.3.tar.gz", hash = "sha256:43c1911eecb0d3e161ad78611bc905d1ad0e523e4ddc202a58a821773dc4c927"}, -] - -[package.dependencies] -alabaster = ">=0.7.14" -babel = ">=2.13" -colorama = {version = ">=0.4.6", markers = "sys_platform == \"win32\""} -docutils = ">=0.20,<0.22" -imagesize = ">=1.3" -Jinja2 = ">=3.1" -packaging = ">=23.0" -Pygments = ">=2.17" -requests = ">=2.30.0" -snowballstemmer = ">=2.2" -sphinxcontrib-applehelp = ">=1.0.7" -sphinxcontrib-devhelp = ">=1.0.6" -sphinxcontrib-htmlhelp = ">=2.0.6" -sphinxcontrib-jsmath = ">=1.0.1" -sphinxcontrib-qthelp = ">=1.0.6" -sphinxcontrib-serializinghtml = ">=1.1.9" -tomli = {version = ">=2", markers = "python_version < \"3.11\""} - -[package.extras] -docs = ["sphinxcontrib-websupport"] -lint = ["flake8 (>=6.0)", "mypy (==1.11.1)", "pyright (==1.1.384)", "pytest (>=6.0)", "ruff (==0.6.9)", "sphinx-lint (>=0.9)", "tomli (>=2)", "types-Pillow (==10.2.0.20240822)", "types-Pygments (==2.18.0.20240506)", "types-colorama (==0.4.15.20240311)", "types-defusedxml (==0.7.0.20240218)", "types-docutils (==0.21.0.20241005)", "types-requests (==2.32.0.20240914)", "types-urllib3 (==1.26.25.14)"] -test = ["cython (>=3.0)", "defusedxml (>=0.7.1)", "pytest (>=8.0)", "setuptools (>=70.0)", "typing_extensions (>=4.9)"] - [[package]] name = "sphinx" version = "9.0.4" @@ -4297,33 +3910,6 @@ sphinx = ">=1.8" code-style = ["pre-commit (==2.12.1)"] rtd = ["ipython", "myst-nb", "sphinx", "sphinx-book-theme", "sphinx-examples"] -[[package]] -name = "sphinx-design" -version = "0.6.1" -description = "A sphinx extension for designing beautiful, view size responsive web components." -optional = false -python-versions = ">=3.9" -groups = ["docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "sphinx_design-0.6.1-py3-none-any.whl", hash = "sha256:b11f37db1a802a183d61b159d9a202314d4d2fe29c163437001324fe2f19549c"}, - {file = "sphinx_design-0.6.1.tar.gz", hash = "sha256:b44eea3719386d04d765c1a8257caca2b3e6f8421d7b3a5e742c0fd45f84e632"}, -] - -[package.dependencies] -sphinx = ">=6,<9" - -[package.extras] -code-style = ["pre-commit (>=3,<4)"] -rtd = ["myst-parser (>=2,<4)"] -testing = ["defusedxml", "myst-parser (>=2,<4)", "pytest (>=8.3,<9.0)", "pytest-cov", "pytest-regressions"] -testing-no-myst = ["defusedxml", "pytest (>=8.3,<9.0)", "pytest-cov", "pytest-regressions"] -theme-furo = ["furo (>=2024.7.18,<2024.8.0)"] -theme-im = ["sphinx-immaterial (>=0.12.2,<0.13.0)"] -theme-pydata = ["pydata-sphinx-theme (>=0.15.2,<0.16.0)"] -theme-rtd = ["sphinx-rtd-theme (>=2.0,<3.0)"] -theme-sbt = ["sphinx-book-theme (>=1.1,<2.0)"] - [[package]] name = "sphinx-design" version = "0.7.0" @@ -4331,7 +3917,6 @@ description = "A sphinx extension for designing beautiful, view size responsive optional = false python-versions = ">=3.11" groups = ["docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "sphinx_design-0.7.0-py3-none-any.whl", hash = "sha256:f82bf179951d58f55dca78ab3706aeafa496b741a91b1911d371441127d64282"}, {file = "sphinx_design-0.7.0.tar.gz", hash = "sha256:d2a3f5b19c24b916adb52f97c5f00efab4009ca337812001109084a740ec9b7a"}, @@ -4582,7 +4167,7 @@ version = "2.4.1" description = "A lil' TOML parser" optional = false python-versions = ">=3.8" -groups = ["dev", "docs"] +groups = ["dev"] files = [ {file = "tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30"}, {file = "tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a"}, @@ -4632,7 +4217,6 @@ files = [ {file = "tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe"}, {file = "tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f"}, ] -markers = {docs = "python_version == \"3.10\""} [[package]] name = "tomli-w" @@ -4960,7 +4544,6 @@ distlib = ">=0.3.7,<1" filelock = {version = ">=3.24.2,<4", markers = "python_version >= \"3.10\""} platformdirs = ">=3.9.1,<5" python-discovery = ">=1.4.2" -typing-extensions = {version = ">=4.13.2", markers = "python_version < \"3.11\""} [[package]] name = "wcwidth" @@ -4981,7 +4564,7 @@ description = "Backport of pathlib-compatible object wrapper for zip files" optional = false python-versions = ">=3.10" groups = ["dev"] -markers = "python_version < \"3.12\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\") or python_version < \"3.12\" and platform_machine != \"ppc64le\" and platform_machine != \"s390x\"" +markers = "python_version == \"3.11\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\" or platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "zipp-4.1.0-py3-none-any.whl", hash = "sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f"}, {file = "zipp-4.1.0.tar.gz", hash = "sha256:4cb57381f544315db7688e976e922a2b18cdb513d21cc194eb42232ba2a3e602"}, @@ -5003,5 +4586,5 @@ polars = ["polars"] [metadata] lock-version = "2.1" -python-versions = ">=3.10,<3.14" -content-hash = "72350f56d6631ce5895d0ccc60dc374cd09526ccb2068569acc2c4204489589f" +python-versions = ">=3.11,<3.14" +content-hash = "66f68d8b87c38e61d51fa9863dd71043b7b38764338b8c94d3f78fc4007ce217" diff --git a/pretab/extension.py b/pretab/extension.py index 7129eed..4e60bcd 100644 --- a/pretab/extension.py +++ b/pretab/extension.py @@ -251,10 +251,7 @@ def load_entry_point_representations(group=ENTRY_POINT_GROUP, *, override=False) """ from importlib.metadata import entry_points - try: - eps = entry_points(group=group) - except TypeError: # pragma: no cover - Python < 3.10 selection fallback - eps = entry_points().get(group, []) + eps = entry_points(group=group) loaded = [] for ep in eps: diff --git a/pyproject.toml b/pyproject.toml index 37192d1..a980a19 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ authors = [ ] readme = "README.md" license = "MIT" -requires-python = ">=3.10,<3.14" +requires-python = ">=3.11,<3.14" dynamic = ["dependencies"] [project.optional-dependencies] @@ -95,7 +95,7 @@ exclude = [ "examples", ] -pythonVersion = "3.10" +pythonVersion = "3.11" typeCheckingMode = "basic" venvPath = "." venv = ".venv" @@ -111,7 +111,7 @@ reportUnsupportedDunderAll = false # Configure code linting [tool.ruff] line-length = 120 -target-version = "py310" +target-version = "py311" exclude = ["*.ipynb"] [tool.ruff.lint] From 4b85f648c78393edf05ca28589b7c80d5b2b3361 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 18:21:54 +0100 Subject: [PATCH 02/86] fix(preprocessor): guard frozen output changes --- docs/core_concepts/reproducibility.md | 19 ++++- pretab/preprocessor.py | 28 +++++++- tests/integration/test_frozen_lifecycle.py | 83 +++++++++++++++++++++- 3 files changed, 124 insertions(+), 6 deletions(-) diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index 63755dd..da18f98 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -112,9 +112,22 @@ object and leaves the original untouched, and `mark_stale(reason)` records why a should no longer be used. ```{warning} -`fit`, `fit_transform`, and `set_params` on a frozen preprocessor raise `FrozenRepresentationError`. This is deliberate: -a deployed representation should not silently change shape. Use `refit` to produce a new -object instead of mutating the old one. +Attempts to refit a frozen preprocessor, change its parameters, or change its +`set_output` format raise `FrozenRepresentationError`. Use `clone_unfitted()` +for a mutable copy or `refit()` to produce a new fitted object. +``` + +`set_output(transform=None)` leaves the configuration unchanged. Repeating an +explicitly selected format, such as `"pandas"`, is also allowed after freezing. +Selecting a format for the first time is a change, even if it matches the +current global default. + +```{note} +Freezing protects instance settings, not sklearn's global configuration. If no +instance format is set, `sklearn.set_config(transform_output="pandas")` can +still change the returned container without changing the fingerprint. Call +`set_output(transform="default")`, or select another supported format, before +`freeze()` to make the output container independent of global settings. ``` ## Where to go next diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index aaba9df..3540d8d 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -1497,11 +1497,20 @@ def is_frozen(self) -> bool: return bool(getattr(self, "_frozen", False)) def freeze(self) -> "Preprocessor": - """Freeze the fitted preprocessor, blocking ``fit`` and ``set_params`` mutation. + """Freeze the fitted preprocessor against mutation. + + Blocks ``fit``, ``set_params``, and changes through ``set_output``. + ``set_output(transform=None)`` and repeating an explicitly configured + output format remain no-ops. Returns ``self`` for chaining. A frozen preprocessor is intended as an immutable deployment artifact; use :meth:`clone_unfitted` or :meth:`refit` to obtain a fresh, mutable estimator. + + Global sklearn output configuration remains external to the frozen state: + it can change the returned container without changing the fingerprint. + Call ``set_output(transform="default")`` (or another supported format) + before freezing to pin the container independently of global settings. """ check_is_fitted(self) self._frozen = True @@ -1543,3 +1552,20 @@ def set_params(self, **params): "Use clone_unfitted() for a mutable copy, or refit() to fit fresh data." ) return super().set_params(**params) + + def set_output(self, *, transform=None): + """Set sklearn output wrapping, refusing changes on a frozen preprocessor. + + ``transform`` accepts ``"default"``, ``"pandas"``, ``"polars"``, or + ``None`` with sklearn's usual semantics. ``None`` leaves the setting + unchanged; repeating an explicit instance setting is also a no-op. + """ + if transform is not None and self.is_frozen(): + configured = getattr(self, "_sklearn_output_config", {}).get("transform") + if transform != configured: + raise FrozenRepresentationError( + f"Cannot set_output(transform={transform!r}) on a frozen {type(self).__name__}. " + "Use clone_unfitted() for a mutable copy, or refit() to fit fresh data." + ) + transform = None + return super().set_output(transform=transform) diff --git a/tests/integration/test_frozen_lifecycle.py b/tests/integration/test_frozen_lifecycle.py index 9c491c7..308f2af 100644 --- a/tests/integration/test_frozen_lifecycle.py +++ b/tests/integration/test_frozen_lifecycle.py @@ -1,13 +1,16 @@ """Tests for the immutable lifecycle: freeze / stale / clone / refit (P9.3). Covers the ``lifecycle_state_`` transitions, ``freeze`` / ``is_frozen``, -``set_params`` rejection on frozen instances, ``clone_unfitted`` and ``refit`` -returning fresh objects, and ``mark_stale``. +``set_params`` / ``set_output`` rejection on frozen instances, output no-ops +and global configuration, ``clone_unfitted`` and ``refit`` returning fresh +objects, and ``mark_stale``. """ import numpy as np import pandas as pd import pytest +from sklearn import config_context +from sklearn.pipeline import Pipeline from pretab import FrozenRepresentationError, Preprocessor @@ -67,6 +70,82 @@ def test_frozen_fit_rejected_without_mutating_state(frame, target, method): np.testing.assert_array_equal(p.transform(frame, return_array=True), original) +@pytest.mark.parametrize( + ("configured", "transform"), + [(None, "default"), (None, "pandas"), (None, "polars"), ("default", "pandas"), ("pandas", "default")], +) +@pytest.mark.parametrize("via_pipeline", [False, True]) +def test_frozen_set_output_rejects_changes(frame, target, configured, transform, via_pipeline): + processor = _make() + processor.set_output(transform=configured) + processor.fit(frame, target).freeze() + fingerprint = processor.fingerprint_ + original = processor.transform(frame, return_array=True) + output_config = getattr(processor, "_sklearn_output_config", None) + caller = Pipeline([("pre", processor)]) if via_pipeline else processor + + with pytest.raises(FrozenRepresentationError, match=r"clone_unfitted\(\).*refit\(\)"): + caller.set_output(transform=transform) + + assert getattr(processor, "_sklearn_output_config", None) == output_config + assert processor.fingerprint_ == fingerprint + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + + +@pytest.mark.parametrize("configured", [None, "default", "pandas"]) +@pytest.mark.parametrize("via_pipeline", [False, True]) +def test_frozen_set_output_noops_preserve_state(frame, target, configured, via_pipeline): + processor = _make() + processor.set_output(transform=configured) + processor.fit(frame, target).freeze() + fingerprint = processor.fingerprint_ + original = processor.transform(frame, return_array=True) + caller = Pipeline([("pre", processor)]) if via_pipeline else processor + + assert caller.set_output() is caller + assert caller.set_output(transform=configured) is caller + + assert processor.fingerprint_ == fingerprint + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + + +@pytest.mark.parametrize("already_fitted", [False, True]) +def test_unfrozen_set_output_keeps_sklearn_behavior(frame, target, already_fitted): + processor = _make() + if already_fitted: + processor.fit(frame, target) + assert processor.set_output(transform="pandas") is processor + if not already_fitted: + processor.fit(frame, target) + + wrapped = processor.transform(frame, return_array=True) + assert isinstance(wrapped, pd.DataFrame) + assert list(wrapped.columns) == list(processor.get_feature_names_out()) + assert processor.set_output(transform="default") is processor + unwrapped = processor.transform(frame, return_array=True) + assert isinstance(unwrapped, np.ndarray) + np.testing.assert_array_equal(unwrapped, wrapped.to_numpy()) + + +@pytest.mark.parametrize("pin_output", [False, True]) +def test_frozen_global_output_config_preserves_state(frame, target, pin_output): + processor = _make() + if pin_output: + processor.set_output(transform="default") + processor.fit(frame, target).freeze() + fingerprint = processor.fingerprint_ + original = processor.transform(frame, return_array=True) + + with config_context(transform_output="pandas"): + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray if pin_output else pd.DataFrame) + np.testing.assert_array_equal(transformed, original) + assert processor.fingerprint_ == fingerprint + + assert isinstance(processor.transform(frame, return_array=True), np.ndarray) + assert processor.fingerprint_ == fingerprint + + def test_clone_unfitted_returns_fresh_unfrozen(frame, target): p = _make().fit(frame, target).freeze() clone = p.clone_unfitted() From e181c2c67a9e9eeca5b5954f00d43a23afc18524 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 18:31:48 +0100 Subject: [PATCH 03/86] fix(periodic): reject invalid periods --- pretab/encoding/numerical/periodic.py | 16 ++++++++++--- tests/encoding/numerical/test_periodic.py | 28 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/pretab/encoding/numerical/periodic.py b/pretab/encoding/numerical/periodic.py index 75aaf31..5cf6bd4 100644 --- a/pretab/encoding/numerical/periodic.py +++ b/pretab/encoding/numerical/periodic.py @@ -1,3 +1,5 @@ +from numbers import Real + import numpy as np from sklearn.utils.validation import check_is_fitted @@ -15,8 +17,9 @@ class PeriodicEncodingTransformer(BasePreTabTransformer): Parameters ---------- - period : int - The full cycle length (e.g., 24 for hours, 7 for weekdays). + period : int or float, > 0 + The finite, positive full cycle length (e.g., 24 for hours, 7 for + weekdays). Boolean values are not accepted. harmonics : int, default=1 The number of sine/cosine harmonic pairs to emit. Harmonic ``h`` uses the angle :math:`2\pi h x / p`, so ``harmonics`` pairs contribute @@ -69,7 +72,7 @@ class PeriodicEncodingTransformer(BasePreTabTransformer): _representation_family = "periodic" _representation_component_kind = "frequency" - def __init__(self, period: int, harmonics: int = 1, include_original: bool = False): + def __init__(self, period: int | float, harmonics: int = 1, include_original: bool = False): self.period = period self.harmonics = harmonics self.include_original = include_original @@ -79,6 +82,13 @@ def _representation_periodic(self): return True, float(self.period) def fit(self, X, y=None): + if ( + isinstance(self.period, (bool, np.bool_)) + or not isinstance(self.period, Real) + or not np.isfinite(self.period) + or self.period <= 0 + ): + raise InvalidParamError(f"period must be a finite, positive real number; got {self.period!r}.") X = self._validate(X, reset=True) if not isinstance(self.harmonics, (int, np.integer)) or self.harmonics < 1: raise InvalidParamError(f"harmonics must be a positive integer; got {self.harmonics!r}.") diff --git a/tests/encoding/numerical/test_periodic.py b/tests/encoding/numerical/test_periodic.py index e0a7270..c626e70 100644 --- a/tests/encoding/numerical/test_periodic.py +++ b/tests/encoding/numerical/test_periodic.py @@ -33,6 +33,34 @@ def test_cyclic_rejects_out_of_range_input(): transformer.fit(np.array([[-1]])) +@pytest.mark.parametrize( + "period", + [0, -1, "24", None, np.nan, np.inf, -np.inf, True, False, np.bool_(True), 24 + 0j, [24], np.array([24])], +) +def test_cyclic_rejects_invalid_period_before_fitting(period): + transformer = PeriodicEncodingTransformer(period=period) + with pytest.raises(InvalidParamError, match=r"period.*finite.*positive") as error: + transformer.fit(np.array([[0.0]])) + + assert repr(period) in str(error.value) + assert not hasattr(transformer, "n_features_in_") + + +@pytest.mark.parametrize("period", [24, 24.0, 7.5, np.int64(7), np.float32(7.5), np.float64(24)]) +def test_cyclic_accepts_positive_finite_period(period): + values = np.array([[0.0], [period / 4], [period / 2], [period]]) + transformer = PeriodicEncodingTransformer(period=period) + transformed = transformer.fit_transform(values) + angles = 2 * np.pi * values[:, 0] / period + + assert transformer.period is period + assert transformed.shape == (4, 2) + assert np.isfinite(transformed).all() + np.testing.assert_allclose(transformed[:, 0], np.sin(angles), atol=1e-12) + np.testing.assert_allclose(transformed[:, 1], np.cos(angles), atol=1e-12) + assert transformer.get_representation_spec().period == float(period) + + def test_cyclic_requires_period(): with pytest.raises(TypeError): PeriodicEncodingTransformer() # type: ignore[call-arg] From 56af47293e58b50421c06e71b491a877f6640579 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 20:04:54 +0100 Subject: [PATCH 04/86] fix(serialization): resolve sklearn state typing errors --- docs/core_concepts/reproducibility.md | 11 +++ pretab/compose/serialize.py | 27 ++++++++ pretab/preprocessor.py | 11 ++- tests/integration/test_serialization.py | 90 ++++++++++++++++++++++++- 4 files changed, 137 insertions(+), 2 deletions(-) diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index da18f98..e92f870 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -59,6 +59,17 @@ serializer; unsupported state raises `PretabSerializationError` when the spec is spec is serialized before `to_spec(path)` opens the file, so a failed save leaves an existing spec at that path untouched. +```{note} +Restoring a PreTab 1.0.0 `Preprocessor` from a spec or trusted pickle repairs +the stale feature count in pass-through and float-cast helpers directly after +sparse one-hot encoders. With unchanged dependencies, these objects retain their +transformed values, names, and feature information without refitting, and can +again export specs and fingerprints. Standalone helper validation is unchanged. +Fingerprints can differ from 1.0.0 because the fitted metadata and JSON encoding +have been corrected. This targeted repair is not a general guarantee of +cross-version compatibility. Only unpickle artifacts from trusted sources. +``` + ## Fingerprint `fingerprint_` is a SHA-256 hash over a canonical view of the fitted representation: the diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 0c7a424..6705ac8 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -23,10 +23,13 @@ import importlib import math from collections import UserList +from itertools import pairwise from typing import Any, cast import numpy as np from sklearn.base import BaseEstimator +from sklearn.pipeline import FeatureUnion, Pipeline +from sklearn.preprocessing import OneHotEncoder from sklearn.utils.validation import check_is_fitted from .._version import __version__ as _PRETAB_VERSION @@ -35,6 +38,7 @@ from ..core.representation import FeatureLineage, RepresentationSpec from ..exceptions import PretabSerializationError from ..placement.base import PlacementResult +from ..preprocessing.floats import NoTransformer, ToFloatTransformer from .inspection import representation_leaf from .registry import TransformerSpec @@ -346,6 +350,28 @@ def check_spec_schema(data: dict) -> None: ) +def _repair_legacy_sparse_feature_counts(preprocessor) -> None: + """Repair the sparse-input helper width stored by PreTab 1.0.0.""" + column_transformer = getattr(preprocessor, "column_transformer_", None) + if column_transformer is None: + return + for _, transformer, _ in column_transformer.transformers_: + if isinstance(transformer, FeatureUnion): + transformer = dict(vars(transformer)["transformer_list"]).get("representation") + if not isinstance(transformer, Pipeline): + continue + for (_, encoder), (_, helper) in pairwise(transformer.steps): + if ( + type(encoder) is OneHotEncoder + and vars(encoder)["sparse_output"] + and hasattr(encoder, "categories_") + and type(helper) in (NoTransformer, ToFloatTransformer) + and getattr(helper, "n_features_in_", None) == 1 + and not hasattr(helper, "feature_names_in_") + ): + helper.n_features_in_ = len(encoder.get_feature_names_out()) + + def preprocessor_from_spec(data: dict): """Reconstruct a fitted preprocessor from a spec produced by :func:`preprocessor_to_spec`.""" check_spec_schema(data) @@ -353,4 +379,5 @@ def preprocessor_from_spec(data: dict): obj = Preprocessor.__new__(Preprocessor) obj.__dict__.update(_decode_mapping(data["state"])) + _repair_legacy_sparse_feature_counts(obj) return obj diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 3540d8d..8defcee 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -41,7 +41,12 @@ to_dataframe_output, validate_embedding_request, ) -from .compose.serialize import SCHEMA_VERSION, preprocessor_from_spec, preprocessor_to_spec +from .compose.serialize import ( + SCHEMA_VERSION, + _repair_legacy_sparse_feature_counts, + preprocessor_from_spec, + preprocessor_to_spec, +) from .core._typing import TransformerLike from .core.logging import configure_logging, get_logger from .core.parameters import UNSET, validate_task @@ -528,6 +533,10 @@ def __init__( self.verbose = verbose self.preset = preset + def __setstate__(self, state): + super().__setstate__(state) + _repair_legacy_sparse_feature_counts(self) + def fit(self, X, y=None, embeddings=None): """ Fit the preprocessor to the input data and target labels. diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index b0a4f17..f1148e9 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -8,6 +8,7 @@ import json import math +import pickle from typing import cast import numpy as np @@ -15,7 +16,8 @@ import pytest from pretab import Preprocessor, PretabSerializationError, RepresentationPolicy -from pretab.compose.serialize import SCHEMA_VERSION +from pretab.compose.serialize import SCHEMA_VERSION, _encode_mapping +from pretab.preprocessing.floats import NoTransformer, ToFloatTransformer @pytest.fixture @@ -70,6 +72,92 @@ def test_round_trip_reproduces_transform_bit_for_bit(frame, target, params, cate assert list(p.get_feature_names_out()) == list(restored.get_feature_names_out()) +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +@pytest.mark.parametrize("helper_type", [NoTransformer, ToFloatTransformer]) +@pytest.mark.parametrize("add_missing_indicator", [False, True]) +@pytest.mark.parametrize("frozen", [False, True]) +def test_restore_legacy_sparse_one_hot_feature_count(restore_format, helper_type, add_missing_indicator, frozen): + frame = pd.DataFrame({"city": ["Rome", None, "Berlin", "Rome"]}) + fitted = Preprocessor( + numerical_method="none", categorical_method="one-hot", add_missing_indicator=add_missing_indicator + ).fit(frame) + fitted.set_output(transform="default") + if frozen: + fitted.freeze() + expected = fitted.transform(frame) + expected_names = fitted.get_feature_names_out() + expected_info = fitted.get_feature_info(verbose=False) + spec = fitted.to_spec() + pipeline = fitted.column_transformer_.named_transformers_["cat_city"] + if add_missing_indicator: + pipeline = dict(pipeline.transformer_list)["representation"] + helper = helper_type() + helper.__dict__.update(vars(pipeline.named_steps["to_float"])) + helper.n_features_in_ = 1 + pipeline.steps[-1] = ("to_float", helper) + + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(fitted)) # noqa: S301 - only locally generated test data + else: + spec["state"] = _encode_mapping(vars(fitted)) + restored = Preprocessor.from_spec(spec) + + np.testing.assert_array_equal(restored.transform(frame), expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), expected_names) + assert restored.get_feature_info(verbose=False) == expected_info + assert restored.is_frozen() == frozen + assert vars(restored)["_sklearn_output_config"] == vars(fitted)["_sklearn_output_config"] + restored_pipeline = restored.column_transformer_.named_transformers_["cat_city"] + if add_missing_indicator: + restored_pipeline = dict(restored_pipeline.transformer_list)["representation"] + restored_helper = restored_pipeline.named_steps["to_float"] + assert type(restored_helper) is helper_type + assert restored_helper.n_features_in_ == 2 + rewritten = Preprocessor.from_spec(restored.to_spec()) + assert rewritten.fingerprint_ == restored.fingerprint_ + np.testing.assert_array_equal(rewritten.transform(frame), expected) + + +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +@pytest.mark.parametrize("helper_type", [NoTransformer, ToFloatTransformer]) +@pytest.mark.parametrize("state_case", ["healthy", "unexpected_width", "dense_input", "named_input"]) +def test_restore_preserves_nonlegacy_helper_metadata(restore_format, helper_type, state_case): + frame = pd.DataFrame({"city": ["Rome", "Berlin", "Rome"]}) + fitted = Preprocessor(numerical_method="none", categorical_method="one-hot").fit(frame) + spec = fitted.to_spec() + pipeline = fitted.column_transformer_.named_transformers_["cat_city"] + helper = helper_type() + helper.__dict__.update(vars(pipeline.named_steps["to_float"])) + expected_count = {"healthy": 2, "unexpected_width": 3, "dense_input": 1, "named_input": 1}[state_case] + helper.n_features_in_ = expected_count + if state_case == "dense_input": + pipeline.named_steps["onehot"].sparse_output = False + if state_case == "named_input": + helper.feature_names_in_ = np.array(["fitted_name"], dtype=object) + pipeline.steps[-1] = ("to_float", helper) + + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(fitted)) # noqa: S301 - only locally generated test data + else: + spec["state"] = _encode_mapping(vars(fitted)) + restored = Preprocessor.from_spec(spec) + + restored_helper = restored.column_transformer_.named_transformers_["cat_city"].named_steps["to_float"] + assert restored_helper.n_features_in_ == expected_count + if state_case == "named_input": + np.testing.assert_array_equal(restored_helper.feature_names_in_, ["fitted_name"]) + if state_case != "healthy": + with pytest.raises(ValueError): + restored.get_feature_names_out() + + +def test_pickle_unfitted_preprocessor_preserves_params(): + original = Preprocessor(numerical_method="none", categorical_method="one-hot") + restored = pickle.loads(pickle.dumps(original)) # noqa: S301 - only locally generated test data + assert restored.get_params() == original.get_params() + assert not hasattr(restored, "column_transformer_") + + def test_spec_is_json_serializable_and_versioned(frame, target): p = Preprocessor(numerical_method="bspline", target_aware=False, placement_strategy="quantile").fit(frame, target) spec = p.to_spec() From 028171a556f25e72606a204684ff80281adafff5 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 22:12:16 +0100 Subject: [PATCH 05/86] fix(inspection): report fitted feature dimensions --- docs/core_concepts/outputs_and_inspection.md | 9 ++ docs/core_concepts/reproducibility.md | 5 +- pretab/compose/inspection.py | 122 ++++-------------- tests/compose/test_inspection.py | 105 ++++++++++++++- .../extension/test_registration_discovery.py | 37 ++++++ 5 files changed, 170 insertions(+), 108 deletions(-) diff --git a/docs/core_concepts/outputs_and_inspection.md b/docs/core_concepts/outputs_and_inspection.md index 68f1989..f644f13 100644 --- a/docs/core_concepts/outputs_and_inspection.md +++ b/docs/core_concepts/outputs_and_inspection.md @@ -364,6 +364,15 @@ For other fitted details (total output width, per-feature output counts, the las [API reference](../api/preprocessor.rst). ``` +```{note} +`dimension` is the actual width of the fitted feature block, including any +missing-indicator columns. Inspection reads the fitted output spans without +evaluating dummy inputs, so it also works for representations restricted to a +particular input domain. `categories` records vocabulary size separately: dropped +or grouped one-hot categories can produce fewer columns than the vocabulary +contains, while additional representation or indicator columns can increase width. +``` + ## Fit-time logging `verbose` controls how much `fit` reports through the shared `"pretab"` logger, useful when diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index e92f870..a6c1c3f 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -63,8 +63,9 @@ spec at that path untouched. Restoring a PreTab 1.0.0 `Preprocessor` from a spec or trusted pickle repairs the stale feature count in pass-through and float-cast helpers directly after sparse one-hot encoders. With unchanged dependencies, these objects retain their -transformed values, names, and feature information without refitting, and can -again export specs and fingerprints. Standalone helper validation is unchanged. +transformed values and names without refitting, and can again export specs and +fingerprints. Feature information reports the fitted layout; previously incorrect +dimension metadata can change. Standalone helper validation is unchanged. Fingerprints can differ from 1.0.0 because the fitted metadata and JSON encoding have been corrected. This targeted repair is not a general guarantee of cross-version compatibility. Only unpickle artifacts from trusted sources. diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index f6ca0cf..e1ab0b0 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -11,17 +11,13 @@ from typing import Any, cast import numpy as np -import pandas as pd from sklearn.base import clone from sklearn.pipeline import FeatureUnion, Pipeline from ..core._typing import TransformerLike -from ..core.logging import get_logger from ..core.representation import FeatureLineage from .registry import TRANSFORMER_REGISTRY -logger = get_logger(__name__) - __all__ = [ "block_name", "block_uses_target", @@ -185,19 +181,6 @@ def _separate_state_branches(transformer): return branches["representation"], branches["missing"] -def _probe_input(step, value): - """Return a one-row probe input for measuring a fitted step's output width. - - A step fitted directly on the ColumnTransformer's DataFrame column records - ``feature_names_in_`` and, like scikit-learn, warns on input without feature - names, so its probe is a DataFrame carrying the fitted names. - """ - names = getattr(step, "feature_names_in_", None) - if names is None: - return np.full((1, 1), value) - return pd.DataFrame(np.full((1, len(names)), value), columns=names) - - def representation_leaf(transformer): """Return the last step of a fitted per-column block's representation. @@ -214,6 +197,8 @@ def representation_leaf(transformer): def build_feature_info(column_transformer, *, embeddings, embedding_dimensions): """Collect per-feature metadata (preprocessing, dimension, categories). + Dimensions come from the fitted output spans without evaluating transformers. + Category counts describe fitted vocabularies, not emitted widths. Returns a ``(numerical_info, categorical_info, embedding_info)`` tuple of dicts keyed by feature name. """ @@ -234,109 +219,46 @@ def build_feature_info(column_transformer, *, embeddings, embedding_dimensions): transformer_pipeline, columns, ) in column_transformer.transformers_: + if transformer_pipeline == "drop" or len(columns) == 0: + continue + span = column_transformer.output_indices_[name] + dimension = span.stop - span.start separate_state = _separate_state_branches(transformer_pipeline) if separate_state is not None: representation_pipeline, _missing_indicator = separate_state steps = [step[0] for step in representation_pipeline.steps] preprocessing_type = f"representation({' -> '.join(steps)}) + missing" - span = column_transformer.output_indices_.get(name) - separate_state_dimension = None if span is None else span.stop - span.start else: representation_pipeline = transformer_pipeline - steps = [step[0] for step in representation_pipeline.steps] + steps = ( + [step[0] for step in representation_pipeline.steps] + if isinstance(representation_pipeline, Pipeline) + else [type(representation_pipeline).__name__] + ) preprocessing_type = " -> ".join(steps) - separate_state_dimension = None for feature_name in columns: - dimension = None categories = None - - if "discretizer" in steps or any( - step in steps - for step in [ - "standardization", - "minmax", - "quantile", - "polynomial", - "splines", - "box-cox", - ] - ): - last_step = representation_pipeline.steps[-1][1] - if hasattr(last_step, "transform"): - dummy_input = _probe_input(last_step, 1e-05) - try: - transformed_feature = last_step.transform(dummy_input) - dimension = transformed_feature.shape[1] - except (ValueError, TypeError, AttributeError, IndexError) as exc: - logger.debug( - "Could not introspect output width of %r: %s", - feature_name, - exc, - ) - dimension = None - if separate_state_dimension is not None: - dimension = separate_state_dimension - numerical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": None, - } - - elif "continuous_ordinal" in steps: + if "continuous_ordinal" in steps: step = representation_pipeline.named_steps["continuous_ordinal"] position = columns.index(feature_name) # An encoder that received no column (a 0-width block) has no mapping. has_mapping = position < len(step.mapping_) categories = len(step.mapping_[position]) if has_mapping else None - dimension = separate_state_dimension if separate_state_dimension is not None else int(has_mapping) - categorical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": categories, - } - elif "onehot" in steps: step = representation_pipeline.named_steps["onehot"] if hasattr(step, "categories_"): categories = sum(len(cat) for cat in step.categories_) - dimension = categories - if separate_state_dimension is not None: - dimension = separate_state_dimension - categorical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": categories, - } - - else: - last_step = representation_pipeline.steps[-1][1] - if hasattr(last_step, "transform"): - dummy_input = _probe_input(last_step, 0.0) - try: - transformed_feature = last_step.transform(dummy_input) - dimension = transformed_feature.shape[1] - except (ValueError, TypeError, AttributeError, IndexError) as exc: - logger.debug( - "Could not introspect output width of %r: %s", - feature_name, - exc, - ) - dimension = None - if separate_state_dimension is not None: - dimension = separate_state_dimension - if name.startswith("cat_"): - categorical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": None, - } - else: - numerical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": None, - } + feature_info = ( + categorical_feature_info + if name.startswith("cat_") or "continuous_ordinal" in steps or "onehot" in steps + else numerical_feature_info + ) + feature_info[feature_name] = { + "preprocessing": preprocessing_type, + "dimension": dimension, + "categories": categories, + } return numerical_feature_info, categorical_feature_info, embedding_feature_info diff --git a/tests/compose/test_inspection.py b/tests/compose/test_inspection.py index a76ee31..2784b93 100644 --- a/tests/compose/test_inspection.py +++ b/tests/compose/test_inspection.py @@ -1,12 +1,14 @@ """Unit tests for :mod:`pretab.compose.inspection`.""" import warnings +from unittest.mock import Mock import numpy as np import pandas as pd import pytest from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline +from sklearn.preprocessing import FunctionTransformer, MaxAbsScaler, PolynomialFeatures from pretab.compose.factory import build_column_transformer, get_categorical_transformer_steps from pretab.compose.inspection import ( @@ -60,13 +62,28 @@ def test_build_feature_info_does_not_infer_kind_from_cat_in_feature_name(make_co assert feature not in categorical +def test_build_feature_info_uses_fitted_width_without_transform(monkeypatch): + frame = pd.DataFrame({"age": [1.0, 2.0, 4.0]}) + pipeline = Pipeline([("positive_only", FunctionTransformer(np.log, feature_names_out="one-to-one"))]) + ct = ColumnTransformer([("num_age", pipeline, ["age"])]).fit(frame) + expected = ct.transform(frame) + expected_names = ct.get_feature_names_out() + + def reject_transform(*_args, **_kwargs): + raise AssertionError("Feature inspection must not invoke transform") + + fitted_transformer = ct.named_transformers_["num_age"].named_steps["positive_only"] + monkeypatch.setattr(fitted_transformer, "transform", reject_transform) + + numerical, _, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + assert numerical["age"]["dimension"] == np.shape(expected)[1] == len(expected_names) == 1 + assert numerical["age"]["dimension"] == get_output_slices(ct)[0][2] + + @pytest.mark.parametrize(("method", "dimension"), [("rbf", 3), ("standardization", 1)]) -def test_build_feature_info_probes_a_step_fitted_on_the_frame_without_warning( - make_config, sample_frame, method, dimension -): - """Without an imputer the representation is fitted on the DataFrame column and - records ``feature_names_in_``; probing it with a bare array warned that X does - not have valid feature names.""" +def test_build_feature_info_reads_width_after_frame_fit_without_warning(make_config, sample_frame, method, dimension): + """Fitting on named columns must not trigger feature-name warnings during inspection.""" config = make_config(numerical_method=method, numerical_imputation=None, output_dim=3) ct = build_column_transformer(config, ["age"], ["city"]).fit(sample_frame) @@ -91,6 +108,82 @@ def test_build_feature_info_reports_a_zero_width_block(): assert categorical["city"]["dimension"] == 0 +@pytest.mark.parametrize("sparse_output", [False, True]) +def test_build_feature_info_reports_zero_width_after_dropping_only_category(sparse_output): + frame = pd.DataFrame({"city": ["Rome", "Rome", "Rome"], "age": [1.0, 2.0, 3.0]}) + steps = get_categorical_transformer_steps("one-hot", sparse_output=sparse_output, drop="first") + ct = ColumnTransformer([("cat_city", Pipeline(steps), ["city"]), ("num_age", "passthrough", ["age"])]).fit(frame) + + _, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + span = ct.output_indices_["cat_city"] + assert categorical["city"]["dimension"] == np.shape(ct.transform(frame)[:, span])[1] == 0 + assert categorical["city"]["categories"] == 1 + assert np.shape(ct.transform(frame))[1] == len(ct.get_feature_names_out()) == 1 + assert get_output_slices(ct) == [("num_age", 0, 1)] + + +@pytest.mark.parametrize("sparse_output", [False, True]) +@pytest.mark.parametrize("suffix", ["to_float", "scaler", "polynomial"]) +@pytest.mark.parametrize( + "encoder_options", + [{}, {"drop": "first"}, {"min_frequency": 2}, {"max_categories": 2}, {"drop": "first", "min_frequency": 2}], +) +def test_build_feature_info_separates_vocabulary_from_emitted_width( + monkeypatch, sparse_output, suffix, encoder_options +): + frame = pd.DataFrame({"city": ["Rome", "Rome", "Berlin", "Oslo", "Paris"]}) + steps = get_categorical_transformer_steps( + "one-hot", add_imputer=False, sparse_output=sparse_output, **encoder_options + ) + if suffix == "scaler": + steps.append(("scaler", MaxAbsScaler())) + elif suffix == "polynomial": + steps.append(("polynomial", PolynomialFeatures(degree=2, include_bias=False))) + ct = ColumnTransformer([("cat_city", Pipeline(steps), ["city"])]).fit(frame) + expected = ct.transform(frame) + expected_names = ct.get_feature_names_out() + reject_transform = Mock(side_effect=AssertionError("Feature inspection must not invoke transform")) + for _, step in ct.named_transformers_["cat_city"].steps: + monkeypatch.setattr(step, "transform", reject_transform) + + numerical, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + assert numerical == {} + assert categorical["city"]["categories"] == 4 + assert categorical["city"]["dimension"] == np.shape(expected)[1] == len(expected_names) + assert categorical["city"]["dimension"] == get_output_slices(ct)[0][2] + reject_transform.assert_not_called() + + +@pytest.mark.parametrize("missing_options", [{"add_missing_indicator": True}, {"missing_policy": "separate_state"}]) +def test_build_feature_info_uses_combined_indicator_span(make_config, missing_options): + frame = pd.DataFrame({"age": [1.0, np.nan, 3.0, 4.0], "city": ["Rome", np.nan, "Oslo", "Rome"]}) + config = make_config(numerical_method="rbf", output_dim=3, categorical_method="one-hot", **missing_options) + ct = build_column_transformer(config, ["age"], ["city"]).fit(frame) + + numerical, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + spans = {name: width for name, _, width in get_output_slices(ct)} + + assert numerical["age"]["dimension"] == spans["num_age"] == 4 + assert categorical["city"]["dimension"] == spans["cat_city"] == 3 + assert categorical["city"]["categories"] == 2 + assert sum(spans.values()) == np.shape(ct.transform(frame))[1] == len(ct.get_feature_names_out()) + + +@pytest.mark.parametrize("passthrough", ["direct", "pipeline"]) +def test_build_feature_info_handles_passthrough_and_dropped_blocks(passthrough): + frame = pd.DataFrame({"age": [1.0, 2.0, 3.0], "ignored": [4.0, 5.0, 6.0]}) + transformer = "passthrough" if passthrough == "direct" else Pipeline([("passthrough", "passthrough")]) + ct = ColumnTransformer([("num_age", transformer, ["age"]), ("num_ignored", "drop", ["ignored"])]).fit(frame) + + numerical, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + assert list(numerical) == ["age"] + assert categorical == {} + assert numerical["age"]["dimension"] == np.shape(ct.transform(frame))[1] == len(ct.get_feature_names_out()) == 1 + + def test_build_transformer_summary_has_header_and_rows(): numerical = {"age": {"preprocessing": "imputer -> standardization", "dimension": 1, "categories": None}} categorical = {"city": {"preprocessing": "imputer -> continuous_ordinal", "dimension": 1, "categories": 3}} diff --git a/tests/extension/test_registration_discovery.py b/tests/extension/test_registration_discovery.py index e8279df..0a3482a 100644 --- a/tests/extension/test_registration_discovery.py +++ b/tests/extension/test_registration_discovery.py @@ -38,6 +38,16 @@ def _output_sizes(self): return [1] * self.n_features_in_ +class _PositiveOnly(_Square): + representation_name = "positive_only_reg" + + def transform(self, X): + values = self._validate(X, reset=False) + if np.any(values <= 0): + raise ValueError("Positive input required") + return np.log(values) + + class _CatStringLength(BaseRepresentation): representation_name = "cat_reg" feature_kind = "categorical" @@ -139,6 +149,33 @@ def test_register_end_to_end_through_preprocessor(): assert out.max() <= 1 + 1e-9 +def test_registered_positive_only_feature_info_matches_fitted_layout(monkeypatch): + register_representation("positive_only_reg", _PositiveOnly) + frame = pd.DataFrame({"value": [1.0, 2.0, 4.0, 8.0]}) + pre = Preprocessor( + numerical_method="positive_only_reg", + numerical_imputation=None, + target_aware=False, + placement_strategy="uniform", + ) + pre.set_params(scaling=None) + pre.fit(frame) + expected = np.asarray(pre.transform(frame, return_array=True)) + expected_names = pre.get_feature_names_out() + + def reject_transform(*_args, **_kwargs): + raise AssertionError("Feature inspection must not invoke transform") + + step = pre.column_transformer_.named_transformers_["num_value"].named_steps["positive_only_reg"] + monkeypatch.setattr(step, "transform", reject_transform) + + numerical, categorical, embeddings = pre.get_feature_info(verbose=False) + + assert categorical == embeddings == {} + assert numerical["value"]["dimension"] == pre.output_dims_["value"] == 1 + assert pre.total_output_dim_ == expected.shape[1] == len(expected_names) == 1 + + def test_register_categorical_updates_categorical_view(): register_representation("cat_reg", _CatStringLength) assert "cat_reg" in registry.CATEGORICAL_METHODS From 8e08b37819125cf54675d9f4dcd4b212dd3860a7 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 22:17:26 +0100 Subject: [PATCH 06/86] test(search): cover named-column refits --- tests/compose/test_search.py | 42 ++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/tests/compose/test_search.py b/tests/compose/test_search.py index 630666f..2d94d76 100644 --- a/tests/compose/test_search.py +++ b/tests/compose/test_search.py @@ -324,6 +324,48 @@ def test_search_records_the_input_features(nonlinear_data): assert not hasattr(search, "feature_names_in_") +@pytest.mark.parametrize("frame_type", ["pandas", "polars"]) +@pytest.mark.parametrize("estimator_kind", ["regressor", "classifier"]) +@pytest.mark.parametrize("new_width", [1, 2]) +def test_refit_replaces_named_input_metadata(nonlinear_data, class_data, frame_type, estimator_kind, new_width): + frame, target = class_data if estimator_kind == "classifier" else nonlinear_data + estimator = LogisticRegression() if estimator_kind == "classifier" else LinearRegression() + renamed = frame.rename(columns={"x": "renamed"}) + if new_width == 2: + renamed = renamed.assign(squared=frame["x"].to_numpy() ** 2) + expected_columns = list(renamed.columns) + if frame_type == "polars": + polars = pytest.importorskip("polars") + frame = polars.DataFrame({column: frame[column].to_numpy() for column in frame.columns}) + renamed = polars.DataFrame({column: renamed[column].to_numpy() for column in renamed.columns}) + + methods = ["minmax", "standardization"] + search = _search(estimator, methods, cv=3).fit(frame, target) + previous_preprocessor = search.best_preprocessor_ + previous_estimator = search.best_estimator_ + np.testing.assert_array_equal(search.feature_names_in_, ["x"]) + + search.fit(renamed, target) + fresh = _search(estimator, methods, cv=3).fit(renamed, target) + + assert search.n_features_in_ == new_width + np.testing.assert_array_equal(search.feature_names_in_, expected_columns) + np.testing.assert_array_equal(search.best_preprocessor_.feature_names_in_, expected_columns) + assert search.best_preprocessor_ is not previous_preprocessor + assert search.best_estimator_ is not previous_estimator + assert search.best_method_ == fresh.best_method_ + assert search.cv_results_ == fresh.cv_results_ + np.testing.assert_array_equal( + search.best_preprocessor_.get_feature_names_out(), fresh.best_preprocessor_.get_feature_names_out() + ) + if estimator_kind == "classifier": + np.testing.assert_array_equal(search.classes_, fresh.classes_) + np.testing.assert_array_equal(search.predict(renamed), fresh.predict(renamed)) + np.testing.assert_allclose(search.predict_proba(renamed), fresh.predict_proba(renamed)) + else: + np.testing.assert_allclose(search.predict(renamed), fresh.predict(renamed)) + + def test_classifier_search_places_against_class_labels(class_data): """A classifier made the search keep task="regression": string labels crashed the target-aware placement and integer labels were treated as a regression target.""" From 8a3a7d6135d6d1838f3bba6e286e3759fa6e412d Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 22:26:46 +0100 Subject: [PATCH 07/86] test(regression): pin fixed audit contracts --- tests/integration/test_edge_case_contract.py | 4 +++ tests/integration/test_missing_policy.py | 32 +++++++++++++++++--- tests/integration/test_output_format.py | 21 ++++++++++--- 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/tests/integration/test_edge_case_contract.py b/tests/integration/test_edge_case_contract.py index 005c397..5732be9 100644 --- a/tests/integration/test_edge_case_contract.py +++ b/tests/integration/test_edge_case_contract.py @@ -390,6 +390,10 @@ def test_empty_numerical_column_keeps_its_block(method, target_aware, placement, pre = Preprocessor(numerical_method=method, target_aware=target_aware, placement_strategy=placement) _fit_empty(pre, X, y) _assert_metadata_matches_output(pre, X, _observed(X, "numerical", rng)) + if method == "minmax": + blocks = pre.transform(X, return_array=False) + assert isinstance(blocks, dict) + np.testing.assert_array_equal(blocks["num_empty"], np.zeros((len(X), 1))) # The methods that cannot be fitted on a constant column (see CONSTANT_RAISES). diff --git a/tests/integration/test_missing_policy.py b/tests/integration/test_missing_policy.py index 2e480ba..da3af25 100644 --- a/tests/integration/test_missing_policy.py +++ b/tests/integration/test_missing_policy.py @@ -8,6 +8,7 @@ from sklearn.base import clone from pretab import Preprocessor +from pretab.compose.inspection import get_output_slices from pretab.exceptions import InvalidParamError, PretabDataError @@ -312,14 +313,37 @@ def test_imputer_indicator_adds_exactly_one_column_per_feature_with_missing(fram @pytest.mark.parametrize("method", ["bspline", "rbf", "pspline", "fourier", "cubicspline"]) -def test_imputer_indicator_lineage_and_feature_info(frame_with_nan, y, method): - pre = Preprocessor(numerical_method=method, output_dim=5, add_missing_indicator=True).fit(frame_with_nan, y) +@pytest.mark.parametrize("output_dim", [5, 7]) +def test_imputer_indicator_lineage_and_feature_info(frame_with_nan, y, method, output_dim): + pre = Preprocessor(numerical_method=method, output_dim=output_dim, add_missing_indicator=True).fit( + frame_with_nan, y + ) + output = np.asarray(pre.transform(frame_with_nan, return_array=True)) + blocks = pre.transform(frame_with_nan, return_array=False) + assert isinstance(blocks, dict) + names = list(pre.get_feature_names_out()) lineage = pre.get_feature_lineage() - assert [record.output_feature for record in lineage] == list(pre.get_feature_names_out()) + assert [record.output_feature for record in lineage] == names missing = [record for record in lineage if record.family == "missing_state"] assert [record.output_feature for record in missing] == ["num_a__missingindicator_a", "num_b__missingindicator_b"] - numerical, _, _ = pre.get_feature_info(verbose=False) + numerical, categorical, embeddings = pre.get_feature_info(verbose=False) + assert categorical == embeddings == {} assert {feature: info["dimension"] for feature, info in numerical.items()} == pre.output_dims_ + slices = get_output_slices(pre.column_transformer_) + assert output.shape[1] == len(names) == len(lineage) == pre.total_output_dim_ + assert sum(width for _, _, width in slices) == output.shape[1] + for block, start, width in slices: + feature = block.removeprefix("num_") + records = [record for record in lineage if record.source_features == (feature,)] + assert width == len(records) == pre.output_dims_[feature] == numerical[feature]["dimension"] + assert [record.output_index for record in records] == list(range(start, start + width)) + assert [record.output_feature for record in records] == names[start : start + width] + np.testing.assert_array_equal(output[:, start : start + width], blocks[block]) + indicator = next(record for record in records if record.family == "missing_state") + np.testing.assert_array_equal(output[:, indicator.output_index], frame_with_nan[feature].isna().astype(float)) + if method == "bspline" and output_dim == 7: + assert width == 8 + assert sum(record.family != "missing_state" for record in records) == 7 def test_imputer_indicator_on_categorical_integer_codes(y): diff --git a/tests/integration/test_output_format.py b/tests/integration/test_output_format.py index cf831ef..9503e21 100644 --- a/tests/integration/test_output_format.py +++ b/tests/integration/test_output_format.py @@ -219,11 +219,24 @@ def test_set_output_pandas_fit_transform(frame, y): assert out.shape[1] == p.total_output_dim_ -def test_set_output_pandas_preserves_input_index(indexed_frame, y): +@pytest.mark.parametrize("index_name", [None, "row_id"]) +@pytest.mark.parametrize("duplicate_index", [False, True]) +def test_set_output_pandas_preserves_input_index(indexed_frame, y, index_name, duplicate_index): """Regression guard for issue #60: the DataFrame keeps X's index, as sklearn's transformers do.""" - p = _bspline().set_output(transform="pandas") - pd.testing.assert_index_equal(p.fit_transform(indexed_frame, y).index, indexed_frame.index) - pd.testing.assert_index_equal(p.transform(indexed_frame).index, indexed_frame.index) + labels = indexed_frame.index.to_numpy() + if duplicate_index: + labels = labels // 2 + indexed_frame = indexed_frame.set_axis(pd.Index(labels, name=index_name)) + expected_index = indexed_frame.index.copy(deep=True) + expected = np.asarray(_bspline().fit_transform(indexed_frame, y)) + fitted = _bspline() + fitted.set_output(transform="pandas") + for output in (fitted.fit_transform(indexed_frame, y), fitted.transform(indexed_frame)): + assert isinstance(output, pd.DataFrame) + pd.testing.assert_index_equal(output.index, expected_index) + assert output.shape == expected.shape + assert list(output.columns) == list(fitted.get_feature_names_out()) + np.testing.assert_array_equal(output.to_numpy(), expected) def test_set_output_pandas_inside_column_transformer(indexed_frame): From c9bd80cd7ec8a29a771c7d16aafed2a9bda352a9 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 10 Nov 2026 22:56:52 +0100 Subject: [PATCH 08/86] docs(reproducibility): clarify upgrade precautions --- docs/core_concepts/reproducibility.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index a6c1c3f..75717ba 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -34,6 +34,7 @@ reads it. Non-finite floats, such as the imputers' `missing_values=np.nan`, are tagged value, `{"__float__": "nan"}` (or `"inf"`, `"-inf"`), instead of a bare `NaN` token. Specs written by PreTab 1.0.0, which contain bare `NaN` tokens, still load. The reverse is not supported: older readers cannot decode the new float tags. +Keep the original spec if you may need to roll back to PreTab 1.0.0. The tagged encoding also changes fingerprints for fitted state containing non-finite values, including the default imputers; this change does not alter transformed values. @@ -71,6 +72,10 @@ have been corrected. This targeted repair is not a general guarantee of cross-version compatibility. Only unpickle artifacts from trusted sources. ``` +When refitting after an upgrade, check output names and widths before reusing a +trained model. If the feature layout changes, refit the preprocessing and retrain +the model together. + ## Fingerprint `fingerprint_` is a SHA-256 hash over a canonical view of the fitted representation: the From 0e118d341179a55a660c13b2f06071065959fe0e Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 11 Nov 2026 20:04:08 +0100 Subject: [PATCH 09/86] test(layout): pin fitted block contracts --- tests/compose/test_block_layout_contract.py | 275 ++++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 tests/compose/test_block_layout_contract.py diff --git a/tests/compose/test_block_layout_contract.py b/tests/compose/test_block_layout_contract.py new file mode 100644 index 0000000..537506e --- /dev/null +++ b/tests/compose/test_block_layout_contract.py @@ -0,0 +1,275 @@ +"""Agreement between fitted block spans and the public output-layout APIs.""" + +from unittest.mock import Mock + +import numpy as np +import pandas as pd +import pytest +from scipy import sparse +from sklearn.pipeline import FeatureUnion, Pipeline +from sklearn.utils.validation import check_is_fitted + +from pretab import BaseRepresentation, Preprocessor, register_representation +from pretab.compose import registry +from pretab.compose.inspection import block_name, build_feature_lineage, get_output_slices +from pretab.embedding.language import LanguageEmbeddingTransformer +from pretab.exceptions import IncompatibleParamsError + + +class _PositiveOnly(BaseRepresentation): + representation_name = "layout_positive_only" + feature_kind = "numerical" + + def fit(self, X, y=None): + self._validate(X, reset=True) + return self + + def transform(self, X): + check_is_fitted(self, "n_features_in_") + values = self._validate(X, reset=False) + if np.any(values <= 0): + raise ValueError("Positive input required") + return np.log(values) + + def _output_sizes(self): + return [1] * self.n_features_in_ + + +@pytest.fixture +def positive_only_method(): + saved_registry = dict(registry.TRANSFORMER_REGISTRY) + saved_numerical = dict(registry.NUMERICAL_METHODS) + saved_categorical = set(registry.CATEGORICAL_METHODS) + try: + register_representation("layout_positive_only", _PositiveOnly) + yield "layout_positive_only" + finally: + registry.TRANSFORMER_REGISTRY.clear() + registry.TRANSFORMER_REGISTRY.update(saved_registry) + registry.NUMERICAL_METHODS.clear() + registry.NUMERICAL_METHODS.update(saved_numerical) + registry.CATEGORICAL_METHODS.clear() + registry.CATEGORICAL_METHODS.update(saved_categorical) + + +@pytest.fixture +def layout_data(): + values = np.linspace(1.0, 9.0, 80) + frame = pd.DataFrame( + { + "value": values, + "other": values**2, + "city": np.resize(["Rome", "Oslo", "Berlin", "Rome"], len(values)), + } + ) + frame.loc[[3, 11], "value"] = np.nan + frame.loc[[5, 17], "city"] = np.nan + return frame, np.sin(values) + + +def _dense(values): + return values.toarray() if sparse.issparse(values) else np.asarray(values) + + +def _assert_block_layout(preprocessor, frame, *, embeddings=None): + transformed = ( + preprocessor.transform(frame, return_array=True) + if embeddings is None + else preprocessor.column_transformer_.transform(frame) + ) + blocks = preprocessor.transform(frame, embeddings=embeddings, return_array=False) + assert isinstance(blocks, dict) + names = preprocessor.get_feature_names_out() + lineage = build_feature_lineage(preprocessor.column_transformer_) + assert lineage == preprocessor.get_feature_lineage() + numerical, categorical, embedding_info = preprocessor.get_feature_info(verbose=False) + assert embedding_info == { + name: {"preprocessing": None, "dimension": width, "categories": None} + for name, width in preprocessor.embedding_dimensions_.items() + } + metadata = {**numerical, **categorical} + dimensions = preprocessor.output_dims_ + slices = get_output_slices(preprocessor.column_transformer_) + sources = { + block_name(name, columns): str(columns[0]) + for name, transformer, columns in preprocessor.column_transformer_.transformers_ + if transformer != "drop" and len(columns) == 1 + } + + assert list(blocks) == [name for name, _, _ in slices] + list(embedding_info) + assert [record.output_index for record in lineage] == list(range(len(names))) + assert [record.output_feature for record in lineage] == list(names) + offset = 0 + for name, start, width in slices: + source = sources[name] + records = [record for record in lineage if record.source_features == (source,)] + stop = start + width + assert start == offset + assert [record.output_index for record in records] == list(range(start, stop)) + assert [record.output_feature for record in records] == list(names[start:stop]) + assert width == len(records) == len(names[start:stop]) + assert width == dimensions[source] == metadata[source]["dimension"] + assert np.shape(blocks[name]) == (len(frame), width) + np.testing.assert_array_equal(_dense(blocks[name]), _dense(transformed[:, start:stop])) + offset = stop + + assert sum(dimensions.values()) == offset == preprocessor.total_output_dim_ + assert offset == np.shape(transformed)[1] == len(names) == len(lineage) + np.testing.assert_array_equal(np.hstack([_dense(blocks[name]) for name, _, _ in slices]), _dense(transformed)) + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize( + "parameters", + [ + pytest.param({"numerical_method": "bspline", "categorical_method": "one-hot"}, id="spline-onehot"), + pytest.param({"numerical_method": "rbf", "categorical_method": "int"}, id="feature-map-ordinal"), + pytest.param( + {"numerical_method": "ple", "target_aware": True, "placement_strategy": "cart"}, + id="target-aware-ple", + ), + pytest.param( + {"numerical_method": "bspline", "categorical_method": "one-hot", "add_missing_indicator": True}, + id="separate-indicators", + ), + pytest.param( + {"numerical_method": "rbf", "missing_policy": "separate_state"}, + id="separate-state-policy", + ), + pytest.param( + { + "numerical_method": "rbf", + "output_dim": 9, + "adaptive": True, + "min_output_dim": 3, + "max_output_dim": 6, + "target_aware": True, + "placement_strategy": "cart", + }, + id="adaptive-widths", + ), + pytest.param({"numerical_method": "none"}, id="passthrough"), + ], +) +def test_fitted_block_layout_agrees_across_views(layout_data, output_format, parameters): + frame, target = layout_data + options = { + "output_dim": 5, + "adaptive": False, + "target_aware": False, + "placement_strategy": "uniform", + "output_format": output_format, + "random_state": 0, + **parameters, + } + preprocessor = Preprocessor(**options) + Pipeline([("preprocessor", preprocessor)]).fit(frame, target) + + _assert_block_layout(preprocessor, frame) + dimensions = preprocessor.output_dims_ + indicators = options.get("add_missing_indicator", False) or options.get("missing_policy") == "separate_state" + for feature in ("value", "other"): + if options["adaptive"]: + assert 3 <= dimensions[feature] <= 6 + assert dimensions[feature] < options["output_dim"] + else: + expected = 1 if options["numerical_method"] == "none" else options["output_dim"] + has_indicator = indicators and ( + options.get("missing_policy") == "separate_state" or frame[feature].isna().any() + ) + assert dimensions[feature] == expected + int(has_indicator) + category_width = frame["city"].nunique() if options.get("categorical_method") == "one-hot" else 1 + assert dimensions["city"] == category_width + int(indicators) + if indicators: + blocks = preprocessor.transform(frame, return_array=False) + assert isinstance(blocks, dict) + for name, _, _ in get_output_slices(preprocessor.column_transformer_): + assert isinstance(preprocessor.column_transformer_.named_transformers_[name], FeatureUnion) + for name, feature in (("num_value", "value"), ("num_other", "other"), ("cat_city", "city")): + if options.get("missing_policy") == "separate_state" or frame[feature].isna().any(): + np.testing.assert_array_equal(_dense(blocks[name])[:, -1], frame[feature].isna().astype(float)) + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_language_embedding_block_layout(layout_data, monkeypatch, output_format): + frame, _ = layout_data + model = Mock() + model.get_sentence_embedding_dimension.return_value = 3 + model.encode.side_effect = lambda values, **kwargs: np.array( + [[len(value), len(set(value)), sum(map(ord, value))] for value in values], dtype=float + ) + monkeypatch.setattr(LanguageEmbeddingTransformer, "_resolve_model", lambda self: model) + preprocessor = Preprocessor( + numerical_method="none", + categorical_method="pretrained", + target_aware=False, + placement_strategy="uniform", + output_format=output_format, + ).fit(frame) + + _assert_block_layout(preprocessor, frame) + + assert preprocessor.output_dims_ == {"value": 1, "other": 1, "city": 3} + embedding_records = [record for record in preprocessor.get_feature_lineage() if record.source_features == ("city",)] + assert len(embedding_records) == 3 + assert all( + record.family == "language_embedding" and record.component == "embedding" for record in embedding_records + ) + model.encode.assert_called() + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_external_embedding_blocks_are_separate_from_column_layout(layout_data, output_format): + frame, _ = layout_data + embeddings = [np.arange(len(frame) * width).reshape(len(frame), width) for width in (2, 4)] + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + output_structure="blocks", + output_format=output_format, + ).fit(frame, embeddings=embeddings) + + _assert_block_layout(preprocessor, frame, embeddings=embeddings) + + blocks = preprocessor.transform(frame, embeddings=embeddings) + assert isinstance(blocks, dict) + _, _, metadata = preprocessor.get_feature_info(verbose=False) + for name, values in zip(("embedding_1", "embedding_2"), embeddings, strict=True): + assert metadata[name]["dimension"] == values.shape[1] + np.testing.assert_array_equal(_dense(blocks[name]), values) + assert preprocessor.total_output_dim_ == 3 + assert sum(np.shape(block)[1] for block in blocks.values()) == preprocessor.total_output_dim_ + 6 + with pytest.raises(IncompatibleParamsError, match="dictionary output"): + preprocessor.transform(frame, embeddings=embeddings, return_array=True) + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_positive_only_plugin_layout_does_not_probe_transform(positive_only_method, monkeypatch, output_format): + frame = pd.DataFrame({"value": [1.0, 2.0, 4.0, 8.0], "other": [2.0, 3.0, 5.0, 7.0]}) + preprocessor = Preprocessor( + numerical_method=positive_only_method, + numerical_imputation=None, + target_aware=False, + placement_strategy="uniform", + output_format=output_format, + ) + preprocessor.set_params(scaling=None) + preprocessor.fit(frame) + _assert_block_layout(preprocessor, frame) + expected_names = preprocessor.get_feature_names_out() + expected_lineage = preprocessor.get_feature_lineage() + reject_transform = Mock(side_effect=AssertionError("Layout inspection must not invoke transform")) + for pipeline in preprocessor.column_transformer_.named_transformers_.values(): + monkeypatch.setattr(pipeline.named_steps[positive_only_method], "transform", reject_transform) + + numerical, categorical, embedding_info = preprocessor.get_feature_info(verbose=False) + + assert categorical == embedding_info == {} + assert preprocessor.output_dims_ == {"value": 1, "other": 1} + assert [numerical[feature]["dimension"] for feature in frame] == [1, 1] + assert preprocessor.total_output_dim_ == len(expected_names) == len(expected_lineage) == 2 + assert get_output_slices(preprocessor.column_transformer_) == [("num_value", 0, 1), ("num_other", 1, 1)] + np.testing.assert_array_equal(preprocessor.get_feature_names_out(), expected_names) + assert preprocessor.get_feature_lineage() == expected_lineage + reject_transform.assert_not_called() From 31caaa09e0c901ec87630778ccfa648b1f114ded Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 11 Nov 2026 20:32:41 +0100 Subject: [PATCH 10/86] test(inspection): pin representation detection contracts --- tests/compose/test_inspection.py | 93 +++++++++++++++++++ .../test_registered_cross_fitting.py | 88 +++++++++++++++++- 2 files changed, 180 insertions(+), 1 deletion(-) diff --git a/tests/compose/test_inspection.py b/tests/compose/test_inspection.py index 2784b93..4d95607 100644 --- a/tests/compose/test_inspection.py +++ b/tests/compose/test_inspection.py @@ -12,11 +12,14 @@ from pretab.compose.factory import build_column_transformer, get_categorical_transformer_steps from pretab.compose.inspection import ( + _locate_block_representation, + block_uses_target, build_feature_info, build_transformer_summary, clean_feature_names, get_output_slices, ) +from pretab.core.representation import RepresentationSpec @pytest.fixture @@ -26,6 +29,96 @@ def fitted_ct(make_config, sample_frame): return ct, sample_frame +@pytest.fixture +def declared_representation(): + spec = RepresentationSpec( + family="declared_joint_basis", + component_kind="basis", + scope="multivariate", + supervision="optional", + uses_target=True, + is_interaction=True, + input_features=("age", "income"), + output_features=("age_income",), + output_dim=1, + degree=None, + include_bias=False, + periodic=False, + period=None, + local_support=False, + location_kind=None, + locations=None, + ) + representation = Mock(spec=["get_representation_spec", "n_features_in_"]) + representation.n_features_in_ = 2 + representation.get_representation_spec.return_value = spec + return representation + + +@pytest.mark.parametrize("step_name", ["representation", "scaler", "onehot"]) +@pytest.mark.parametrize("trailing_helper", [False, True]) +def test_locate_representation_spec_precedes_legacy_steps(declared_representation, step_name, trailing_helper): + steps = [("imputer", FunctionTransformer()), (step_name, declared_representation)] + if trailing_helper: + steps.append(("minmax", MaxAbsScaler())) + pipeline = Pipeline(steps) + + assert _locate_block_representation(pipeline, ["age", "income"]) == ( + 1, + ("declared_joint_basis", "basis", True, True), + ) + assert block_uses_target(pipeline) is True + + +@pytest.mark.parametrize( + ("columns", "fitted_width", "expected_names"), + [ + (["age", "income"], 2, ["age", "income"]), + (("age", "income"), 2, ["age", "income"]), + (["age"], 2, None), + (None, 2, None), + ], +) +def test_locate_representation_only_forwards_matching_input_names( + declared_representation, columns, fitted_width, expected_names +): + declared_representation.n_features_in_ = fitted_width + + assert _locate_block_representation(declared_representation, columns) == ( + 0, + ("declared_joint_basis", "basis", True, True), + ) + declared_representation.get_representation_spec.assert_called_once_with(input_features=expected_names) + + +def test_locate_representation_uses_the_rightmost_declared_spec(declared_representation): + earlier = Mock(spec=["get_representation_spec"]) + earlier.get_representation_spec.side_effect = AssertionError("An earlier declaration must not be inspected") + pipeline = Pipeline([("earlier", earlier), ("representation", declared_representation), ("scaler", MaxAbsScaler())]) + + assert _locate_block_representation(pipeline, ["age", "income"]) == ( + 1, + ("declared_joint_basis", "basis", True, True), + ) + earlier.get_representation_spec.assert_not_called() + + +@pytest.mark.parametrize( + ("step_names", "expected"), + [ + (["scaler"], (0, ("standardization", "raw", False, False))), + (["onehot", "scaler"], (1, ("standardization", "raw", False, False))), + (["scaler", "onehot"], (1, ("onehot", "category", False, False))), + (["imputer", "to_float"], (None, ("passthrough", "raw", False, False))), + ], +) +def test_locate_representation_legacy_fallback_is_the_rightmost_known_step(step_names, expected): + pipeline = Pipeline([(name, FunctionTransformer()) for name in step_names]) + + assert _locate_block_representation(pipeline, ["age"]) == expected + assert block_uses_target(pipeline) is False + + def test_get_output_slices_are_ordered_and_named(fitted_ct): ct, _ = fitted_ct slices = get_output_slices(ct) diff --git a/tests/extension/test_registered_cross_fitting.py b/tests/extension/test_registered_cross_fitting.py index 399aa9a..4772796 100644 --- a/tests/extension/test_registered_cross_fitting.py +++ b/tests/extension/test_registered_cross_fitting.py @@ -8,6 +8,8 @@ """ import warnings +from types import SimpleNamespace +from unittest.mock import Mock import numpy as np import pandas as pd @@ -19,7 +21,7 @@ from sklearn.preprocessing import MinMaxScaler, TargetEncoder from pretab import CrossFittedTransformer, Preprocessor, register_representation -from pretab.compose.inspection import block_uses_target, refit_block_representation +from pretab.compose.inspection import _locate_block_representation, block_uses_target, refit_block_representation from pretab.exceptions import IncompatibleParamsError @@ -75,6 +77,86 @@ def noise_target_data(): return X, rng.normal(size=400) +@pytest.mark.parametrize("feature_kind", ["numerical", "categorical"]) +@pytest.mark.parametrize("supervision", ["unsupervised", "optional", "supervised"]) +@pytest.mark.parametrize("target_aware", [False, True]) +@pytest.mark.parametrize("missing_union", [False, True]) +def test_registered_target_usage_follows_declared_supervision(feature_kind, supervision, target_aware, missing_union): + register_representation("contract_encoder", _MeanEncoder, feature_kind=feature_kind, supervision=supervision) + pipeline = Pipeline( + [ + ("imputer", SimpleImputer()), + ("contract_encoder", _MeanEncoder(target_aware=target_aware)), + ("scaler", MinMaxScaler()), + ] + ) + block = ( + FeatureUnion([("representation", pipeline), ("missing", MissingIndicator(features="all"))]) + if missing_union + else pipeline + ) + expected_target = supervision == "supervised" or (supervision == "optional" and target_aware) + expected = ( + (2, ("standardization", "raw", False, False)) + if supervision == "unsupervised" + else (1, ("contract_encoder", "category" if feature_kind == "categorical" else "basis", expected_target, False)) + ) + + assert _locate_block_representation(pipeline, ["value"]) == expected + assert block_uses_target(block) is expected_target + + +@pytest.mark.parametrize("cls", [_MeanEncoder, _OffByDefaultMeanEncoder]) +def test_registered_class_identity_accepts_subclasses(cls): + register_representation("contract_encoder", _MeanEncoder, feature_kind="categorical", supervision="optional") + encoder = cls() + pipeline = Pipeline([("contract_encoder", encoder)]) + + assert _locate_block_representation(pipeline, ["value"]) == ( + 0, + ("contract_encoder", "category", encoder.target_aware, False), + ) + assert block_uses_target(pipeline) is encoder.target_aware + + +@pytest.mark.parametrize("supervision", ["optional", "supervised"]) +@pytest.mark.parametrize("step_name", ["scaler", "to_float"]) +def test_registered_name_without_matching_class_keeps_the_helper_target_free(monkeypatch, supervision, step_name): + register_representation(step_name, _MeanEncoder, feature_kind="numerical", supervision=supervision, override=True) + helper = MinMaxScaler() + monkeypatch.setattr(helper, "target_aware", True, raising=False) + pipeline = Pipeline([(step_name, helper)]) + expected = ( + (0, ("standardization", "raw", False, False)) + if step_name == "scaler" + else (None, ("passthrough", "raw", False, False)) + ) + + assert _locate_block_representation(pipeline, ["value"]) == expected + assert block_uses_target(pipeline) is False + + +@pytest.mark.parametrize("uses_target", [False, True]) +def test_declared_spec_precedes_matching_registry_and_legacy_name(monkeypatch, uses_target): + register_representation("scaler", _MeanEncoder, feature_kind="categorical", supervision="supervised", override=True) + encoder = _MeanEncoder() + spec = SimpleNamespace( + family="declared_encoder", component_kind="category", uses_target=uses_target, is_interaction=False + ) + get_spec = Mock(return_value=spec) + monkeypatch.setattr(encoder, "get_representation_spec", get_spec, raising=False) + pipeline = Pipeline([("imputer", SimpleImputer()), ("scaler", encoder), ("onehot", MinMaxScaler())]) + + assert _locate_block_representation(pipeline, ["value"]) == ( + 1, + ("declared_encoder", "category", uses_target, False), + ) + get_spec.assert_called_once_with(input_features=["value"]) + assert block_uses_target(pipeline) is uses_target + assert get_spec.call_count == 2 + assert get_spec.call_args.kwargs == {"input_features": None} + + @pytest.mark.parametrize( ("cls", "supervision"), [(TargetEncoder, "supervised"), (_MeanEncoder, "optional")], @@ -227,6 +309,10 @@ def test_refit_representation_shares_only_the_prefix_and_missing_branch( else pipeline ).fit(X, y) assert block_uses_target(fitted) + assert _locate_block_representation(pipeline, ["x"]) == ( + prefix_length, + ("pipeline_mean", "basis", True, False), + ) original = fitted.transform(X).copy() original_input = X.copy(deep=True) train, held_out = X.iloc[40:], X.iloc[:40] From 906956d51b7480aa9fd6186639ee6b961de8c16f Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 11 Nov 2026 20:49:10 +0100 Subject: [PATCH 11/86] test(input): pin shared input routing contracts --- tests/integration/test_column_labels.py | 171 ++++++++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/tests/integration/test_column_labels.py b/tests/integration/test_column_labels.py index 00a1ad7..798efab 100644 --- a/tests/integration/test_column_labels.py +++ b/tests/integration/test_column_labels.py @@ -7,7 +7,9 @@ """ import warnings +from copy import deepcopy from typing import cast +from unittest.mock import Mock import numpy as np import pandas as pd @@ -17,6 +19,7 @@ from sklearn.pipeline import make_pipeline from pretab import Preprocessor +from pretab.compose.inspection import refit_block_representation from pretab.core.supervised import CrossFittedTransformer from pretab.exceptions import PretabDataError @@ -35,6 +38,174 @@ def _blocks(out): return cast("dict[str, np.ndarray]", out) +@pytest.fixture(params=["string", "integer"]) +def input_route_frame(request): + frame = pd.DataFrame( + {1: [True, False, True, False, True, True], 0: [10.0, 20, 30, 40, 50, 60]}, + index=pd.Index([8, 3, 8, 2, 7, 5]), + ) + if request.param == "string": + frame.columns = ["flag", "value"] + return frame + + +@pytest.fixture +def input_route_spies(monkeypatch): + def install(preprocessor): + align = Mock(wraps=preprocessor._align_input) + adapt = Mock(wraps=preprocessor._column_transformer_input) + route = Mock() + route.attach_mock(align, "align") + route.attach_mock(adapt, "adapt") + monkeypatch.setattr(preprocessor, "_align_input", align) + monkeypatch.setattr(preprocessor, "_column_transformer_input", adapt) + return route, align, adapt + + return install + + +@pytest.mark.parametrize("operation", ["fit", "fit_transform"]) +def test_fitting_uses_shared_input_adaptation(input_route_spies, input_route_frame, operation): + frame = input_route_frame + original = frame.copy(deep=True) + preprocessor = _passthrough(categorical_method="int", target_aware=False, placement_strategy="uniform") + route, align, adapt = input_route_spies(preprocessor) + + result = getattr(preprocessor, operation)(frame) + + expected_route = ["adapt"] if operation == "fit" else ["adapt", "align", "adapt"] + assert [call[0] for call in route.mock_calls] == expected_route + assert align.call_count == int(operation == "fit_transform") + assert adapt.call_count == (1 if operation == "fit" else 2) + for call in adapt.call_args_list: + pd.testing.assert_frame_equal(call.args[0], original) + assert vars(preprocessor.column_transformer_)["feature_names_in_"].tolist() == [ + str(label) for label in frame.columns + ] + if operation == "fit": + assert result is preprocessor + else: + blocks = _blocks(result) + np.testing.assert_array_equal(blocks[f"num_{frame.columns[1]}"].ravel(), frame.iloc[:, 1]) + np.testing.assert_array_equal(blocks[f"cat_{frame.columns[0]}"].ravel(), [2.0, 1.0, 2.0, 1.0, 2.0, 2.0]) + pd.testing.assert_frame_equal(frame, original) + + +@pytest.mark.parametrize("input_kind", ["frame", "reordered", "array", "list"]) +def test_transform_aligns_before_shared_input_adaptation(input_route_spies, input_route_frame, input_kind): + frame = input_route_frame.astype(float) if input_kind == "list" else input_route_frame + original = frame.copy(deep=True) + preprocessor = _passthrough(categorical_method="int", target_aware=False, placement_strategy="uniform").fit(frame) + expected = _blocks(preprocessor.transform(frame)) + incoming = { + "frame": frame, + "reordered": frame.iloc[:, ::-1], + "array": frame.to_numpy(), + "list": frame.to_numpy().tolist(), + }[input_kind] + original_incoming = deepcopy(incoming) + route, align, adapt = input_route_spies(preprocessor) + + if input_kind in ("array", "list") and hasattr(preprocessor, "feature_names_in_"): + with pytest.warns(UserWarning, match="does not have valid feature names"): + actual = _blocks(preprocessor.transform(incoming)) + else: + actual = _blocks(preprocessor.transform(incoming)) + + assert [call[0] for call in route.mock_calls] == ["align", "adapt"] + align.assert_called_once() + adapt.assert_called_once() + assert align.call_args.args[0] is incoming + expected_frame = frame.iloc[:, ::-1] if input_kind == "reordered" else frame + if input_kind in ("array", "list"): + expected_frame = frame.set_axis([str(label) for label in frame.columns], axis=1).reset_index(drop=True) + pd.testing.assert_frame_equal(adapt.call_args.args[0], expected_frame) + assert list(actual) == list(expected) + for name in expected: + np.testing.assert_array_equal(actual[name], expected[name]) + if isinstance(incoming, pd.DataFrame): + pd.testing.assert_frame_equal(incoming, original_incoming) + else: + np.testing.assert_array_equal(incoming, original_incoming) + pd.testing.assert_frame_equal(frame, original) + + +@pytest.mark.parametrize("input_kind", ["reordered", "array"]) +def test_fold_refit_aligns_and_adapts_before_routing_to_representations( + input_route_spies, input_route_frame, monkeypatch, input_kind +): + frame = pd.concat([input_route_frame] * 10, ignore_index=True) + original = frame.copy(deep=True) + target = frame.iloc[:, 1].to_numpy() + np.random.default_rng(0).normal(size=len(frame)) + preprocessor = Preprocessor( + numerical_method="ple", + categorical_method="int", + output_dim=4, + adaptive=False, + target_aware=True, + placement_strategy="cart", + scaling="none", + random_state=0, + ).fit(frame, target) + original_output = preprocessor.transform(frame) + train = frame.iloc[12:] + train_target = target[12:] + incoming = train.iloc[:, ::-1] if input_kind == "reordered" else train.to_numpy() + route, align, adapt = input_route_spies(preprocessor) + refit = Mock(wraps=refit_block_representation) + monkeypatch.setattr("pretab.preprocessor.refit_block_representation", refit) + + if input_kind == "array" and hasattr(preprocessor, "feature_names_in_"): + with pytest.warns(UserWarning, match="does not have valid feature names"): + fold = preprocessor._cross_fit_fold(incoming, train_target) + else: + fold = preprocessor._cross_fit_fold(incoming, train_target) + + assert [call[0] for call in route.mock_calls] == ["align", "adapt"] + align.assert_called_once() + adapt.assert_called_once() + assert align.call_args.args[0] is incoming + refit.assert_called_once() + numerical_name = f"num_{frame.columns[1]}" + categorical_name = f"cat_{frame.columns[0]}" + expected_frame = train.iloc[:, [1]].set_axis([str(frame.columns[1])], axis=1) + if input_kind == "array": + expected_frame = expected_frame.reset_index(drop=True) + assert refit.call_args.args[0] is preprocessor.column_transformer_.named_transformers_[numerical_name] + pd.testing.assert_frame_equal(refit.call_args.args[1], expected_frame) + assert refit.call_args.args[2] is train_target + assert fold.column_transformer_ is not preprocessor.column_transformer_ + assert fold.column_transformer_.named_transformers_[numerical_name] is not refit.call_args.args[0] + assert ( + fold.column_transformer_.named_transformers_[categorical_name] + is preprocessor.column_transformer_.named_transformers_[categorical_name] + ) + np.testing.assert_array_equal(preprocessor.transform(frame), original_output) + pd.testing.assert_frame_equal(frame, original) + + +def test_feature_info_uses_fitted_metadata_without_input_routing_or_transform( + input_route_spies, input_route_frame, monkeypatch +): + frame = input_route_frame + preprocessor = _passthrough(categorical_method="int", target_aware=False, placement_strategy="uniform").fit(frame) + expected = preprocessor.get_feature_info(verbose=False) + route, align, adapt = input_route_spies(preprocessor) + reject_transform = Mock(side_effect=AssertionError("Feature metadata must not transform synthetic input")) + monkeypatch.setattr(preprocessor.column_transformer_, "transform", reject_transform) + + actual = preprocessor.get_feature_info(verbose=False) + + assert actual == expected + assert list(actual[0]) == [frame.columns[1]] + assert list(actual[1]) == [frame.columns[0]] + assert actual[2] == {} + assert route.mock_calls == [] + align.assert_not_called() + adapt.assert_not_called() + reject_transform.assert_not_called() + + @pytest.mark.parametrize("label", ["_score", "income__log", "__index_level_0__", "trailing__"]) def test_numerical_labels_with_underscores_fit(label): values = np.random.default_rng(0).normal(size=50) From 5753421a2f87abb378425813f01eb69a79f88d8c Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 11 Nov 2026 21:02:49 +0100 Subject: [PATCH 12/86] test(config): pin normalized configuration routing contracts --- tests/compose/test_config.py | 123 +++++++++++++++++++++++ tests/compose/test_factory.py | 179 +++++++++++++++++++++++++++++++++- 2 files changed, 301 insertions(+), 1 deletion(-) diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index 657be4f..71acd31 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -1,8 +1,131 @@ """Unit tests for :class:`pretab.compose.config.PreprocessorConfig`.""" +from dataclasses import asdict + import pytest +from pretab import Preprocessor from pretab.exceptions import InvalidParamError +from pretab.preprocessor import PRESETS + + +@pytest.mark.parametrize("task", ["regression", "classification"]) +@pytest.mark.parametrize( + ("preset", "overrides"), + [ + (None, {}), + ("standard", {}), + ("expanded", {"categorical_method": "one-hot", "output_dim": 10}), + ("adaptive", {"adaptive": True, "max_output_dim": 15}), + ], +) +def test_resolved_config_matches_inline_preset_contract(task, preset, overrides): + assert set(PRESETS) == {"standard", "expanded", "adaptive"} + preprocessor = Preprocessor(preset=preset, task=task) + requested = preprocessor.get_params(deep=False) + expected = { + "numerical_method": "bspline" if preset is not None and task == "regression" else "ple", + "categorical_method": "int", + "feature_preprocessing": None, + "output_dim": 7, + "degree": 3, + "target_aware": True, + "placement_strategy": "cart", + "task": task, + "adaptive": False, + "min_output_dim": 7, + "max_output_dim": 10, + "random_state": None, + "scaling": "minmax", + "cat_cutoff": 0.03, + "treat_all_integers_as_numerical": False, + "numerical_imputation": "median", + "categorical_imputation": "most_frequent", + "add_missing_indicator": False, + "missing_policy": None, + "policy": None, + "max_output_features": None, + "max_features_per_input": None, + "max_dense_memory": None, + "overflow_policy": "error", + "output_structure": "matrix", + "output_format": "dense", + "dtype": None, + "verbose": 0, + **overrides, + } + + assert preprocessor.get_resolved_config() == expected + assert preprocessor.get_params(deep=False) == requested + assert "preset" not in expected + + +@pytest.mark.parametrize("is_numerical", [False, True]) +@pytest.mark.parametrize("configured_imputation", [False, True]) +@pytest.mark.parametrize( + "missing_policy", [None, "error", "propagate", "impute", "impute_with_indicator", "separate_state"] +) +def test_imputation_plan_routes_policy_and_feature_kind( + make_config, is_numerical, configured_imputation, missing_policy +): + config = make_config( + numerical_imputation="mean" if configured_imputation else None, + categorical_imputation="constant" if configured_imputation else None, + add_missing_indicator=True, + missing_policy=missing_policy, + ) + plans = { + None: (configured_imputation, configured_imputation, not configured_imputation), + "error": (False, False, False), + "propagate": (False, False, False), + "impute": (True, False, False), + "impute_with_indicator": (True, True, False), + "separate_state": (True, False, True), + } + add_imputer, add_indicator, separate_state = plans[missing_policy] + numerical_strategy = "mean" if configured_imputation else "median" + categorical_strategy = "constant" if configured_imputation else "most_frequent" + + assert config.imputation_plan(is_numerical=is_numerical) == { + "add_imputer": add_imputer, + "add_indicator": add_indicator, + "separate_state": separate_state, + "strategy": numerical_strategy if is_numerical else categorical_strategy, + } + + +def test_normalized_config_retains_every_representation_setting(make_config): + parameters = { + "numerical_method": "cubic", + "categorical_method": "ohe", + "feature_preprocessing": {"age": "rbf", "city": "int"}, + "output_dim": 11, + "degree": 2, + "target_aware": True, + "placement_strategy": "cart", + "task": "classification", + "adaptive": True, + "min_output_dim": 3, + "max_output_dim": 8, + "random_state": 17, + "scaling": "standardization", + "cat_cutoff": 6, + "treat_all_integers_as_numerical": True, + "numerical_imputation": "mean", + "categorical_imputation": "constant", + "add_missing_indicator": True, + "missing_policy": "separate_state", + "verbose": 2, + } + + config = make_config(**parameters) + + assert asdict(config) == { + **parameters, + "numerical_method": "cubicspline", + "categorical_method": "one-hot", + } + assert config.feature_preprocessing is not parameters["feature_preprocessing"] def test_none_method_normalizes_to_none(make_config): diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index f271615..04a2c7f 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -1,14 +1,20 @@ """Unit tests for :mod:`pretab.compose.factory`.""" +from dataclasses import fields +from unittest.mock import Mock, call, patch + import numpy as np import pandas as pd import pytest from sklearn.compose import ColumnTransformer -from sklearn.pipeline import Pipeline +from sklearn.pipeline import FeatureUnion, Pipeline +from pretab import Preprocessor +from pretab.compose.config import PreprocessorConfig from pretab.compose.factory import ( _placement_kwargs, build_column_transformer, + create_transformer, get_categorical_transformer_steps, get_numerical_transformer_steps, ) @@ -188,3 +194,174 @@ def test_build_column_transformer_fits_and_transforms(make_config, sample_frame) out = ct.fit_transform(sample_frame, np.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0])) assert isinstance(out, np.ndarray) assert out.shape[0] == len(sample_frame) + + +@pytest.mark.parametrize("adaptive", [False, True]) +@pytest.mark.parametrize("random_state", [None, 17]) +@pytest.mark.parametrize( + "missing_policy", [None, "error", "propagate", "impute", "impute_with_indicator", "separate_state"] +) +def test_create_transformer_forwards_normalized_numerical_options(make_config, adaptive, random_state, missing_policy): + config = make_config( + numerical_method="rbf", + output_dim=11, + degree=2, + target_aware=True, + placement_strategy="cart", + task="classification", + adaptive=adaptive, + min_output_dim=3, + max_output_dim=8, + random_state=random_state, + scaling="standardization", + numerical_imputation=None, + add_missing_indicator=True, + missing_policy=missing_policy, + ) + plan = config.imputation_plan(is_numerical=True) + + with patch( + "pretab.compose.factory.get_numerical_transformer_steps", wraps=get_numerical_transformer_steps + ) as numerical_steps: + block = create_transformer(config.numerical_method, is_numerical=True, config=config) + + numerical_steps.assert_called_once_with( + method="rbf", + task="classification", + target_aware=True, + add_imputer=plan["add_imputer"], + imputer_strategy="median", + output_dim=11, + adaptive=adaptive, + min_output_dim=3 if adaptive else None, + max_output_dim=8 if adaptive else None, + degree=2, + scaling="standardization", + placement_strategy="cart", + **({} if random_state is None else {"random_state": random_state}), + ) + if plan["separate_state"] or plan["add_indicator"]: + assert isinstance(block, FeatureUnion) + representation = dict(block.transformer_list)["representation"] + else: + representation = block + assert isinstance(representation, Pipeline) + assert ("imputer" in representation.named_steps) is plan["add_imputer"] + if plan["add_imputer"]: + assert representation.named_steps["imputer"].strategy == "median" + + +@pytest.mark.parametrize("preset", [None, "standard", "expanded", "adaptive"]) +@pytest.mark.parametrize("missing_policy", [None, "impute_with_indicator", "separate_state"]) +def test_preprocessor_routes_one_normalized_config_through_the_factory(sample_frame, preset, missing_policy): + feature_overrides = {"age": "rbf", "city": "int"} + preprocessor = Preprocessor( + preset=preset, + numerical_method="cubic", + categorical_method="ohe", + feature_preprocessing=feature_overrides, + degree=2, + target_aware=False, + placement_strategy="uniform", + task="classification", + adaptive=False, + min_output_dim=3, + max_output_dim=8, + random_state=17, + scaling="standardization", + cat_cutoff=0.1, + treat_all_integers_as_numerical=True, + numerical_imputation="mean", + categorical_imputation="constant", + add_missing_indicator=True, + missing_policy=missing_policy, + max_output_features=64, + max_features_per_input=16, + max_dense_memory=1_000_000, + output_structure="blocks", + output_format="sparse", + dtype="float32", + ) + requested = preprocessor.get_params(deep=False) + resolved = preprocessor.get_resolved_config() + config_fields = {field.name for field in fields(PreprocessorConfig)} + facade_fields = { + "policy", + "max_output_features", + "max_features_per_input", + "max_dense_memory", + "overflow_policy", + "output_structure", + "output_format", + "dtype", + } + assert set(resolved) == config_fields | facade_fields + assert config_fields.isdisjoint(facade_fields) + + normalized_configs: list[PreprocessorConfig] = [] + from_params = PreprocessorConfig.from_params + + def normalize_config(**parameters): + config = from_params(**parameters) + normalized_configs.append(config) + return config + + with ( + patch.object(PreprocessorConfig, "from_params", side_effect=normalize_config) as normalize, + patch.object( + PreprocessorConfig, "method_for", autospec=True, side_effect=PreprocessorConfig.method_for + ) as method_for, + patch.object( + PreprocessorConfig, "imputation_plan", autospec=True, side_effect=PreprocessorConfig.imputation_plan + ) as imputation_plan, + patch("pretab.compose.factory.create_transformer", wraps=create_transformer) as create, + ): + route = Mock() + for name, spy in ( + ("normalize", normalize), + ("method", method_for), + ("imputation", imputation_plan), + ("create", create), + ): + route.attach_mock(spy, name) + + preprocessor.fit(sample_frame, np.array([0, 1, 0, 1, 0, 1])) + + normalize.assert_called_once_with(**{name: resolved[name] for name in config_fields}) + (config,) = normalized_configs + assert all(item.kwargs["config"] is config for item in create.call_args_list) + assert all(item.args[0] is config for item in method_for.call_args_list + imputation_plan.call_args_list) + assert config.numerical_method == "cubicspline" + assert config.categorical_method == "one-hot" + assert config.feature_preprocessing == feature_overrides + assert config.feature_preprocessing is not feature_overrides + assert method_for.call_args_list == [ + call(config, "age", is_numerical=True), + call(config, "city", is_numerical=False), + ] + assert create.call_args_list == [ + call("rbf", is_numerical=True, config=config), + call("int", is_numerical=False, config=config), + ] + assert imputation_plan.call_args_list == [call(config, is_numerical=True), call(config, is_numerical=False)] + assert [item[0] for item in route.mock_calls] == [ + "normalize", + "method", + "create", + "imputation", + "method", + "create", + "imputation", + ] + + for name, strategy in (("num_age", "mean"), ("cat_city", "constant")): + block = preprocessor.column_transformer_.named_transformers_[name] + assert isinstance(block, FeatureUnion) + representation = dict(block.transformer_list)["representation"] + assert representation.named_steps["imputer"].strategy == strategy + numerical = dict(preprocessor.column_transformer_.named_transformers_["num_age"].transformer_list)["representation"] + assert numerical.named_steps["rbf"].output_dim == resolved["output_dim"] + assert numerical.named_steps["rbf"].random_state == 17 + assert preprocessor.get_params(deep=False) == requested + assert preprocessor.get_resolved_config() == resolved + assert feature_overrides == {"age": "rbf", "city": "int"} From 6d85ae4b44a011cb9339656cb14a660f01be9b8b Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 11 Nov 2026 21:54:15 +0100 Subject: [PATCH 13/86] test(api): pin public API metadata contracts --- tests/integration/test_public_api.py | 158 +++ tests/regression/_snapshots/public_api.json | 1060 +++++++++++++++++++ 2 files changed, 1218 insertions(+) create mode 100644 tests/regression/_snapshots/public_api.json diff --git a/tests/integration/test_public_api.py b/tests/integration/test_public_api.py index 095f723..5680744 100644 --- a/tests/integration/test_public_api.py +++ b/tests/integration/test_public_api.py @@ -2,13 +2,171 @@ Guards the names third parties import and confirms the legacy ``pretab.pipeline`` package (folded into ``pretab.compose`` during the 1.0.0 restructure) is gone. + +Update current API metadata explicitly, then review the JSON diff before committing:: + + PRETAB_UPDATE_API_SNAPSHOT=1 pytest tests/integration/test_public_api.py -k test_public_api_snapshot """ +import difflib import importlib +import inspect +import json +import os +from dataclasses import asdict, replace +from pathlib import Path import pytest import pretab +from pretab import exceptions as pretab_exceptions +from pretab.compose import registry + +API_SNAPSHOT_PATH = Path(__file__).parents[1] / "regression" / "_snapshots" / "public_api.json" + + +def _snapshot_value(value): + if isinstance(value, type): + return f"{value.__module__}.{value.__qualname__}" + if isinstance(value, frozenset): + return sorted(value) + raise TypeError(f"Unsupported API snapshot value: {type(value).__name__}") + + +def _public_api_contract(): + transformers = importlib.import_module("pretab.transformers") + callables = { + f"pretab.{name}": member + for name in pretab.__all__ + if callable(member := getattr(pretab, name)) + and not (isinstance(member, type) and issubclass(member, BaseException)) + } + callables.update({f"pretab.transformers.{name}": getattr(transformers, name) for name in transformers.__all__}) + exception_classes = { + name: member + for name in pretab_exceptions.__all__ + if isinstance(member := getattr(pretab_exceptions, name), type) and issubclass(member, BaseException) + } + capabilities = [name for name, member in vars(registry.TransformerSpec).items() if isinstance(member, property)] + contract = { + "exports": { + "pretab": sorted(pretab.__all__), + "pretab.transformers": sorted(transformers.__all__), + "pretab.exceptions": sorted(pretab_exceptions.__all__), + "pretab.compose.registry": sorted(registry.__all__), + }, + "signatures": {name: str(inspect.signature(member)) for name, member in callables.items()}, + "registry": { + name: {**asdict(spec), "derived_capabilities": {key: getattr(spec, key) for key in capabilities}} + for name, spec in registry.TRANSFORMER_REGISTRY.items() + }, + "aliases": {"numerical": registry.NUMERICAL_ALIASES, "categorical": registry.CATEGORICAL_ALIASES}, + "selectable_methods": { + "numerical": sorted(registry.NUMERICAL_METHODS), + "categorical": sorted(registry.CATEGORICAL_METHODS), + }, + "exceptions": { + name: { + "class": member, + "bases": member.__bases__, + "kind": "warning" if issubclass(member, Warning) else "error", + } + for name, member in exception_classes.items() + }, + } + return json.loads(json.dumps(contract, default=_snapshot_value, allow_nan=False)) + + +def _assert_api_snapshot(actual, path, *, update=False): + rendered = json.dumps(actual, indent=2, sort_keys=True, allow_nan=False) + "\n" + if update: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(rendered, encoding="utf-8") + return + assert path.is_file(), ( + f"Missing API snapshot: {path}. Create it explicitly with PRETAB_UPDATE_API_SNAPSHOT=1 " + "pytest tests/integration/test_public_api.py -k test_public_api_snapshot, then review the diff." + ) + expected = json.loads(path.read_text(encoding="utf-8")) + if expected != actual: + difference = "".join( + difflib.unified_diff( + (json.dumps(expected, indent=2, sort_keys=True, allow_nan=False) + "\n").splitlines(keepends=True), + rendered.splitlines(keepends=True), + fromfile="reviewed public API", + tofile="current public API", + ) + ) + pytest.fail( + f"Public API changed. Review compatibility before updating the snapshot.\n{difference}", pytrace=False + ) + + +def test_public_api_snapshot(): + _assert_api_snapshot( + _public_api_contract(), API_SNAPSHOT_PATH, update=os.environ.get("PRETAB_UPDATE_API_SNAPSHOT") == "1" + ) + + +def test_api_snapshot_update_is_explicit(tmp_path): + path = tmp_path / "snapshots" / "api.json" + with pytest.raises(AssertionError, match="PRETAB_UPDATE_API_SNAPSHOT=1"): + _assert_api_snapshot({"default": 7}, path) + assert not path.exists() + + _assert_api_snapshot({"default": 7}, path, update=True) + _assert_api_snapshot({"default": 7}, path) + with pytest.raises(pytest.fail.Exception, match="Public API changed"): + _assert_api_snapshot({"default": 8}, path) + assert json.loads(path.read_text(encoding="utf-8")) == {"default": 7} + + _assert_api_snapshot({"default": 8}, path, update=True) + assert json.loads(path.read_text(encoding="utf-8")) == {"default": 8} + + +@pytest.mark.parametrize("surface", ["signature", "default", "registry", "alias", "exception", "export"]) +def test_api_snapshot_rejects_surface_drift_without_rewriting(tmp_path, monkeypatch, surface): + path = tmp_path / "api.json" + _assert_api_snapshot(_public_api_contract(), path, update=True) + reviewed = path.read_bytes() + + if surface in {"signature", "default"}: + signature = inspect.signature(pretab.Preprocessor) + parameters = list(signature.parameters.values()) + if surface == "signature": + parameters.append(inspect.Parameter("contract_probe", inspect.Parameter.KEYWORD_ONLY, default=None)) + else: + parameters = [ + parameter.replace(default=99) if parameter.name == "output_dim" else parameter + for parameter in parameters + ] + monkeypatch.setattr( + pretab.Preprocessor, "__signature__", signature.replace(parameters=parameters), raising=False + ) + elif surface == "registry": + original = registry.TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem( + registry.TRANSFORMER_REGISTRY, + "rbf", + replace(original, supports_adaptive_resolution=not original.supports_adaptive_resolution), + ) + elif surface == "alias": + monkeypatch.setitem(registry.NUMERICAL_ALIASES, "std", "minmax") + elif surface == "exception": + changed = type("PretabDataError", (pretab_exceptions.PretabError,), {"__module__": pretab_exceptions.__name__}) + monkeypatch.setattr(pretab_exceptions, "PretabDataError", changed) + else: + monkeypatch.setattr(pretab, "__all__", [*pretab.__all__, "contract_probe"]) + monkeypatch.setattr(pretab, "contract_probe", pretab.Preprocessor, raising=False) + + with pytest.raises(pytest.fail.Exception) as failure: + _assert_api_snapshot(_public_api_contract(), path) + message = str(failure.value) + assert "--- reviewed public API" in message + assert "+++ current public API" in message + assert "@@" in message + assert path.read_bytes() == reviewed + # The stable public transformer facade. Every name here must stay importable from # ``pretab.transformers`` no matter how the internal modules are relocated during the diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json new file mode 100644 index 0000000..a9678e9 --- /dev/null +++ b/tests/regression/_snapshots/public_api.json @@ -0,0 +1,1060 @@ +{ + "aliases": { + "categorical": { + "dummy": "one-hot", + "embedding": "pretrained", + "embeddings": "pretrained", + "identity": "none", + "integer": "int", + "label": "int", + "labelencoder": "int", + "language": "pretrained", + "llm": "pretrained", + "ohe": "one-hot", + "onehotencoder": "one-hot", + "ordinal": "int", + "ordinalencoder": "int", + "passthrough": "none", + "raw": "none" + }, + "numerical": { + "bin": "custombin", + "binning": "custombin", + "cubic": "cubicspline", + "fourierfeatures": "fourier", + "identity": "none", + "minmaxscaler": "minmax", + "natural": "naturalspline", + "naturalcubic": "naturalspline", + "nystrom": "nystroem", + "passthrough": "none", + "piecewiselinear": "ple", + "poly": "polynomial", + "quantiletransformer": "quantile", + "randomfourier": "rff", + "randomfourierfeatures": "rff", + "raw": "none", + "rbfsampler": "rff", + "robustscaler": "robust", + "standard": "standardization", + "standardize": "standardization", + "standardscaler": "standardization", + "std": "standardization", + "tensor": "tensorspline", + "tensorproduct": "tensorspline", + "tensorproductspline": "tensorspline", + "thinplate": "tprs", + "thinplatespline": "tprs", + "zscore": "standardization" + } + }, + "exceptions": { + "ConfigWarning": { + "bases": ["pretab.exceptions.PretabWarning"], + "class": "pretab.exceptions.ConfigWarning", + "kind": "warning" + }, + "DataWarning": { + "bases": ["pretab.exceptions.PretabWarning"], + "class": "pretab.exceptions.DataWarning", + "kind": "warning" + }, + "EmptyDataError": { + "bases": ["pretab.exceptions.PretabDataError"], + "class": "pretab.exceptions.EmptyDataError", + "kind": "error" + }, + "FrozenRepresentationError": { + "bases": ["pretab.exceptions.PretabError"], + "class": "pretab.exceptions.FrozenRepresentationError", + "kind": "error" + }, + "IncompatibleParamsError": { + "bases": ["pretab.exceptions.PretabConfigError"], + "class": "pretab.exceptions.IncompatibleParamsError", + "kind": "error" + }, + "InsufficientSamplesError": { + "bases": ["pretab.exceptions.PretabDataError"], + "class": "pretab.exceptions.InsufficientSamplesError", + "kind": "error" + }, + "InvalidParamError": { + "bases": ["pretab.exceptions.PretabConfigError"], + "class": "pretab.exceptions.InvalidParamError", + "kind": "error" + }, + "LeakageWarning": { + "bases": ["pretab.exceptions.PretabWarning"], + "class": "pretab.exceptions.LeakageWarning", + "kind": "warning" + }, + "OptionalDependencyError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ImportError"], + "class": "pretab.exceptions.OptionalDependencyError", + "kind": "error" + }, + "OutputBudgetError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.OutputBudgetError", + "kind": "error" + }, + "PretabConfigError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.PretabConfigError", + "kind": "error" + }, + "PretabDataError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.PretabDataError", + "kind": "error" + }, + "PretabError": { + "bases": ["builtins.Exception"], + "class": "pretab.exceptions.PretabError", + "kind": "error" + }, + "PretabNotFittedError": { + "bases": [ + "pretab.exceptions.PretabError", + "sklearn.exceptions.NotFittedError" + ], + "class": "pretab.exceptions.PretabNotFittedError", + "kind": "error" + }, + "PretabSerializationError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.PretabSerializationError", + "kind": "error" + }, + "PretabWarning": { + "bases": ["builtins.UserWarning"], + "class": "pretab.exceptions.PretabWarning", + "kind": "warning" + }, + "RepresentationConformanceError": { + "bases": ["pretab.exceptions.PretabError", "builtins.AssertionError"], + "class": "pretab.exceptions.RepresentationConformanceError", + "kind": "error" + } + }, + "exports": { + "pretab": [ + "BaseRepresentation", + "CrossFittedTransformer", + "FeatureLineage", + "FrozenRepresentationError", + "LeakageWarning", + "OutputBudgetError", + "Preprocessor", + "PretabSerializationError", + "PretabWarning", + "RepresentationConformanceError", + "RepresentationPolicy", + "RepresentationSearchCV", + "RepresentationSpec", + "__version__", + "check_representation", + "configure_logging", + "list_representations", + "load_entry_point_representations", + "register_representation", + "set_verbosity" + ], + "pretab.compose.registry": [ + "CATEGORICAL_ALIASES", + "CATEGORICAL_METHODS", + "NUMERICAL_ALIASES", + "NUMERICAL_METHODS", + "TRANSFORMER_REGISTRY", + "TransformerSpec", + "categorical_method_names", + "get_spec", + "numerical_method_names", + "placement_strategies_for", + "register_spec", + "resolve_method", + "supports_adaptive_resolution", + "supports_target_aware" + ], + "pretab.exceptions": [ + "ConfigWarning", + "DataWarning", + "EmptyDataError", + "FrozenRepresentationError", + "IncompatibleParamsError", + "InsufficientSamplesError", + "InvalidParamError", + "LeakageWarning", + "OptionalDependencyError", + "OutputBudgetError", + "PretabConfigError", + "PretabDataError", + "PretabError", + "PretabNotFittedError", + "PretabSerializationError", + "PretabWarning", + "RepresentationConformanceError", + "insufficient_samples_error", + "invalid_param_error" + ], + "pretab.transformers": [ + "BSplineTransformer", + "ContinuousOrdinalTransformer", + "CubicRegressionSplineTransformer", + "FourierFeatureTransformer", + "ISplineTransformer", + "LanguageEmbeddingTransformer", + "MSplineTransformer", + "MissingStateIndicator", + "NaturalCubicSplineTransformer", + "NoTransformer", + "NumericBinningTransformer", + "NystroemFeaturesTransformer", + "OneHotFromOrdinalTransformer", + "PLETransformer", + "PSplineTransformer", + "PeriodicEncodingTransformer", + "RBFExpansionTransformer", + "RandomFourierFeaturesTransformer", + "ReLUExpansionTransformer", + "SigmoidExpansionTransformer", + "TanhExpansionTransformer", + "TensorProductSplineTransformer", + "ThinPlateSplineTransformer", + "ToFloatTransformer" + ] + }, + "registry": { + "box-cox": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "box-cox", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.PowerTransformer" + }, + "bspline": { + "allowed_args": [ + "degree", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "bspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.b_spline.BSplineTransformer" + }, + "cubicspline": { + "allowed_args": [ + "output_dim", + "degree", + "include_bias", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "cubicspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.cubic_regression.CubicRegressionSplineTransformer" + }, + "custombin": { + "allowed_args": ["output_dim", "encode"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "custombin", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.encoding.numerical.binning.NumericBinningTransformer" + }, + "fourier": { + "allowed_args": [ + "n_frequencies", + "frequency_strategy", + "include_original", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "fourier", + "optional_dependency": null, + "periodic": true, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.functional.fourier.FourierFeatureTransformer" + }, + "int": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "name": "int", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.encoding.categorical.ordinal.ContinuousOrdinalTransformer" + }, + "ispline": { + "allowed_args": [ + "degree", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "ispline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.i_spline.ISplineTransformer" + }, + "minmax": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "minmax", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.MinMaxScaler" + }, + "mspline": { + "allowed_args": [ + "degree", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "mspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.m_spline.MSplineTransformer" + }, + "naturalspline": { + "allowed_args": [ + "output_dim", + "include_bias", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "naturalspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.natural_cubic.NaturalCubicSplineTransformer" + }, + "none": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical", "numerical"], + "name": "none", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.preprocessing.floats.NoTransformer" + }, + "nystroem": { + "allowed_args": [ + "n_components", + "kernel", + "gamma", + "degree", + "coef0", + "random_state" + ], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "nystroem", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.kernel_approximation.nystroem.NystroemFeaturesTransformer" + }, + "one-hot": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "name": "one-hot", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": true, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._encoders.OneHotEncoder" + }, + "onehot_from_ordinal": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "name": "onehot_from_ordinal", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.encoding.categorical.one_hot.OneHotFromOrdinalTransformer" + }, + "ple": { + "allowed_args": [ + "output_dim", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": true, + "requires_y": true, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "ple", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "required", + "transformer_cls": "pretab.encoding.numerical.ple.PLETransformer" + }, + "polynomial": { + "allowed_args": ["degree", "interaction_only", "include_bias"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "polynomial", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._polynomial.PolynomialFeatures" + }, + "pretrained": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "name": "pretrained", + "optional_dependency": "embeddings", + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.embedding.language.LanguageEmbeddingTransformer" + }, + "pspline": { + "allowed_args": ["output_dim", "degree", "diff_order"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "pspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.spline.p_spline.PSplineTransformer" + }, + "quantile": { + "allowed_args": ["n_quantiles", "output_distribution", "random_state"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "quantile", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.QuantileTransformer" + }, + "rbf": { + "allowed_args": [ + "output_dim", + "gamma", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "rbf", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.rbf.RBFExpansionTransformer" + }, + "relu": { + "allowed_args": [ + "output_dim", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "relu", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.relu.ReLUExpansionTransformer" + }, + "rff": { + "allowed_args": ["n_components", "gamma", "random_state"], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "rff", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.kernel_approximation.random_fourier.RandomFourierFeaturesTransformer" + }, + "robust": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "robust", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.RobustScaler" + }, + "sigmoid": { + "allowed_args": [ + "output_dim", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "sigmoid", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.sigmoid.SigmoidExpansionTransformer" + }, + "standardization": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "standardization", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.StandardScaler" + }, + "tanh": { + "allowed_args": [ + "output_dim", + "scale", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "name": "tanh", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.tanh.TanhExpansionTransformer" + }, + "tensorspline": { + "allowed_args": ["output_dim", "degree", "diff_order"], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "tensorspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["quantile", "uniform"], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.spline.multivariate.tensor_product.TensorProductSplineTransformer" + }, + "tprs": { + "allowed_args": [ + "n_components", + "landmark_strategy", + "rank_strategy", + "random_state" + ], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "tprs", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.spline.multivariate.thin_plate.ThinPlateSplineTransformer" + }, + "yeo-johnson": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "name": "yeo-johnson", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.PowerTransformer" + } + }, + "selectable_methods": { + "categorical": [ + "int", + "none", + "one-hot", + "onehot_from_ordinal", + "pretrained" + ], + "numerical": [ + "box-cox", + "bspline", + "cubicspline", + "custombin", + "fourier", + "ispline", + "minmax", + "mspline", + "naturalspline", + "none", + "ple", + "polynomial", + "pspline", + "quantile", + "rbf", + "relu", + "robust", + "sigmoid", + "standardization", + "tanh", + "yeo-johnson" + ] + }, + "signatures": { + "pretab.BaseRepresentation": "()", + "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None)", + "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool) -> None", + "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None)", + "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", + "pretab.RepresentationSearchCV": "(estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None)", + "pretab.RepresentationSpec": "(family: str, component_kind: str, scope: str, supervision: str, uses_target: bool, is_interaction: bool, input_features: tuple[str, ...], output_features: tuple[str, ...], output_dim: int, degree: int | None, include_bias: bool, periodic: bool, period: float | None, local_support: bool, location_kind: str | None, locations: tuple[tuple[float, ...], ...] | None, dtype: str = 'float64', cross_fitted: bool = False, n_folds: int | None = None) -> None", + "pretab.check_representation": "(cls, *, X=None, y=None)", + "pretab.configure_logging": "(level: int = 1, handler: 'logging.Handler | None' = None) -> None", + "pretab.list_representations": "(*, feature_kind=None, scope=None, supervised=None, periodic=None, sparse_output=None, adaptive=None, include_optional=True)", + "pretab.load_entry_point_representations": "(group='pretab.representations', *, override=False)", + "pretab.register_representation": "(name, cls, *, feature_kind=None, scope=None, supervision=None, allowed_args=(), placement_strategies=(), supports_adaptive_resolution=False, preprocessor_compatible=True, optional_dependency=None, periodic=False, sparse_output=False, override=False)", + "pretab.set_verbosity": "(level: int = 1) -> None", + "pretab.transformers.BSplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.ContinuousOrdinalTransformer": "()", + "pretab.transformers.CubicRegressionSplineTransformer": "(output_dim=UNSET, degree=3, include_bias=False, target_aware: bool = False, placement_strategy: str = 'uniform', task=None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.FourierFeatureTransformer": "(n_frequencies: int = 5, frequency_strategy: str = 'harmonic', include_original: bool = False, random_state: int | None = None)", + "pretab.transformers.ISplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.LanguageEmbeddingTransformer": "(model_name='paraphrase-MiniLM-L3-v2', model=None)", + "pretab.transformers.MSplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.MissingStateIndicator": "()", + "pretab.transformers.NaturalCubicSplineTransformer": "(output_dim=UNSET, degree=3, include_bias=False, target_aware: bool = False, placement_strategy: str = 'uniform', task=None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.NoTransformer": "()", + "pretab.transformers.NumericBinningTransformer": "(output_dim=UNSET, encode='ordinal', placement_strategy='uniform')", + "pretab.transformers.NystroemFeaturesTransformer": "(n_components: int = 100, kernel: str = 'rbf', gamma: float | None = None, degree: float = 3, coef0: float = 1, random_state: int | None = None)", + "pretab.transformers.OneHotFromOrdinalTransformer": "()", + "pretab.transformers.PLETransformer": "(output_dim=UNSET, placement_strategy: str = 'cart', task: Literal['regression', 'classification'] = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = 51)", + "pretab.transformers.PSplineTransformer": "(output_dim=UNSET, degree=3, diff_order=2, include_bias=False, placement_strategy: str = 'uniform', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.PeriodicEncodingTransformer": "(period: int | float, harmonics: int = 1, include_original: bool = False)", + "pretab.transformers.RBFExpansionTransformer": "(output_dim=UNSET, gamma: float = 1.0, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.RandomFourierFeaturesTransformer": "(n_components: int = 100, gamma: float = 1.0, random_state: int | None = None)", + "pretab.transformers.ReLUExpansionTransformer": "(output_dim=UNSET, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.SigmoidExpansionTransformer": "(output_dim=UNSET, scale: float = 1.0, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.TanhExpansionTransformer": "(output_dim=UNSET, scale: float = 1.0, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.TensorProductSplineTransformer": "(output_dim=UNSET, degree=3, diff_order=2, include_bias=False, placement_strategy: str = 'uniform', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.ThinPlateSplineTransformer": "(n_components=10, landmark_strategy='kmeans', rank_strategy='eigen', include_bias=False, random_state=None)", + "pretab.transformers.ToFloatTransformer": "()" + } +} From 1206af554584e93a7d9bcd1f0aa9ea2088215ead Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 11 Nov 2026 22:04:43 +0100 Subject: [PATCH 14/86] test(serialization): pin current-config compatibility contracts --- tests/integration/test_serialization.py | 91 ++++++++++++++++++++----- 1 file changed, 74 insertions(+), 17 deletions(-) diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index f1148e9..1a6c137 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -1,7 +1,7 @@ -"""Tests for portable serialization: ``to_spec`` / ``from_spec`` (P9.1). +"""Tests for fitted-state serialization through specs and pickle. Covers the versioned JSON envelope, bit-for-bit transform reproduction across -representation families, file round-trips, categorical / missing-value handling, +representation families, fitted metadata, file round-trips, categorical / missing-value handling, policy preservation, and the security allow-list that keeps loading a spec safe (unlike ``pickle``). """ @@ -45,6 +45,8 @@ def target(): {"numerical_method": "tanh", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "relu", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "bspline", "target_aware": False, "placement_strategy": "quantile"}, + {"numerical_method": "mspline", "target_aware": False, "placement_strategy": "quantile"}, + {"numerical_method": "ispline", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "cubicspline", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "naturalspline", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "pspline", "target_aware": False, "placement_strategy": "uniform"}, @@ -61,15 +63,28 @@ def _ids(configs): @pytest.mark.parametrize("params", _CONFIGS, ids=_ids(_CONFIGS)) @pytest.mark.parametrize("categorical_method", ["int", "one-hot"]) -def test_round_trip_reproduces_transform_bit_for_bit(frame, target, params, categorical_method): +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +def test_round_trip_reproduces_transform_bit_for_bit(frame, target, params, categorical_method, restore_format): p = Preprocessor(output_dim=6, categorical_method=categorical_method, **params).fit(frame, target) + fingerprint = p.fingerprint_ + names = p.get_feature_names_out() + dimensions = p.output_dims_ + feature_info = p.get_feature_info(verbose=False) reference = np.asarray(p.transform(frame, return_array=True), dtype=float) - restored = Preprocessor.from_spec(p.to_spec()) + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(p)) # noqa: S301 - only locally generated test data + else: + restored = Preprocessor.from_spec(json.loads(json.dumps(p.to_spec(), allow_nan=False))) reproduced = np.asarray(restored.transform(frame, return_array=True), dtype=float) assert np.array_equal(reference, reproduced, equal_nan=True) - assert list(p.get_feature_names_out()) == list(restored.get_feature_names_out()) + np.testing.assert_array_equal(restored.get_feature_names_out(), names) + assert reference.shape == reproduced.shape == (len(frame), len(names)) + assert sum(dimensions.values()) == reference.shape[1] + assert restored.output_dims_ == dimensions + assert restored.get_feature_info(verbose=False) == feature_info + assert p.fingerprint_ == restored.fingerprint_ == fingerprint @pytest.mark.parametrize("restore_format", ["pickle", "spec"]) @@ -258,22 +273,64 @@ def test_round_trip_preserves_policy(frame, target): assert restored.policy_.constant == "error" -def test_round_trip_with_missing_values(target): +@pytest.mark.parametrize( + "params", + [ + pytest.param(config, id=config["numerical_method"]) + for config in _CONFIGS + if config["numerical_method"] in {"bspline", "ple", "rbf"} + ], +) +@pytest.mark.parametrize("categorical_method", ["int", "one-hot"]) +@pytest.mark.parametrize("missing_policy", ["impute", "impute_with_indicator", "separate_state"]) +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +def test_round_trip_with_missing_values(params, categorical_method, missing_policy, restore_format): frame = pd.DataFrame({"a": [1.0, np.nan, 3.0, 4.0, np.nan, 6.0] * 5, "c": ["x", "y", None, "x", "y", "z"] * 5}) y = np.arange(len(frame), dtype=float) p = Preprocessor( - numerical_method="rbf", - categorical_method="one-hot", - target_aware=False, - placement_strategy="quantile", - numerical_imputation="median", + output_dim=6, + categorical_method=categorical_method, + missing_policy=missing_policy, + random_state=0, + **params, ).fit(frame, y) - restored = Preprocessor.from_spec(p.to_spec()) - assert np.array_equal( - np.asarray(p.transform(frame, return_array=True), dtype=float), - np.asarray(restored.transform(frame, return_array=True), dtype=float), - equal_nan=True, - ) + fingerprint = p.fingerprint_ + names = list(p.get_feature_names_out()) + dimensions = p.output_dims_ + feature_info = p.get_feature_info(verbose=False) + reference = np.asarray(p.transform(frame, return_array=True), dtype=float) + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(p)) # noqa: S301 - only locally generated test data + else: + restored = Preprocessor.from_spec(json.loads(json.dumps(p.to_spec(), allow_nan=False))) + + np.testing.assert_array_equal(restored.transform(frame, return_array=True), reference) + assert reference.shape == (len(frame), len(names)) + assert np.isfinite(reference).all() + assert sum(dimensions.values()) == reference.shape[1] + assert list(restored.get_feature_names_out()) == names + assert restored.output_dims_ == dimensions + assert restored.get_feature_info(verbose=False) == feature_info + assert feature_info[0]["a"]["dimension"] == dimensions["a"] + assert feature_info[1]["c"]["dimension"] == dimensions["c"] + assert feature_info[2] == {} + + for candidate in (p, restored): + for column, prefix in (("a", "num"), ("c", "cat")): + if missing_policy != "impute": + suffix = ( + f"missingindicator_{column}" + if missing_policy == "impute_with_indicator" + else f"missing__{column}__missing" + ) + indicator_name = f"{prefix}_{column}__{suffix}" + output = np.asarray(candidate.transform(frame, return_array=True), dtype=float) + np.testing.assert_array_equal( + output[:, names.index(indicator_name)], frame[column].isna().astype(float) + ) + with pytest.raises(ValueError, match="columns are missing"): + candidate.transform(frame.drop(columns=[column])) + assert candidate.fingerprint_ == fingerprint def test_round_trip_reproduces_unseen_category_encoding(frame, target): From 4f285a6920541a0285c785e35dd0feec939e3553 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 13 Nov 2026 09:03:02 +0100 Subject: [PATCH 15/86] feat(config): add immutable representation configuration --- docs/api/preprocessor.rst | 13 ++ docs/core_concepts/target_awareness.md | 13 +- pretab/__init__.py | 2 + pretab/compose/__init__.py | 4 + pretab/compose/config.py | 174 +++++++++++++++++- tests/compose/test_representation_config.py | 187 ++++++++++++++++++++ tests/integration/test_public_api.py | 11 ++ tests/regression/_snapshots/public_api.json | 3 + 8 files changed, 402 insertions(+), 5 deletions(-) create mode 100644 tests/compose/test_representation_config.py diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index f7e5c48..934b92c 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -13,6 +13,19 @@ configuration, and produces model-ready output with full lineage. Preprocessor +Representation values +--------------------- + +:class:`~pretab.RepresentationConfig` stores a representation request with +read-only, detached parameters and JSON-compatible dictionary conversion. +Constructing the value does not fit an estimator or resolve method aliases. + +.. autosummary:: + :toctree: _autosummary + :nosignatures: + + RepresentationConfig + Configuration, output, and reproducibility ------------------------------------------ diff --git a/docs/core_concepts/target_awareness.md b/docs/core_concepts/target_awareness.md index 3ac549e..da711ab 100644 --- a/docs/core_concepts/target_awareness.md +++ b/docs/core_concepts/target_awareness.md @@ -83,11 +83,20 @@ the same format, or a pandas/Polars DataFrame. Fold outputs are restored to the order. A pandas output keeps the input index when the wrapped transformer preserves it; otherwise it uses a fresh row index. -Cross-fitting currently requires matrix output. A wrapped `Preprocessor` configured with -`output_structure="blocks"` raises an explicit error; use `output_structure="matrix"` instead. +`CrossFittedTransformer.fit_transform` requires matrix output. A wrapped `Preprocessor` +configured with `output_structure="blocks"` raises `IncompatibleParamsError`; use +`output_structure="matrix"` instead. Each fold must return a 2D output with one row per held-out sample, a fixed width, and, for DataFrames, the same column labels in the same order as the all-data fit. +`output_format="dense"` makes block values dense; it does not turn a block dictionary into +a matrix. DeepTab's preprocessing factory requests dense blocks, so a preprocessor built by +that factory cannot be wrapped unchanged to produce cross-fitted training features. + +Calling `fit(X, y).transform(X)` is not an out-of-fold workaround: it uses the estimator fit +on all training rows, even when ordinary block transformation succeeds. Use `fit_transform` +for out-of-fold training features and `transform` for genuinely new rows. + A wrapped `Preprocessor` is not refit from scratch on each fold: every fold reuses its all-data fit and refits only the target-aware representations and subsequent pipeline steps. Column types, target-free blocks and their category vocabularies, imputers, scalers before the diff --git a/pretab/__init__.py b/pretab/__init__.py index afa6482..5114e7b 100644 --- a/pretab/__init__.py +++ b/pretab/__init__.py @@ -1,4 +1,5 @@ from ._version import __version__ +from .compose import RepresentationConfig from .compose.search import RepresentationSearchCV from .core.logging import configure_logging, set_verbosity from .core.policy import RepresentationPolicy @@ -31,6 +32,7 @@ "Preprocessor", "PretabSerializationError", "PretabWarning", + "RepresentationConfig", "RepresentationConformanceError", "RepresentationPolicy", "RepresentationSearchCV", diff --git a/pretab/compose/__init__.py b/pretab/compose/__init__.py index e00ec52..e19799f 100644 --- a/pretab/compose/__init__.py +++ b/pretab/compose/__init__.py @@ -4,3 +4,7 @@ Includes the ``config``, ``registry``, ``factory``, ``feature_detection``, ``output`` and ``inspection`` modules. """ + +from .config import RepresentationConfig + +__all__ = ["RepresentationConfig"] diff --git a/pretab/compose/config.py b/pretab/compose/config.py index 4408cb2..c495cfe 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -16,9 +16,12 @@ from __future__ import annotations -from dataclasses import dataclass +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass, field, fields +from math import isfinite +from typing import Any -from ..core.parameters import validate_placement, validate_task +from ..core.parameters import UNSET, _Unset, validate_placement, validate_task from ..exceptions import invalid_param_error from .registry import ( CATEGORICAL_ALIASES, @@ -28,13 +31,178 @@ resolve_method, ) -__all__ = ["PreprocessorConfig"] +__all__ = ["PreprocessorConfig", "RepresentationConfig"] # Valid values for the high-level ``missing_policy`` orchestration knob. ``None`` # keeps the explicit imputation parameters authoritative (historical behaviour). MISSING_POLICIES = frozenset({"error", "propagate", "impute", "impute_with_indicator", "separate_state"}) +@dataclass(frozen=True, slots=True, eq=False) +class _FrozenParams(Mapping[str, Any]): + _entries: tuple[tuple[str, Any], ...] + + def __getitem__(self, key: str) -> Any: + for stored_key, value in self._entries: + if stored_key == key: + return value + raise KeyError(key) + + def __iter__(self) -> Iterator[str]: + return (key for key, _ in self._entries) + + def __len__(self) -> int: + return len(self._entries) + + def __repr__(self) -> str: + return repr(dict(self)) + + +def _freeze_config_value(value: Any, path: str, active: set[int]) -> Any: + if value is None or type(value) in (str, bool, int): + return value + if type(value) is float and isfinite(value): + return value + if not isinstance(value, (Mapping, Sequence)) or isinstance(value, (str, bytes, bytearray, memoryview)): + raise invalid_param_error( + "RepresentationConfig", path, value, "must contain only finite JSON-compatible values" + ) + identity = id(value) + if identity in active: + raise invalid_param_error("RepresentationConfig", path, value, "must not contain circular references") + active.add(identity) + try: + if isinstance(value, Mapping): + entries = [] + for key, item in value.items(): + if type(key) is not str: + raise invalid_param_error("RepresentationConfig", path, key, "mapping keys must be strings") + entries.append((key, _freeze_config_value(item, f"{path}[{key!r}]", active))) + return _FrozenParams(tuple(entries)) + return tuple(_freeze_config_value(item, f"{path}[{index}]", active) for index, item in enumerate(value)) + finally: + active.remove(identity) + + +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()} + if isinstance(value, tuple): + return [_config_value_to_json(item) for item in value] + return value + + +@dataclass(frozen=True) +class RepresentationConfig: + """Immutable, JSON-compatible settings for one representation. + + Parameters + ---------- + method : str + Requested method name. Alias resolution and parameter applicability + require a numerical or categorical context and are checked separately. + output_dim : int, optional + Positive requested width, subject to the selected family's constraints. + target_aware : bool, optional + Whether to use the target for placement. + placement_strategy : str, optional + Requested nonempty placement-strategy name. + adaptive : bool, optional + Whether to use adaptive resolution. + min_output_dim, max_output_dim : int or None, optional + Positive adaptive bounds, or ``None`` where the method permits it. + params : mapping, optional + Family-specific options. Nested mappings and sequences are copied into + read-only storage. Only finite JSON-compatible values are accepted. + name : str or None, default=None + Optional metadata label; it does not rename input or output columns. + + Notes + ----- + Omitted common settings retain ``UNSET`` rather than adopting method defaults. + This value is not an estimator; it has no fitted state or ``set_params``. + """ + + method: str + output_dim: int | _Unset = UNSET + target_aware: bool | _Unset = UNSET + placement_strategy: str | _Unset = UNSET + adaptive: bool | _Unset = UNSET + min_output_dim: int | _Unset | None = UNSET + max_output_dim: int | _Unset | None = UNSET + params: Mapping[str, Any] = field(default_factory=dict) + name: str | None = None + + def __post_init__(self) -> None: + if self.method is UNSET: + raise invalid_param_error("RepresentationConfig", "method", self.method, "is required") + for key in ("method", "placement_strategy", "name"): + value = getattr(self, key) + if (key == "placement_strategy" and value is UNSET) or (key == "name" and value is None): + continue + if type(value) is not str or not value.strip(): + raise invalid_param_error("RepresentationConfig", key, value, "must be a nonempty string") + for key in ("output_dim", "min_output_dim", "max_output_dim"): + value = getattr(self, key) + if value is UNSET or (key != "output_dim" and value is None): + continue + if type(value) is not int or value < 1: + raise invalid_param_error("RepresentationConfig", key, value, "must be a positive integer") + for key in ("target_aware", "adaptive"): + value = getattr(self, key) + if value is not UNSET and type(value) is not bool: + raise invalid_param_error("RepresentationConfig", key, value, "must be a boolean") + if not isinstance(self.params, Mapping): + raise invalid_param_error("RepresentationConfig", "params", self.params, "must be a mapping") + reserved = {item.name for item in fields(self)} + for key in self.params: + if key in reserved: + raise invalid_param_error( + "RepresentationConfig", + f"params[{key!r}]", + self.params[key], + "must be supplied as a top-level field", + ) + object.__setattr__(self, "params", _freeze_config_value(self.params, "params", set())) + + def to_dict(self) -> dict[str, Any]: + """Return detached JSON-compatible settings, omitting ``UNSET`` fields.""" + return { + item.name: _config_value_to_json(value) + for item in fields(self) + if (value := getattr(self, item.name)) is not UNSET + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> RepresentationConfig: + """Build a value from a mapping, collecting family options into ``params``. + + An option supplied both at the top level and in ``params`` is an error, + even if the two values agree. Method-specific validation requires the + feature-kind context and is not performed by this constructor. + """ + if not isinstance(data, Mapping): + raise invalid_param_error("RepresentationConfig", "data", data, "must be a mapping") + requested = dict(data) + if any(type(key) is not str for key in requested): + raise invalid_param_error("RepresentationConfig", "data", data, "mapping keys must be strings") + if "method" not in requested: + raise invalid_param_error("RepresentationConfig", "method", UNSET, "is required") + params = requested.pop("params", {}) + if not isinstance(params, Mapping): + raise invalid_param_error("RepresentationConfig", "params", params, "must be a mapping") + params = dict(params) + common = {item.name for item in fields(cls)} + for key in list(requested): + if key not in common: + if key in params: + raise invalid_param_error( + "RepresentationConfig", key, requested[key], "must not also be supplied inside params" + ) + params[key] = requested.pop(key) + return cls(**requested, params=params) + + def _normalize_method(method, canonical, aliases) -> str: """Resolve a global method name to canonical form, mapping ``None`` to ``"none"``.""" if method is None: diff --git a/tests/compose/test_representation_config.py b/tests/compose/test_representation_config.py new file mode 100644 index 0000000..4f4a1a0 --- /dev/null +++ b/tests/compose/test_representation_config.py @@ -0,0 +1,187 @@ +"""Value semantics for immutable, portable representation settings.""" + +import copy +import json +import pickle +from dataclasses import FrozenInstanceError, is_dataclass +from typing import Any, cast + +import pytest +from sklearn.base import clone + +from pretab import Preprocessor +from pretab.compose.config import RepresentationConfig +from pretab.core.parameters import UNSET +from pretab.exceptions import InvalidParamError + + +def test_omitted_fields_remain_unset(): + config = RepresentationConfig(method="rbf") + + assert is_dataclass(config) + for key in ("output_dim", "target_aware", "placement_strategy", "adaptive", "min_output_dim", "max_output_dim"): + assert getattr(config, key) is UNSET + assert config.to_dict() == {"method": "rbf", "params": {}, "name": None} + assert "RepresentationConfig(method='rbf'" in repr(config) + with pytest.raises(FrozenInstanceError): + cast(Any, config).method = "ple" + with pytest.raises(TypeError): + hash(config) + + +def test_nested_values_are_detached_and_read_only(): + original = {"options": {"locations": [1.0, 2.0]}, "labels": ["a", "b"]} + config = RepresentationConfig(method="rbf", params=original) + original["options"]["locations"][0] = 9.0 + original["labels"].append("c") + original["extra"] = True + + assert config.params["options"]["locations"] == (1.0, 2.0) + assert config.params["labels"] == ("a", "b") + assert "extra" not in config.params + with pytest.raises(TypeError): + cast(Any, config.params)["extra"] = True + with pytest.raises(TypeError): + config.params["options"]["extra"] = True + with pytest.raises(TypeError): + config.params["options"]["locations"][0] = 9.0 + + +def test_json_round_trip_and_returned_containers_are_detached(): + config = RepresentationConfig( + method="rbf", + output_dim=3, + adaptive=True, + max_output_dim=None, + params={"options": {"values": [None, False, 2, 0.5, "x"]}}, + name="age", + ) + data = config.to_dict() + assert RepresentationConfig.from_dict(json.loads(json.dumps(data, allow_nan=False))) == config + data["params"]["options"]["values"].append("changed") + assert len(config.to_dict()["params"]["options"]["values"]) == 5 + assert config.to_dict()["max_output_dim"] is None + + +def test_mapping_shorthand_and_order_have_value_equality(): + shorthand = {"method": "RBF", "output_dim": 3, "gamma": 0.5, "params": {"scale": [1, 2]}} + config = RepresentationConfig.from_dict(shorthand) + + assert config == RepresentationConfig(method="RBF", output_dim=3, params={"gamma": 0.5, "scale": (1, 2)}) + assert config != RepresentationConfig(method="rbf", output_dim=3, params={"gamma": 0.5, "scale": [1, 2]}) + assert config.method == "RBF" + assert shorthand == {"method": "RBF", "output_dim": 3, "gamma": 0.5, "params": {"scale": [1, 2]}} + with pytest.raises(KeyError): + config.params["missing"] + + +@pytest.mark.parametrize( + "restore", + [ + copy.copy, + copy.deepcopy, + lambda value: pickle.loads(pickle.dumps(value)), # noqa: S301 + lambda value: clone(value, safe=False), + ], +) +def test_copy_pickle_and_clone_preserve_immutable_values(restore): + config = RepresentationConfig(method="rbf", params={"locations": [{"value": 0.5}]}) + restored = restore(config) + + assert restored == config and restored is not config + assert restored.output_dim is UNSET + with pytest.raises(TypeError): + restored.params["locations"][0]["value"] = 1.0 + + +def test_value_can_be_cloned_as_an_estimator_parameter(): + config = RepresentationConfig(method="rbf", output_dim=3, params={"gamma": 0.5}) + requested = {"age": config} + original = Preprocessor(feature_preprocessing=requested) + copied = cast(Preprocessor, clone(original)) + + assert original.get_params(deep=False)["feature_preprocessing"] is requested + assert copied.feature_preprocessing is not None + assert copied.feature_preprocessing == requested + assert copied.feature_preprocessing is not requested + assert copied.feature_preprocessing["age"] is not config + + +@pytest.mark.parametrize( + "key", + [ + "method", + "output_dim", + "target_aware", + "placement_strategy", + "adaptive", + "min_output_dim", + "max_output_dim", + "params", + "name", + ], +) +def test_common_fields_cannot_be_hidden_in_params(key): + with pytest.raises(InvalidParamError, match="top-level field"): + RepresentationConfig(method="rbf", params={key: 1}) + + +def test_duplicate_family_options_are_rejected(): + with pytest.raises(InvalidParamError, match="also be supplied inside params"): + RepresentationConfig.from_dict({"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}) + + +@pytest.mark.parametrize("key", ["method", "placement_strategy", "name"]) +@pytest.mark.parametrize("value", ["", " ", 3, False, []]) +def test_invalid_text_fields_raise_typed_errors(key, value): + with pytest.raises(InvalidParamError, match=key): + RepresentationConfig(**{"method": "rbf", key: value}) + + +@pytest.mark.parametrize("key", ["output_dim", "min_output_dim", "max_output_dim"]) +@pytest.mark.parametrize("value", [0, -1, True, 2.5, "3"]) +def test_invalid_counts_raise_typed_errors(key, value): + with pytest.raises(InvalidParamError, match=key): + RepresentationConfig(**{"method": "rbf", key: value}) + + +@pytest.mark.parametrize("key", ["target_aware", "adaptive"]) +@pytest.mark.parametrize("value", [0, 1, None, "true"]) +def test_invalid_boolean_fields_raise_typed_errors(key, value): + with pytest.raises(InvalidParamError, match=key): + RepresentationConfig(**{"method": "rbf", key: value}) + + +@pytest.mark.parametrize( + "value", [float("nan"), float("inf"), float("-inf"), b"raw", {1, 2}, object(), lambda: 1, UNSET] +) +def test_opaque_or_nonfinite_nested_values_are_rejected(value): + with pytest.raises(InvalidParamError, match=r"params\['nested'\]\[0\]"): + RepresentationConfig(method="rbf", params={"nested": [value]}) + + +def test_cyclic_containers_are_rejected_without_recursion_error(): + values = [] + values.append(values) + with pytest.raises(InvalidParamError, match="circular references"): + RepresentationConfig(method="rbf", params={"nested": values}) + + +@pytest.mark.parametrize("data", [None, [], {}, {1: "rbf"}, {"method": "rbf", "params": []}]) +def test_invalid_mapping_shape_raises_typed_error(data): + with pytest.raises(InvalidParamError): + RepresentationConfig.from_dict(data) + + +def test_mapping_keys_and_required_values_are_validated(): + for data in [{1: "invalid"}, {"nested": {1: "invalid"}}]: + with pytest.raises(InvalidParamError, match="keys must be strings"): + cast(Any, RepresentationConfig)(method="rbf", params=data) + with pytest.raises(InvalidParamError, match="method"): + cast(Any, RepresentationConfig)(method=UNSET) + with pytest.raises(InvalidParamError, match="output_dim"): + cast(Any, RepresentationConfig)(method="rbf", output_dim=None) + with pytest.raises(InvalidParamError, match="name"): + cast(Any, RepresentationConfig)(method="rbf", name=UNSET) + with pytest.raises(InvalidParamError, match="params"): + cast(Any, RepresentationConfig)(method="rbf", params=None) diff --git a/tests/integration/test_public_api.py b/tests/integration/test_public_api.py index 5680744..cfc4a35 100644 --- a/tests/integration/test_public_api.py +++ b/tests/integration/test_public_api.py @@ -19,6 +19,7 @@ import pytest import pretab +from pretab import compose as pretab_compose from pretab import exceptions as pretab_exceptions from pretab.compose import registry @@ -51,6 +52,7 @@ def _public_api_contract(): contract = { "exports": { "pretab": sorted(pretab.__all__), + "pretab.compose": sorted(pretab_compose.__all__), "pretab.transformers": sorted(transformers.__all__), "pretab.exceptions": sorted(pretab_exceptions.__all__), "pretab.compose.registry": sorted(registry.__all__), @@ -217,6 +219,15 @@ def test_preprocessor_is_constructible(): assert pretab.Preprocessor() is not None +def test_representation_config_public_exports_are_identical(): + from pretab.compose.config import RepresentationConfig + + assert pretab.RepresentationConfig is RepresentationConfig + assert pretab_compose.RepresentationConfig is RepresentationConfig + assert "RepresentationConfig" in pretab.__all__ + assert pretab_compose.__all__ == ["RepresentationConfig"] + + def test_transformers_public_surface_is_resolvable(): transformers = importlib.import_module("pretab.transformers") assert transformers.__all__ diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index a9678e9..e804912 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -149,6 +149,7 @@ "Preprocessor", "PretabSerializationError", "PretabWarning", + "RepresentationConfig", "RepresentationConformanceError", "RepresentationPolicy", "RepresentationSearchCV", @@ -161,6 +162,7 @@ "register_representation", "set_verbosity" ], + "pretab.compose": ["RepresentationConfig"], "pretab.compose.registry": [ "CATEGORICAL_ALIASES", "CATEGORICAL_METHODS", @@ -1023,6 +1025,7 @@ "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None)", "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool) -> None", "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None)", + "pretab.RepresentationConfig": "(method: 'str', output_dim: 'int | _Unset' = UNSET, target_aware: 'bool | _Unset' = UNSET, placement_strategy: 'str | _Unset' = UNSET, adaptive: 'bool | _Unset' = UNSET, min_output_dim: 'int | _Unset | None' = UNSET, max_output_dim: 'int | _Unset | None' = UNSET, params: 'Mapping[str, Any]' = , name: 'str | None' = None) -> None", "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", "pretab.RepresentationSearchCV": "(estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None)", "pretab.RepresentationSpec": "(family: str, component_kind: str, scope: str, supervision: str, uses_target: bool, is_interaction: bool, input_features: tuple[str, ...], output_features: tuple[str, ...], output_dim: int, degree: int | None, include_bias: bool, periodic: bool, period: float | None, local_support: bool, location_kind: str | None, locations: tuple[tuple[float, ...], ...] | None, dtype: str = 'float64', cross_fitted: bool = False, n_folds: int | None = None) -> None", From d665215206ae25b70dc41f14eac773b1913b1887 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 13 Nov 2026 11:08:23 +0100 Subject: [PATCH 16/86] feat(config): normalize representation configuration inputs --- pretab/compose/config.py | 28 +++++- tests/compose/test_representation_config.py | 97 ++++++++++++++++++++- 2 files changed, 123 insertions(+), 2 deletions(-) diff --git a/pretab/compose/config.py b/pretab/compose/config.py index c495cfe..95b46f5 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -17,7 +17,7 @@ from __future__ import annotations from collections.abc import Iterator, Mapping, Sequence -from dataclasses import dataclass, field, fields +from dataclasses import dataclass, field, fields, replace from math import isfinite from typing import Any @@ -203,6 +203,32 @@ def from_dict(cls, data: Mapping[str, Any]) -> RepresentationConfig: return cls(**requested, params=params) +def _normalize_representation_config( + value: str | Mapping[str, Any] | RepresentationConfig, *, is_numerical: bool +) -> RepresentationConfig: + """Normalize one request in its known feature-kind namespace. + + Raw mappings detach through ``from_dict``. Typed values retain their + requested spelling; normalization replaces rather than mutates an alias. + Omitted fields remain ``UNSET``. Method applicability, capability checks, + and effective defaults are not resolved here. + """ + if isinstance(value, RepresentationConfig): + config = value + elif isinstance(value, str): + config = RepresentationConfig(method=value) + elif isinstance(value, Mapping): + config = RepresentationConfig.from_dict(value) + else: + raise invalid_param_error( + "RepresentationConfig", "value", value, "must be a string, mapping, or RepresentationConfig" + ) + canonical = NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS + aliases = NUMERICAL_ALIASES if is_numerical else CATEGORICAL_ALIASES + method = resolve_method(config.method, canonical, aliases) + return config if method == config.method else replace(config, method=method) + + def _normalize_method(method, canonical, aliases) -> str: """Resolve a global method name to canonical form, mapping ``None`` to ``"none"``.""" if method is None: diff --git a/tests/compose/test_representation_config.py b/tests/compose/test_representation_config.py index 4f4a1a0..65f2b98 100644 --- a/tests/compose/test_representation_config.py +++ b/tests/compose/test_representation_config.py @@ -3,14 +3,16 @@ import copy import json import pickle +from collections import UserDict from dataclasses import FrozenInstanceError, is_dataclass +from types import MappingProxyType from typing import Any, cast import pytest from sklearn.base import clone from pretab import Preprocessor -from pretab.compose.config import RepresentationConfig +from pretab.compose.config import RepresentationConfig, _normalize_representation_config from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError @@ -185,3 +187,96 @@ def test_mapping_keys_and_required_values_are_validated(): cast(Any, RepresentationConfig)(method="rbf", name=UNSET) with pytest.raises(InvalidParamError, match="params"): cast(Any, RepresentationConfig)(method="rbf", params=None) + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical", "canonical"), + [ + ("rbf", True, "rbf"), + (" R_B F ", True, "rbf"), + ("cubic", True, "cubicspline"), + ("std", True, "standardization"), + ("binning", True, "custombin"), + (" O_H E ", False, "one-hot"), + ("ordinal", False, "int"), + ("one_hot", False, "one-hot"), + ("ordinal", True, "ordinal"), + ("binning", False, "binning"), + ("identity", True, "none"), + ("identity", False, "none"), + ], +) +def test_normalization_forms_are_equivalent_in_their_namespace(form, method, is_numerical, canonical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + normalized = _normalize_representation_config(requested, is_numerical=is_numerical) + + assert normalized == RepresentationConfig(method=canonical) + assert normalized.output_dim is UNSET + assert normalized.to_dict() == {"method": canonical, "params": {}, "name": None} + + +@pytest.mark.parametrize("form", ["mapping", "value"]) +@pytest.mark.parametrize(("method", "is_numerical", "canonical"), [("RBF", True, "rbf"), ("OHE", False, "one-hot")]) +def test_normalization_preserves_explicit_and_omitted_settings(form, method, is_numerical, canonical): + data = { + "method": method, + "output_dim": 3, + "target_aware": False, + "placement_strategy": "uniform", + "min_output_dim": None, + "name": "feature", + "params": {"options": {"values": [None, False, 2, 0.5, "x"]}}, + } + requested = data if form == "mapping" else RepresentationConfig.from_dict(data) + normalized = _normalize_representation_config(requested, is_numerical=is_numerical) + + assert normalized.to_dict() == {**data, "method": canonical} + assert normalized.adaptive is UNSET + assert normalized.max_output_dim is UNSET + assert normalized.min_output_dim is None + assert data["method"] == method + if isinstance(requested, RepresentationConfig): + assert requested.method == method + assert _normalize_representation_config(normalized, is_numerical=is_numerical) == normalized + + +@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType]) +def test_normalization_detaches_mapping_at_the_boundary(mapping_type): + data = {"method": "RBF", "gamma": 0.5, "params": {"options": {"values": [1, 2]}}} + requested = mapping_type(data) + preprocessor = Preprocessor(feature_preprocessing={"age": requested}) + data["params"]["options"]["values"][0] = 3 + normalized = _normalize_representation_config(requested, is_numerical=True) + data["params"]["options"]["values"].append(4) + + assert normalized == RepresentationConfig(method="rbf", params={"gamma": 0.5, "options": {"values": [3, 2]}}) + assert preprocessor.get_params(deep=False)["feature_preprocessing"]["age"] is requested + assert requested["method"] == "RBF" + assert "gamma" in requested and "gamma" not in requested["params"] + assert _normalize_representation_config(requested, is_numerical=True).params["options"]["values"] == (3, 2, 4) + with pytest.raises(TypeError): + cast(Any, normalized.params)["changed"] = True + + +@pytest.mark.parametrize("is_numerical", [False, True]) +@pytest.mark.parametrize("value", [None, UNSET, [], 1, True, object(), lambda: "rbf"]) +def test_normalization_rejects_unsupported_input_types(value, is_numerical): + with pytest.raises(InvalidParamError, match="must be a string, mapping, or RepresentationConfig"): + _normalize_representation_config(value, is_numerical=is_numerical) + + +@pytest.mark.parametrize( + "data", + [ + {}, + {"method": None}, + {"method": "rbf", "output_dim": True}, + {"method": "rbf", "params": {"method": "ple"}}, + {"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}, + {"method": "rbf", "params": {"gamma": float("nan")}}, + ], +) +def test_normalization_reuses_value_shape_validation(data): + with pytest.raises(InvalidParamError): + _normalize_representation_config(data, is_numerical=True) From 5b859a79b33a971fa21f5009c748558c439a65f2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 11:08:16 +0100 Subject: [PATCH 17/86] feat(config): add path-aware representation validation --- pretab/compose/config.py | 100 +++++++++++------- tests/compose/test_representation_config.py | 111 +++++++++++++++++++- 2 files changed, 170 insertions(+), 41 deletions(-) diff --git a/pretab/compose/config.py b/pretab/compose/config.py index 95b46f5..a45625e 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -17,7 +17,9 @@ from __future__ import annotations from collections.abc import Iterator, Mapping, Sequence +from contextvars import ContextVar from dataclasses import dataclass, field, fields, replace +from difflib import get_close_matches from math import isfinite from typing import Any @@ -28,6 +30,7 @@ CATEGORICAL_METHODS, NUMERICAL_ALIASES, NUMERICAL_METHODS, + TRANSFORMER_REGISTRY, resolve_method, ) @@ -38,6 +41,14 @@ MISSING_POLICIES = frozenset({"error", "propagate", "impute", "impute_with_indicator", "separate_state"}) +_REPRESENTATION_PATH = ContextVar("representation_config_path", default="RepresentationConfig") + + +def _representation_error(param, value, constraint, *, valid=None): + """Use the standalone value name or the current normalization path.""" + return invalid_param_error(_REPRESENTATION_PATH.get(), param, value, constraint, valid=valid) + + @dataclass(frozen=True, slots=True, eq=False) class _FrozenParams(Mapping[str, Any]): _entries: tuple[tuple[str, Any], ...] @@ -64,19 +75,17 @@ def _freeze_config_value(value: Any, path: str, active: set[int]) -> Any: if type(value) is float and isfinite(value): return value if not isinstance(value, (Mapping, Sequence)) or isinstance(value, (str, bytes, bytearray, memoryview)): - raise invalid_param_error( - "RepresentationConfig", path, value, "must contain only finite JSON-compatible values" - ) + raise _representation_error(path, value, "must contain only finite JSON-compatible values") identity = id(value) if identity in active: - raise invalid_param_error("RepresentationConfig", path, value, "must not contain circular references") + raise _representation_error(path, value, "must not contain circular references") active.add(identity) try: if isinstance(value, Mapping): entries = [] for key, item in value.items(): if type(key) is not str: - raise invalid_param_error("RepresentationConfig", path, key, "mapping keys must be strings") + raise _representation_error(path, key, "mapping keys must be strings") entries.append((key, _freeze_config_value(item, f"{path}[{key!r}]", active))) return _FrozenParams(tuple(entries)) return tuple(_freeze_config_value(item, f"{path}[{index}]", active) for index, item in enumerate(value)) @@ -135,30 +144,29 @@ class RepresentationConfig: def __post_init__(self) -> None: if self.method is UNSET: - raise invalid_param_error("RepresentationConfig", "method", self.method, "is required") + raise _representation_error("method", self.method, "is required") for key in ("method", "placement_strategy", "name"): value = getattr(self, key) if (key == "placement_strategy" and value is UNSET) or (key == "name" and value is None): continue if type(value) is not str or not value.strip(): - raise invalid_param_error("RepresentationConfig", key, value, "must be a nonempty string") + raise _representation_error(key, value, "must be a nonempty string") for key in ("output_dim", "min_output_dim", "max_output_dim"): value = getattr(self, key) if value is UNSET or (key != "output_dim" and value is None): continue if type(value) is not int or value < 1: - raise invalid_param_error("RepresentationConfig", key, value, "must be a positive integer") + raise _representation_error(key, value, "must be a positive integer") for key in ("target_aware", "adaptive"): value = getattr(self, key) if value is not UNSET and type(value) is not bool: - raise invalid_param_error("RepresentationConfig", key, value, "must be a boolean") + raise _representation_error(key, value, "must be a boolean") if not isinstance(self.params, Mapping): - raise invalid_param_error("RepresentationConfig", "params", self.params, "must be a mapping") + raise _representation_error("params", self.params, "must be a mapping") reserved = {item.name for item in fields(self)} for key in self.params: if key in reserved: - raise invalid_param_error( - "RepresentationConfig", + raise _representation_error( f"params[{key!r}]", self.params[key], "must be supplied as a top-level field", @@ -182,51 +190,71 @@ def from_dict(cls, data: Mapping[str, Any]) -> RepresentationConfig: feature-kind context and is not performed by this constructor. """ if not isinstance(data, Mapping): - raise invalid_param_error("RepresentationConfig", "data", data, "must be a mapping") + raise _representation_error("data", data, "must be a mapping") requested = dict(data) if any(type(key) is not str for key in requested): - raise invalid_param_error("RepresentationConfig", "data", data, "mapping keys must be strings") + raise _representation_error("data", data, "mapping keys must be strings") if "method" not in requested: - raise invalid_param_error("RepresentationConfig", "method", UNSET, "is required") + raise _representation_error("method", UNSET, "is required") params = requested.pop("params", {}) if not isinstance(params, Mapping): - raise invalid_param_error("RepresentationConfig", "params", params, "must be a mapping") + raise _representation_error("params", params, "must be a mapping") params = dict(params) common = {item.name for item in fields(cls)} for key in list(requested): if key not in common: if key in params: - raise invalid_param_error( - "RepresentationConfig", key, requested[key], "must not also be supplied inside params" - ) + raise _representation_error(key, requested[key], "must not also be supplied inside params") params[key] = requested.pop(key) return cls(**requested, params=params) def _normalize_representation_config( - value: str | Mapping[str, Any] | RepresentationConfig, *, is_numerical: bool + value: str | Mapping[str, Any] | RepresentationConfig, + *, + is_numerical: bool, + path: str = "RepresentationConfig", ) -> RepresentationConfig: """Normalize one request in its known feature-kind namespace. Raw mappings detach through ``from_dict``. Typed values retain their requested spelling; normalization replaces rather than mutates an alias. - Omitted fields remain ``UNSET``. Method applicability, capability checks, - and effective defaults are not resolved here. + Omitted fields remain ``UNSET``. Unknown methods/options and invalid value + shapes raise path-qualified errors. Known but inapplicable options, + capability checks, and effective defaults are not resolved here. """ - if isinstance(value, RepresentationConfig): - config = value - elif isinstance(value, str): - config = RepresentationConfig(method=value) - elif isinstance(value, Mapping): - config = RepresentationConfig.from_dict(value) - else: - raise invalid_param_error( - "RepresentationConfig", "value", value, "must be a string, mapping, or RepresentationConfig" - ) - canonical = NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS - aliases = NUMERICAL_ALIASES if is_numerical else CATEGORICAL_ALIASES - method = resolve_method(config.method, canonical, aliases) - return config if method == config.method else replace(config, method=method) + token = _REPRESENTATION_PATH.set(path) + try: + if isinstance(value, RepresentationConfig): + config = value + elif isinstance(value, str): + config = RepresentationConfig(method=value) + elif isinstance(value, Mapping): + config = RepresentationConfig.from_dict(value) + else: + raise _representation_error("value", value, "must be a string, mapping, or RepresentationConfig") + canonical = NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS + aliases = NUMERICAL_ALIASES if is_numerical else CATEGORICAL_ALIASES + method = resolve_method(config.method, canonical, aliases) + if method not in canonical: + kind = "numerical" if is_numerical else "categorical" + raise _representation_error( + "method", method, f"unrecognized {kind} preprocessing method", valid=set(canonical) + ) + common = {item.name for item in fields(RepresentationConfig)} + known = common | {key for spec in TRANSFORMER_REGISTRY.values() for key in spec.allowed_args} + applicable = common | set(TRANSFORMER_REGISTRY[method].allowed_args) + for key in config.params: + if key not in known: + location = key if isinstance(value, Mapping) and key in value else f"params[{key!r}]" + matches = get_close_matches(key, sorted(applicable), n=3) + constraint = "unrecognized representation option" + if matches: + constraint += f". Did you mean {', '.join(repr(match) for match in matches)}?" + raise _representation_error(location, config.params[key], constraint, valid=applicable) + return config if method == config.method else replace(config, method=method) + finally: + _REPRESENTATION_PATH.reset(token) def _normalize_method(method, canonical, aliases) -> str: diff --git a/tests/compose/test_representation_config.py b/tests/compose/test_representation_config.py index 65f2b98..c08a883 100644 --- a/tests/compose/test_representation_config.py +++ b/tests/compose/test_representation_config.py @@ -4,7 +4,7 @@ import json import pickle from collections import UserDict -from dataclasses import FrozenInstanceError, is_dataclass +from dataclasses import FrozenInstanceError, is_dataclass, replace from types import MappingProxyType from typing import Any, cast @@ -13,10 +13,18 @@ from pretab import Preprocessor from pretab.compose.config import RepresentationConfig, _normalize_representation_config +from pretab.compose.factory import get_categorical_transformer_steps, get_numerical_transformer_steps +from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError +@pytest.fixture +def nested_registry_option(monkeypatch): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) + + def test_omitted_fields_remain_unset(): config = RepresentationConfig(method="rbf") @@ -201,8 +209,6 @@ def test_mapping_keys_and_required_values_are_validated(): (" O_H E ", False, "one-hot"), ("ordinal", False, "int"), ("one_hot", False, "one-hot"), - ("ordinal", True, "ordinal"), - ("binning", False, "binning"), ("identity", True, "none"), ("identity", False, "none"), ], @@ -218,7 +224,9 @@ def test_normalization_forms_are_equivalent_in_their_namespace(form, method, is_ @pytest.mark.parametrize("form", ["mapping", "value"]) @pytest.mark.parametrize(("method", "is_numerical", "canonical"), [("RBF", True, "rbf"), ("OHE", False, "one-hot")]) -def test_normalization_preserves_explicit_and_omitted_settings(form, method, is_numerical, canonical): +def test_normalization_preserves_explicit_and_omitted_settings( + form, method, is_numerical, canonical, nested_registry_option +): data = { "method": method, "output_dim": 3, @@ -242,7 +250,7 @@ def test_normalization_preserves_explicit_and_omitted_settings(form, method, is_ @pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType]) -def test_normalization_detaches_mapping_at_the_boundary(mapping_type): +def test_normalization_detaches_mapping_at_the_boundary(mapping_type, nested_registry_option): data = {"method": "RBF", "gamma": 0.5, "params": {"options": {"values": [1, 2]}}} requested = mapping_type(data) preprocessor = Preprocessor(feature_preprocessing={"age": requested}) @@ -280,3 +288,96 @@ def test_normalization_rejects_unsupported_input_types(value, is_numerical): def test_normalization_reuses_value_shape_validation(data): with pytest.raises(InvalidParamError): _normalize_representation_config(data, is_numerical=True) + + +@pytest.mark.parametrize("form", ["shorthand", "params", "value"]) +@pytest.mark.parametrize( + ("key", "suggestion"), + [("output_dimm", "output_dim"), ("target_awre", "target_aware"), ("gama", "gamma"), ("not_a_real_option", None)], +) +def test_path_errors_for_unknown_keys_include_close_matches(form, key, suggestion): + data: dict[str, Any] = {"method": "RBF"} + if form == "shorthand": + data[key] = 3 + else: + data["params"] = {key: 3} + requested = RepresentationConfig.from_dict(data) if form == "value" else data + path = "feature_preprocessing['age']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(requested, is_numerical=True, path=path) + + location = key if form == "shorthand" else f"params[{key!r}]" + message = str(failure.value) + assert f"{path}.{location} = 3 is invalid" in message + if suggestion is None: + assert "Did you mean" not in message + else: + assert "Did you mean" in message + assert repr(suggestion) in message.split("\nValid values:")[0] + assert data["method"] == "RBF" + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical"), + [("ordinal", True), ("binning", False), ("not_a_method", True), ("not_a_method", False), ("rbf", False)], +) +def test_path_errors_for_methods_reuse_canonical_factory_choices(form, method, is_numerical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + path = "feature_preprocessing['feature']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(requested, is_numerical=is_numerical, path=path) + factory = get_numerical_transformer_steps if is_numerical else get_categorical_transformer_steps + with pytest.raises(InvalidParamError) as existing: + factory(method, add_imputer=False) + + assert f"{path}.method" in str(failure.value) + assert str(failure.value).split("\nConstraint:")[1] == str(existing.value).split("\nConstraint:")[1] + + +@pytest.mark.parametrize( + ("data", "location"), + [ + ({}, "method"), + ({"method": None}, "method"), + ({"method": "rbf", "output_dim": 0}, "output_dim"), + ({"method": "rbf", "output_dim": True}, "output_dim"), + ({"method": "rbf", "target_aware": 1}, "target_aware"), + ({"method": "rbf", "placement_strategy": ""}, "placement_strategy"), + ({"method": "rbf", "adaptive": None}, "adaptive"), + ({"method": "rbf", "min_output_dim": -1}, "min_output_dim"), + ({"method": "rbf", "params": []}, "params"), + ({"method": "rbf", "params": {"method": "ple"}}, "params['method']"), + ({"method": "rbf", "params": {"gamma": [float("inf")]}}, "params['gamma'][0]"), + ({"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}, "gamma"), + ], +) +def test_path_errors_reuse_common_and_nested_value_checks(data, location): + path = "feature_preprocessing['a.b[0]']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(data, is_numerical=True, path=path) + assert f"{path}.{location}" in str(failure.value) + + +@pytest.mark.parametrize("succeeds", [False, True]) +def test_path_errors_do_not_leak_into_standalone_value_validation(succeeds): + if succeeds: + _normalize_representation_config("rbf", is_numerical=True, path="feature_preprocessing['age']") + else: + with pytest.raises(InvalidParamError): + _normalize_representation_config({"method": "rbf", "output_dim": 0}, is_numerical=True, path="other") + with pytest.raises(InvalidParamError) as failure: + RepresentationConfig(method="") + assert str(failure.value).startswith("RepresentationConfig.method") + + +def test_path_errors_follow_the_live_registry_without_checking_applicability(monkeypatch): + data = {"method": "rbf", "plugin_strength": 0.5} + with pytest.raises(InvalidParamError, match="plugin_strength"): + _normalize_representation_config(data, is_numerical=True) + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "plugin_strength")) + ) + assert _normalize_representation_config(data, is_numerical=True).params["plugin_strength"] == 0.5 + assert _normalize_representation_config({"method": "ohe", "degree": 3}, is_numerical=False).params["degree"] == 3 From 4fe3f9d6ae24d47184dbc2f4e9b74109cefd09f1 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 13:32:40 +0100 Subject: [PATCH 18/86] feat(config): validate representation capabilities --- pretab/compose/config.py | 71 +++++++++- pretab/core/dependencies.py | 10 ++ tests/compose/test_representation_config.py | 141 +++++++++++++++++++- 3 files changed, 212 insertions(+), 10 deletions(-) diff --git a/pretab/compose/config.py b/pretab/compose/config.py index a45625e..4ad6858 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -23,8 +23,9 @@ from math import isfinite from typing import Any +from ..core.dependencies import _check_optional_dependency from ..core.parameters import UNSET, _Unset, validate_placement, validate_task -from ..exceptions import invalid_param_error +from ..exceptions import InvalidParamError, invalid_param_error from .registry import ( CATEGORICAL_ALIASES, CATEGORICAL_METHODS, @@ -209,6 +210,66 @@ def from_dict(cls, data: Mapping[str, Any]) -> RepresentationConfig: return cls(**requested, params=params) +def _validate_representation_capabilities( + config: RepresentationConfig, *, is_numerical: bool, source: str | Mapping[str, Any] | RepresentationConfig +) -> None: + """Check explicit settings against the live spec without choosing defaults.""" + spec = TRANSFORMER_REGISTRY[config.method] + kind = "numerical" if is_numerical else "categorical" + if kind not in spec.feature_kind: + raise _representation_error("method", config.method, f"does not support {kind} features") + if not spec.preprocessor_compatible: + raise _representation_error("method", config.method, "is not selectable through Preprocessor") + for key, value in config.params.items(): + if key not in spec.allowed_args: + location = key if isinstance(source, Mapping) and key in source else f"params[{key!r}]" + raise _representation_error( + location, value, f"is not applicable to method {config.method!r}", valid=spec.allowed_args + ) + if ( + config.output_dim is not UNSET + and "output_dim" not in spec.allowed_args + and not spec.supports_adaptive_resolution + ): + raise _representation_error("output_dim", config.output_dim, f"is not applicable to method {config.method!r}") + for key in ("adaptive", "min_output_dim", "max_output_dim"): + value = getattr(config, key) + if value is not UNSET and not spec.supports_adaptive_resolution: + raise _representation_error(key, value, f"method {config.method!r} does not support adaptive resolution") + if config.target_aware is True and spec.target_usage == "forbidden": + raise _representation_error("target_aware", True, f"method {config.method!r} cannot use the target") + if config.target_aware is False and spec.target_usage == "required": + raise _representation_error("target_aware", False, f"method {config.method!r} requires the target") + if isinstance(config.placement_strategy, str): + if config.placement_strategy not in spec.placement_strategies: + raise _representation_error( + "placement_strategy", + config.placement_strategy, + f"is not supported by method {config.method!r}", + valid=spec.placement_strategies, + ) + target_aware = config.target_aware + if target_aware is UNSET and spec.target_usage != "optional": + target_aware = spec.target_usage == "required" + if isinstance(target_aware, bool): + try: + validate_placement(target_aware, config.placement_strategy) + except InvalidParamError as error: + raise _representation_error("placement_strategy", config.placement_strategy, str(error)) from error + for key in ("min_output_dim", "max_output_dim"): + value = getattr(config, key) + if config.adaptive is False and value is not UNSET: + raise _representation_error(key, value, "must not be supplied with adaptive=False") + if config.adaptive is True and type(config.min_output_dim) is int and type(config.max_output_dim) is int: + if config.min_output_dim > config.max_output_dim: + raise _representation_error("max_output_dim", config.max_output_dim, "must be >= min_output_dim") + path = _REPRESENTATION_PATH.get() + if spec.optional_dependency: + _check_optional_dependency(spec.optional_dependency, f"{path}.method = {config.method!r}") + if config.placement_strategy == "lightgbm": + _check_optional_dependency("lightgbm", f"{path}.placement_strategy = 'lightgbm'") + + def _normalize_representation_config( value: str | Mapping[str, Any] | RepresentationConfig, *, @@ -220,8 +281,8 @@ def _normalize_representation_config( Raw mappings detach through ``from_dict``. Typed values retain their requested spelling; normalization replaces rather than mutates an alias. Omitted fields remain ``UNSET``. Unknown methods/options and invalid value - shapes raise path-qualified errors. Known but inapplicable options, - capability checks, and effective defaults are not resolved here. + shapes raise path-qualified errors. Explicit options are checked against + live registry capabilities; omitted effective defaults remain unresolved. """ token = _REPRESENTATION_PATH.set(path) try: @@ -252,7 +313,9 @@ def _normalize_representation_config( if matches: constraint += f". Did you mean {', '.join(repr(match) for match in matches)}?" raise _representation_error(location, config.params[key], constraint, valid=applicable) - return config if method == config.method else replace(config, method=method) + normalized = config if method == config.method else replace(config, method=method) + _validate_representation_capabilities(normalized, is_numerical=is_numerical, source=value) + return normalized finally: _REPRESENTATION_PATH.reset(token) diff --git a/pretab/core/dependencies.py b/pretab/core/dependencies.py index 234ecd3..4c4bd26 100644 --- a/pretab/core/dependencies.py +++ b/pretab/core/dependencies.py @@ -10,6 +10,7 @@ from __future__ import annotations import importlib +import importlib.util from types import ModuleType from ..exceptions import OptionalDependencyError @@ -21,6 +22,15 @@ ] +def _check_optional_dependency(extra: str, purpose: str) -> None: + """Check top-level discovery without importing an optional model package.""" + module_name = "sentence_transformers" if extra == "embeddings" else extra + if importlib.util.find_spec(module_name.partition(".")[0]) is None: + raise OptionalDependencyError( + f"{purpose} requires the optional '{module_name}' dependency. Install it with: pip install pretab[{extra}]" + ) + + def require_module(module_name: str, extra: str, purpose: str) -> ModuleType: """Import ``module_name`` or raise :class:`OptionalDependencyError`. diff --git a/tests/compose/test_representation_config.py b/tests/compose/test_representation_config.py index c08a883..e46fc27 100644 --- a/tests/compose/test_representation_config.py +++ b/tests/compose/test_representation_config.py @@ -16,13 +16,14 @@ from pretab.compose.factory import get_categorical_transformer_steps, get_numerical_transformer_steps from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.core.parameters import UNSET -from pretab.exceptions import InvalidParamError +from pretab.exceptions import InvalidParamError, OptionalDependencyError @pytest.fixture def nested_registry_option(monkeypatch): - spec = TRANSFORMER_REGISTRY["rbf"] - monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) + for method in ("rbf", "cubicspline"): + spec = TRANSFORMER_REGISTRY[method] + monkeypatch.setitem(TRANSFORMER_REGISTRY, method, replace(spec, allowed_args=(*spec.allowed_args, "options"))) def test_omitted_fields_remain_unset(): @@ -223,7 +224,9 @@ def test_normalization_forms_are_equivalent_in_their_namespace(form, method, is_ @pytest.mark.parametrize("form", ["mapping", "value"]) -@pytest.mark.parametrize(("method", "is_numerical", "canonical"), [("RBF", True, "rbf"), ("OHE", False, "one-hot")]) +@pytest.mark.parametrize( + ("method", "is_numerical", "canonical"), [("RBF", True, "rbf"), ("Cubic", True, "cubicspline")] +) def test_normalization_preserves_explicit_and_omitted_settings( form, method, is_numerical, canonical, nested_registry_option ): @@ -371,7 +374,7 @@ def test_path_errors_do_not_leak_into_standalone_value_validation(succeeds): assert str(failure.value).startswith("RepresentationConfig.method") -def test_path_errors_follow_the_live_registry_without_checking_applicability(monkeypatch): +def test_path_errors_follow_the_live_registry_and_check_applicability(monkeypatch): data = {"method": "rbf", "plugin_strength": 0.5} with pytest.raises(InvalidParamError, match="plugin_strength"): _normalize_representation_config(data, is_numerical=True) @@ -380,4 +383,130 @@ def test_path_errors_follow_the_live_registry_without_checking_applicability(mon TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "plugin_strength")) ) assert _normalize_representation_config(data, is_numerical=True).params["plugin_strength"] == 0.5 - assert _normalize_representation_config({"method": "ohe", "degree": 3}, is_numerical=False).params["degree"] == 3 + with pytest.raises(InvalidParamError, match="degree"): + _normalize_representation_config({"method": "ohe", "degree": 3}, is_numerical=False) + + +@pytest.mark.parametrize( + ("data", "is_numerical", "location"), + [ + ({"method": "ohe", "degree": 3}, False, "degree"), + ({"method": "rbf", "params": {"degree": 3}}, True, "params['degree']"), + ({"method": "polynomial", "gamma": 1.0}, True, "gamma"), + ({"method": "ohe", "output_dim": 3}, False, "output_dim"), + ({"method": "minmax", "adaptive": False}, True, "adaptive"), + ({"method": "custombin", "adaptive": True}, True, "adaptive"), + ({"method": "ohe", "min_output_dim": None}, False, "min_output_dim"), + ({"method": "ple", "target_aware": False}, True, "target_aware"), + ({"method": "pspline", "target_aware": True}, True, "target_aware"), + ({"method": "pspline", "placement_strategy": "quantile"}, True, "placement_strategy"), + ({"method": "ohe", "placement_strategy": "uniform"}, False, "placement_strategy"), + ({"method": "rbf", "placement_strategy": "even"}, True, "placement_strategy"), + ({"method": "rbf", "target_aware": False, "placement_strategy": "cart"}, True, "placement_strategy"), + ({"method": "rbf", "target_aware": True, "placement_strategy": "uniform"}, True, "placement_strategy"), + ({"method": "rbf", "adaptive": False, "max_output_dim": None}, True, "max_output_dim"), + ({"method": "rbf", "adaptive": True, "min_output_dim": 5, "max_output_dim": 3}, True, "max_output_dim"), + ], +) +def test_capability_errors_name_the_explicit_option_and_source(data, is_numerical, location): + path = "feature_preprocessing['age']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(data, is_numerical=is_numerical, path=path) + assert f"{path}.{location}" in str(failure.value) + + +@pytest.mark.parametrize( + "data", + [ + {"method": "rbf", "output_dim": 3, "gamma": 0.5}, + {"method": "bspline", "output_dim": 3}, + {"method": "mspline", "output_dim": 5}, + {"method": "ispline", "output_dim": 5}, + {"method": "pspline", "output_dim": 5, "target_aware": False, "placement_strategy": "uniform"}, + {"method": "ple", "target_aware": True, "placement_strategy": "cart", "adaptive": True}, + {"method": "rbf", "placement_strategy": "quantile"}, + {"method": "rbf", "target_aware": False}, + {"method": "rbf", "adaptive": True, "min_output_dim": None, "max_output_dim": None}, + ], +) +def test_capability_validation_preserves_explicit_requests_without_filling_defaults(data): + normalized = _normalize_representation_config(data, is_numerical=True) + assert normalized == RepresentationConfig.from_dict(data) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("feature_kind", frozenset({"categorical"})), + ("preprocessor_compatible", False), + ("supports_adaptive_resolution", False), + ], +) +def test_capability_validation_uses_live_metadata_even_when_derived_views_are_unchanged(monkeypatch, field, value): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, **{field: value})) + with pytest.raises(InvalidParamError): + _normalize_representation_config({"method": "rbf", "adaptive": True}, is_numerical=True) + + +@pytest.mark.parametrize("method", ["tensor", "thinplate", "rff", "nystroem"]) +def test_capability_validation_does_not_make_standalone_methods_selectable(method): + with pytest.raises(InvalidParamError, match="method"): + _normalize_representation_config(method, is_numerical=True) + + +@pytest.mark.parametrize("available", [False, True]) +@pytest.mark.parametrize(("method", "is_numerical"), [("pretrained", False), ("rbf", True)]) +def test_optional_dependency_metadata_is_checked_without_import_or_construction( + monkeypatch, method, is_numerical, available +): + discovered = [] + + def discover(module_name): + discovered.append(module_name) + return object() if available else None + + def unexpected(*args, **kwargs): + pytest.fail("normalization must not import optional packages or construct a transformer") + + spec = TRANSFORMER_REGISTRY[method] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, method, replace(spec, optional_dependency="embeddings", transformer_cls=unexpected) + ) + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", discover) + monkeypatch.setattr("pretab.core.dependencies.importlib.import_module", unexpected) + path = "feature_preprocessing['city']" + if available: + assert _normalize_representation_config(method, is_numerical=is_numerical, path=path).method == method + else: + with pytest.raises(OptionalDependencyError) as failure: + _normalize_representation_config(method, is_numerical=is_numerical, path=path) + assert f"{path}.method" in str(failure.value) + assert "pip install pretab[embeddings]" in str(failure.value) + assert discovered == ["sentence_transformers"] + + +@pytest.mark.parametrize("available", [False, True]) +def test_explicit_lightgbm_placement_uses_import_free_dependency_check(monkeypatch, available): + discovered = [] + + def discover(module_name): + discovered.append(module_name) + return object() if available else None + + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", discover) + data = {"method": "rbf", "target_aware": True, "placement_strategy": "lightgbm"} + if available: + assert _normalize_representation_config(data, is_numerical=True).placement_strategy == "lightgbm" + else: + with pytest.raises(OptionalDependencyError, match=r"RepresentationConfig.placement_strategy.*lightgbm"): + _normalize_representation_config(data, is_numerical=True) + assert discovered == ["lightgbm"] + + +def test_capability_validation_does_not_check_unselected_optional_dependencies(monkeypatch): + def unexpected(*args, **kwargs): + pytest.fail("no optional dependency is selected") + + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", unexpected) + assert _normalize_representation_config("rbf", is_numerical=True).target_aware is UNSET From de7fdecc06f538a78a9c70fde6ca61839748b060 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 14:07:20 +0100 Subject: [PATCH 19/86] feat(config): resolve per-feature representation settings --- pretab/compose/config.py | 80 +++++++++--- tests/compose/test_config.py | 245 ++++++++++++++++++++++++++++++++++- 2 files changed, 308 insertions(+), 17 deletions(-) diff --git a/pretab/compose/config.py b/pretab/compose/config.py index 4ad6858..49b3f9b 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -8,10 +8,9 @@ the estimator (as scikit-learn requires); this object is the internal, normalized counterpart the composition layer consumes. -Per-column overrides in ``feature_preprocessing`` are kept verbatim because the -namespace they resolve in (numerical vs categorical) depends on the column type, -which is only known after feature detection; :meth:`PreprocessorConfig.method_for` -resolves them in the correct namespace at build time. +Structured per-column overrides detach at normalization. Their method namespace +(numerical vs categorical) depends on feature detection; ``method_for`` keeps +returning a string, while ``representation_for`` resolves applicable settings. """ from __future__ import annotations @@ -270,6 +269,16 @@ def _validate_representation_capabilities( _check_optional_dependency("lightgbm", f"{path}.placement_strategy = 'lightgbm'") +def _representation_request(value: str | Mapping[str, Any] | RepresentationConfig) -> RepresentationConfig: + if isinstance(value, RepresentationConfig): + return value + if isinstance(value, str): + return RepresentationConfig(method=value) + if isinstance(value, Mapping): + return RepresentationConfig.from_dict(value) + raise _representation_error("value", value, "must be a string, mapping, or RepresentationConfig") + + def _normalize_representation_config( value: str | Mapping[str, Any] | RepresentationConfig, *, @@ -286,14 +295,7 @@ def _normalize_representation_config( """ token = _REPRESENTATION_PATH.set(path) try: - if isinstance(value, RepresentationConfig): - config = value - elif isinstance(value, str): - config = RepresentationConfig(method=value) - elif isinstance(value, Mapping): - config = RepresentationConfig.from_dict(value) - else: - raise _representation_error("value", value, "must be a string, mapping, or RepresentationConfig") + config = _representation_request(value) canonical = NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS aliases = NUMERICAL_ALIASES if is_numerical else CATEGORICAL_ALIASES method = resolve_method(config.method, canonical, aliases) @@ -332,8 +334,9 @@ class PreprocessorConfig: """Frozen, normalized configuration derived from Preprocessor parameters. Built via :meth:`from_params`, which normalizes the global method names and - validates the placement contract and the task. All other knobs are carried - through as-is for the factory and orchestration layers. + validates the placement contract and the task. Structured overrides detach + into immutable requests; their feature-kind resolution is deferred until + ``method_for`` or ``representation_for`` is called. """ numerical_method: str @@ -402,10 +405,19 @@ def from_params( "must be None or one of 'error', 'propagate', 'impute', 'impute_with_indicator', 'separate_state'", valid=set(MISSING_POLICIES), ) + overrides = dict(feature_preprocessing or {}) + for feature, value in overrides.items(): + if isinstance(value, str): + continue + token = _REPRESENTATION_PATH.set(f"feature_preprocessing[{feature!r}]") + try: + overrides[feature] = _representation_request(value) + finally: + _REPRESENTATION_PATH.reset(token) return cls( numerical_method=_normalize_method(numerical_method, NUMERICAL_METHODS, NUMERICAL_ALIASES), categorical_method=_normalize_method(categorical_method, CATEGORICAL_METHODS, CATEGORICAL_ALIASES), - feature_preprocessing=dict(feature_preprocessing or {}), + feature_preprocessing=overrides, output_dim=output_dim, degree=degree, target_aware=target_aware, @@ -444,8 +456,46 @@ def method_for(self, feature, *, is_numerical: bool) -> str: """ default = self.numerical_method if is_numerical else self.categorical_method raw = self.feature_preprocessing.get(feature, default) + if isinstance(raw, (Mapping, RepresentationConfig)): + return _normalize_representation_config( + raw, is_numerical=is_numerical, path=f"feature_preprocessing[{feature!r}]" + ).method return self.resolve_numerical(raw) if is_numerical else self.resolve_categorical(raw) + def representation_for(self, feature, *, is_numerical: bool) -> RepresentationConfig: + """Resolve one feature request over applicable constructor-wide controls. + + Method defaults remain omitted when the existing factory would not + forward a constructor-wide value. Inherited inactive adaptive bounds + are dropped, but contradictory explicit local bounds are rejected. + """ + default = self.numerical_method if is_numerical else self.categorical_method + raw = self.feature_preprocessing.get(feature, default) + path = f"feature_preprocessing[{feature!r}]" + requested = _normalize_representation_config(raw, is_numerical=is_numerical, path=path) + spec = TRANSFORMER_REGISTRY[requested.method] + inherited = {} + if "output_dim" in spec.allowed_args or spec.supports_adaptive_resolution: + inherited["output_dim"] = self.output_dim + if spec.target_usage in ("optional", "required"): + inherited["target_aware"] = self.target_aware + if spec.placement_strategies and (spec.target_usage != "forbidden" or not self.target_aware): + inherited["placement_strategy"] = self.placement_strategy + if spec.supports_adaptive_resolution: + adaptive = self.adaptive if requested.adaptive is UNSET else requested.adaptive + if requested.output_dim is not UNSET and requested.adaptive is UNSET: + adaptive = False + inherited["adaptive"] = adaptive + if adaptive: + 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} + params.update(requested.params) + settings = {key: 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) + @property def seed_kwargs(self) -> dict: """Return ``{"random_state": ...}`` only when a seed was explicitly set. diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index 71acd31..956bf3c 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -1,10 +1,12 @@ """Unit tests for :class:`pretab.compose.config.PreprocessorConfig`.""" -from dataclasses import asdict +from dataclasses import asdict, replace import pytest -from pretab import Preprocessor +from pretab import Preprocessor, RepresentationConfig +from pretab.compose.registry import TRANSFORMER_REGISTRY +from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError from pretab.preprocessor import PRESETS @@ -177,3 +179,242 @@ def test_method_for_resolves_in_the_requested_namespace(make_config): def test_seed_kwargs_reflects_random_state(make_config): assert make_config(random_state=None).seed_kwargs == {} assert make_config(random_state=42).seed_kwargs == {"random_state": 42} + + +@pytest.mark.parametrize("typed", [False, True]) +def test_structured_overrides_detach_and_keep_string_method_lookup(make_config, typed): + data = {"method": "RBF", "output_dim": 3, "gamma": 0.5} + value = RepresentationConfig.from_dict(data) if typed else data + config = make_config(feature_preprocessing={"age": value}, adaptive=True) + data["output_dim"] = 9 + requested = config.feature_preprocessing["age"] + resolved = config.representation_for("age", is_numerical=True) + + assert requested == RepresentationConfig(method="RBF", output_dim=3, params={"gamma": 0.5}) + assert config.method_for("age", is_numerical=True) == "rbf" + assert resolved.output_dim == 3 + assert resolved.adaptive is False + assert resolved.min_output_dim is UNSET + assert resolved.max_output_dim is UNSET + assert resolved.params == {"gamma": 0.5, "task": "regression"} + assert requested.target_aware is UNSET + + +@pytest.mark.parametrize("local", [{"adaptive": True}, {}]) +def test_representation_resolution_inherits_applicable_defaults(make_config, local): + config = make_config( + feature_preprocessing={"age": {"method": "cubic", **local}}, + output_dim=11, + degree=2, + adaptive=True, + min_output_dim=3, + max_output_dim=15, + random_state=17, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved == RepresentationConfig( + method="cubicspline", + output_dim=11, + target_aware=False, + placement_strategy="uniform", + adaptive=True, + min_output_dim=3, + max_output_dim=15, + params={"degree": 2, "task": "regression", "random_state": 17}, + ) + + +def test_representation_resolution_keeps_explicit_adaptive_width_and_bounds(make_config): + config = make_config( + feature_preprocessing={ + "age": {"method": "rbf", "output_dim": 3, "adaptive": True, "min_output_dim": None, "max_output_dim": 12} + } + ) + resolved = config.representation_for("age", is_numerical=True) + assert (resolved.output_dim, resolved.adaptive, resolved.min_output_dim, resolved.max_output_dim) == ( + 3, + True, + None, + 12, + ) + + +@pytest.mark.parametrize("method", ["ohe", "ordinal", "identity"]) +def test_representation_resolution_filters_unrelated_constructor_defaults(make_config, method): + config = make_config( + feature_preprocessing={"city": {"method": method}}, target_aware=True, placement_strategy="cart", adaptive=True + ) + resolved = config.representation_for("city", is_numerical=False) + assert resolved == RepresentationConfig(method=config.method_for("city", is_numerical=False)) + + +def test_representation_resolution_rejects_effective_placement_conflict(make_config): + config = make_config( + target_aware=True, + placement_strategy="cart", + feature_preprocessing={"age": {"method": "rbf", "target_aware": False}}, + ) + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].placement_strategy"): + config.representation_for("age", is_numerical=True) + + +def test_representation_resolution_rejects_explicit_bounds_in_fixed_mode(make_config): + config = make_config(feature_preprocessing={"age": {"method": "rbf", "min_output_dim": 2}}) + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].min_output_dim"): + config.representation_for("age", is_numerical=True) + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical"), + [("RBF", True), ("cubic", True), ("b-spline", True), ("OHE", False), ("identity", False)], +) +def test_representation_resolution_forms_are_equivalent(make_config, form, method, is_numerical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + config = make_config(feature_preprocessing={"feature": requested}) + expected = make_config(feature_preprocessing={"feature": method}).representation_for( + "feature", is_numerical=is_numerical + ) + assert config.representation_for("feature", is_numerical=is_numerical) == expected + assert config.method_for("feature", is_numerical=is_numerical) == expected.method + + +def test_normalized_feature_requests_snapshot_nested_values_at_the_boundary(make_config, monkeypatch): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) + nested = {"values": [1, {"weight": 0.5}]} + raw = {"age": {"method": "rbf", "params": {"options": nested}}} + preprocessor = Preprocessor(feature_preprocessing=raw) + assert preprocessor.get_params(deep=False)["feature_preprocessing"] is raw + nested["values"].append(2) + config = make_config(feature_preprocessing=raw) + nested["values"].append(3) + raw["age"]["params"]["options"] = {"changed": True} + + requested = config.feature_preprocessing["age"] + assert requested.params["options"]["values"] == (1, {"weight": 0.5}, 2) + resolved = config.representation_for("age", is_numerical=True) + view = resolved.to_dict() + view["params"]["options"]["values"].append(4) + assert config.representation_for("age", is_numerical=True) == resolved + assert requested.params["options"]["values"] == (1, {"weight": 0.5}, 2) + + +@pytest.mark.parametrize( + ("data", "location"), + [ + ({}, "method"), + ({"method": "rbf", "output_dim": True}, "output_dim"), + ({"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}, "gamma"), + ({"method": "rbf", "params": {"output_dim": 3}}, "params"), + (None, "value"), + ], +) +def test_structured_override_shape_errors_keep_the_feature_path(make_config, data, location): + with pytest.raises(InvalidParamError) as failure: + make_config(feature_preprocessing={"age": data}) + assert "feature_preprocessing['age']" in str(failure.value) + assert location in str(failure.value) + with pytest.raises(InvalidParamError) as standalone: + RepresentationConfig(method="") + assert str(standalone.value).startswith("RepresentationConfig.method") + + +def test_structured_override_namespace_validation_waits_for_feature_detection(make_config): + config = make_config(feature_preprocessing={"city": {"method": "ohe"}}) + assert config.method_for("city", is_numerical=False) == "one-hot" + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['city'\].method"): + config.method_for("city", is_numerical=True) + + +@pytest.mark.parametrize("method", ["not_a_method", "ordinal"]) +def test_legacy_method_lookup_still_defers_invalid_names(make_config, method): + config = make_config(feature_preprocessing={"age": method}) + assert config.method_for("age", is_numerical=True) == method + + +def test_representation_resolution_uses_the_global_method_without_an_override(make_config): + config = make_config(numerical_method="cubic", degree=2) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.method == "cubicspline" + assert resolved.output_dim == 7 + assert resolved.params == {"degree": 2, "task": "regression"} + assert resolved.adaptive is False + assert resolved.min_output_dim is UNSET + assert resolved.max_output_dim is UNSET + + +@pytest.mark.parametrize("random_state", [None, 0, 17]) +def test_representation_resolution_preserves_seed_forwarding(make_config, random_state): + config = make_config(numerical_method="rbf", random_state=random_state) + resolved = config.representation_for("age", is_numerical=True) + assert ("random_state" in resolved.params) == (random_state is not None) + if random_state is not None: + assert resolved.params["random_state"] == random_state + + +def test_explicit_family_options_override_constructor_controls_independently(make_config): + config = make_config( + degree=3, + task="regression", + random_state=17, + feature_preprocessing={"age": {"method": "cubic", "degree": 2, "task": "classification", "random_state": None}}, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.params == {"degree": 2, "task": "classification", "random_state": None} + assert config.task == "regression" + assert config.random_state == 17 + + +@pytest.mark.parametrize("local", [{"output_dim": 3}, {"adaptive": False}, {"output_dim": 3, "adaptive": False}]) +def test_fixed_local_requests_ignore_inherited_bounds(make_config, local): + config = make_config( + adaptive=True, + min_output_dim=8, + max_output_dim=5, + feature_preprocessing={"age": {"method": "rbf", **local}}, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.adaptive is False + assert resolved.min_output_dim is UNSET + assert resolved.max_output_dim is UNSET + + +@pytest.mark.parametrize("adaptive", [False, True]) +def test_local_bounds_alone_do_not_opt_into_adaptive_resolution(make_config, adaptive): + config = make_config(adaptive=adaptive, feature_preprocessing={"age": {"method": "rbf", "max_output_dim": 12}}) + if adaptive: + assert config.representation_for("age", is_numerical=True).max_output_dim == 12 + else: + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].max_output_dim"): + config.representation_for("age", is_numerical=True) + + +def test_active_inherited_bound_relationships_are_validated(make_config): + config = make_config( + adaptive=True, min_output_dim=8, max_output_dim=5, feature_preprocessing={"age": {"method": "rbf"}} + ) + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].max_output_dim"): + config.representation_for("age", is_numerical=True) + + +def test_explicit_unsupervised_pair_overrides_supervised_constructor_settings(make_config): + config = make_config( + target_aware=True, + placement_strategy="cart", + feature_preprocessing={"age": {"method": "rbf", "target_aware": False, "placement_strategy": "quantile"}}, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.target_aware is False + assert resolved.placement_strategy == "quantile" + + +def test_fixed_placement_family_keeps_existing_factory_default_filtering(make_config): + config = make_config( + target_aware=True, placement_strategy="cart", feature_preprocessing={"age": {"method": "pspline"}} + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.output_dim == 7 + assert resolved.params == {"degree": 3} + assert resolved.placement_strategy is UNSET + assert resolved.target_aware is UNSET From eacfb288d68c7316350a1589c4f5a4fd3853e919 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 15:00:43 +0100 Subject: [PATCH 20/86] feat(factory): accept resolved representation configs --- pretab/compose/factory.py | 72 ++++--- tests/compose/test_factory.py | 202 +++++++++++++++++- .../extension/test_registration_discovery.py | 18 ++ 3 files changed, 266 insertions(+), 26 deletions(-) diff --git a/pretab/compose/factory.py b/pretab/compose/factory.py index c518edc..d3a3f99 100644 --- a/pretab/compose/factory.py +++ b/pretab/compose/factory.py @@ -19,7 +19,7 @@ from ..exceptions import ConfigWarning, IncompatibleParamsError, invalid_param_error from ..preprocessing.floats import ToFloatTransformer from ..preprocessing.missing import MissingStateIndicator, _CategoricalMissingNormalizer -from .config import PreprocessorConfig +from .config import PreprocessorConfig, RepresentationConfig, _normalize_representation_config from .registry import ( CATEGORICAL_ALIASES, CATEGORICAL_METHODS, @@ -268,12 +268,20 @@ def get_categorical_transformer_steps( return steps -def create_transformer(method: str, *, is_numerical: bool, config: PreprocessorConfig) -> Pipeline | FeatureUnion: +def create_transformer( + method: str, + *, + is_numerical: bool, + config: PreprocessorConfig, + representation: RepresentationConfig | None = None, +) -> Pipeline | FeatureUnion: """Build the per-column :class:`~sklearn.pipeline.Pipeline` for one feature. ``method`` is the resolved method name; ``is_numerical`` selects the numerical - or categorical construction path. All width / placement / seeding knobs are - taken from ``config``. + or categorical construction path. When ``representation`` is supplied, its + resolved settings replace the run-wide representation controls. Otherwise + existing calls use ``config`` unchanged. Imputation, scaling, and indicator + policy always come from ``config``. Raises ------ @@ -282,10 +290,43 @@ def create_transformer(method: str, *, is_numerical: bool, config: PreprocessorC run is configured with ``target_aware=False``; such a combination cannot be satisfied and is rejected instead of silently ignored. """ + if representation is None: + shared_kwargs = { + "task": config.task, + "target_aware": config.target_aware, + "output_dim": config.output_dim, + "adaptive": config.adaptive, + "min_output_dim": config.min_output_dim if config.adaptive else None, + "max_output_dim": config.max_output_dim if config.adaptive else None, + "degree": config.degree, + "placement_strategy": config.placement_strategy, + **config.seed_kwargs, + } + else: + if not isinstance(representation, RepresentationConfig): + raise invalid_param_error( + "create_transformer", "representation", representation, "must be a RepresentationConfig or None" + ) + representation = _normalize_representation_config( + representation, is_numerical=is_numerical, path="create_transformer.representation" + ) + resolved_method = config.resolve_numerical(method) if is_numerical else config.resolve_categorical(method) + if resolved_method != representation.method: + raise invalid_param_error( + "create_transformer", + "representation.method", + representation.method, + f"must match the selected method {resolved_method!r}", + ) + method = representation.method + settings = representation.to_dict() + shared_kwargs = {key: value for key, value in settings.items() if key not in {"method", "params", "name"}} + shared_kwargs.update(settings["params"]) + known = method in NUMERICAL_METHODS if is_numerical else method in CATEGORICAL_METHODS if known: spec = get_spec(method) - if spec.requires_target and not config.target_aware: + if representation is None and spec.requires_target and not config.target_aware: raise IncompatibleParamsError( f"method {method!r} is always target-aware and requires target_aware=True " f"with placement_strategy in {{'cart', 'lightgbm'}}; got target_aware=False." @@ -295,33 +336,14 @@ def create_transformer(method: str, *, is_numerical: bool, config: PreprocessorC if is_numerical: steps = get_numerical_transformer_steps( method=method, - task=config.task, - target_aware=config.target_aware, add_imputer=plan["add_imputer"], imputer_strategy=plan["strategy"], - output_dim=config.output_dim, - adaptive=config.adaptive, - min_output_dim=config.min_output_dim if config.adaptive else None, - max_output_dim=config.max_output_dim if config.adaptive else None, - degree=config.degree, scaling=config.scaling, - placement_strategy=config.placement_strategy, - **config.seed_kwargs, + **shared_kwargs, ) else: constructor_kwargs = {} if known: - shared_kwargs = { - "task": config.task, - "target_aware": config.target_aware, - "output_dim": config.output_dim, - "adaptive": config.adaptive, - "min_output_dim": config.min_output_dim if config.adaptive else None, - "max_output_dim": config.max_output_dim if config.adaptive else None, - "degree": config.degree, - "placement_strategy": config.placement_strategy, - **config.seed_kwargs, - } constructor_kwargs = _filter_kwargs(spec.allowed_args, shared_kwargs) constructor_kwargs.update(_placement_kwargs(spec, shared_kwargs)) steps = get_categorical_transformer_steps( diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index 04a2c7f..6dcd137 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -6,11 +6,12 @@ import numpy as np import pandas as pd import pytest +from scipy.sparse import issparse from sklearn.compose import ColumnTransformer from sklearn.pipeline import FeatureUnion, Pipeline from pretab import Preprocessor -from pretab.compose.config import PreprocessorConfig +from pretab.compose.config import PreprocessorConfig, RepresentationConfig from pretab.compose.factory import ( _placement_kwargs, build_column_transformer, @@ -19,6 +20,7 @@ get_numerical_transformer_steps, ) from pretab.compose.registry import TransformerSpec, get_spec +from pretab.core.parameters import UNSET from pretab.exceptions import ConfigWarning, InvalidParamError @@ -365,3 +367,201 @@ def normalize_config(**parameters): assert preprocessor.get_params(deep=False) == requested assert preprocessor.get_resolved_config() == resolved assert feature_overrides == {"age": "rbf", "city": "int"} + + +@pytest.mark.parametrize("output_dim", [2, 3, 5]) +def test_resolved_representation_controls_width_and_family_options(make_config, output_dim): + config = make_config( + output_dim=11, + adaptive=True, + feature_preprocessing={"age": {"method": "rbf", "output_dim": output_dim, "gamma": 0.5}}, + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + transformer = block.named_steps["rbf"] + assert transformer.output_dim == output_dim + assert transformer.gamma == 0.5 + assert transformer.adaptive is False + assert block.fit_transform(np.linspace(0, 1, 16).reshape(-1, 1)).shape == (16, output_dim) + assert config.output_dim == 11 + assert config.adaptive is True + + +def test_resolved_representation_target_usage_overrides_run_wide_setting(make_config): + config = make_config( + feature_preprocessing={"age": {"method": "ple", "target_aware": True, "placement_strategy": "cart"}} + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("ple", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + assert block.named_steps["ple"].placement_strategy == "cart" + assert config.target_aware is False + + +def test_resolved_representation_method_must_match_selected_method(make_config): + with pytest.raises(InvalidParamError, match=r"create_transformer.representation.method.*rbf"): + create_transformer( + "standardization", + is_numerical=True, + config=make_config(), + representation=RepresentationConfig(method="rbf"), + ) + + +@pytest.mark.parametrize("method", ["bspline", "mspline", "ispline"]) +@pytest.mark.parametrize(("output_dim", "expected"), [(3, 5), (51, 50)]) +def test_resolved_representation_reuses_bmi_clamping(make_config, method, output_dim, expected): + config = make_config(feature_preprocessing={"age": {"method": method, "output_dim": output_dim}}) + resolved = config.representation_for("age", is_numerical=True) + with pytest.warns(ConfigWarning, match=f"output_dim={output_dim}.*using {expected}"): + block = create_transformer(method, is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + assert block.named_steps[method].output_dim == expected + assert resolved.output_dim == output_dim + + +@pytest.mark.parametrize(("method", "is_numerical"), [("cubic", True), ("b-spline", True), ("ohe", False)]) +def test_resolved_representation_accepts_matching_method_aliases(make_config, method, is_numerical): + config = make_config(feature_preprocessing={"feature": {"method": method}}) + resolved = config.representation_for("feature", is_numerical=is_numerical) + block = create_transformer(method, is_numerical=is_numerical, config=config, representation=resolved) + assert isinstance(block, Pipeline) + assert get_spec(resolved.method).transformer_cls in {type(step) for step in block.named_steps.values()} + + +@pytest.mark.parametrize( + ("random_state", "options", "expected"), + [(None, {}, UNSET), (17, {}, 17), (17, {"random_state": None}, None), (17, {"random_state": 0}, 0)], +) +def test_resolved_representation_preserves_omitted_and_explicit_seeds(make_config, random_state, options, expected): + config = make_config(random_state=random_state, feature_preprocessing={"age": {"method": "rbf", **options}}) + resolved = config.representation_for("age", is_numerical=True) + with patch( + "pretab.compose.factory.get_numerical_transformer_steps", wraps=get_numerical_transformer_steps + ) as steps: + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + if expected is UNSET: + assert "random_state" not in steps.call_args.kwargs + assert block.named_steps["rbf"].random_state == get_spec("rbf").transformer_cls().random_state + else: + assert steps.call_args.kwargs["random_state"] == expected + assert block.named_steps["rbf"].random_state == expected + + +def test_resolved_representation_keeps_explicit_adaptive_bounds(make_config): + config = make_config( + feature_preprocessing={ + "age": { + "method": "rbf", + "output_dim": 9, + "adaptive": True, + "min_output_dim": 3, + "max_output_dim": 12, + } + } + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + transformer = block.named_steps["rbf"] + assert (transformer.output_dim, transformer.adaptive, transformer.min_output_dim, transformer.max_output_dim) == ( + 9, + True, + 3, + 12, + ) + + +def test_resolved_representation_overrides_supervised_run_without_leaking_defaults(make_config): + config = make_config( + target_aware=True, + placement_strategy="cart", + feature_preprocessing={ + "age": { + "method": "rbf", + "target_aware": False, + "placement_strategy": "quantile", + "output_dim": 3, + } + }, + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + transformer = block.named_steps["rbf"] + assert transformer.target_aware is False + assert transformer.placement_strategy == "quantile" + assert block.fit_transform(np.linspace(0, 1, 16).reshape(-1, 1)).shape == (16, 3) + + +@pytest.mark.parametrize("is_numerical", [False, True]) +@pytest.mark.parametrize("missing_policy", [None, "impute", "impute_with_indicator", "separate_state"]) +def test_resolved_representation_preserves_missing_value_and_indicator_assembly( + make_config, is_numerical, missing_policy +): + method = "rbf" if is_numerical else "one-hot" + options = {"output_dim": 3} if is_numerical else {} + config = make_config( + missing_policy=missing_policy, feature_preprocessing={"feature": {"method": method, **options}} + ) + resolved = config.representation_for("feature", is_numerical=is_numerical) + block = create_transformer(method, is_numerical=is_numerical, config=config, representation=resolved) + data = ( + np.array([[0.0], [1.0], [np.nan], [2.0]]) + if is_numerical + else np.array([["a"], ["b"], [np.nan], ["a"]], dtype=object) + ) + result = block.fit_transform(data) + indicator = missing_policy in {"impute_with_indicator", "separate_state"} + assert result.shape == (4, (3 if is_numerical else 2) + int(indicator)) + assert isinstance(block, FeatureUnion if indicator else Pipeline) + representation = dict(block.transformer_list)["representation"] if isinstance(block, FeatureUnion) else block + assert isinstance(representation, Pipeline) + assert representation.named_steps["imputer"].strategy == ("median" if is_numerical else "most_frequent") + if indicator: + values = result.toarray() if issparse(result) else result + np.testing.assert_array_equal(values[:, -1], [0, 0, 1, 0]) + + +def test_resolved_representation_keeps_run_wide_scaling(make_config): + config = make_config(scaling="standardization", feature_preprocessing={"age": {"method": "rbf", "output_dim": 3}}) + block = create_transformer( + "rbf", is_numerical=True, config=config, representation=config.representation_for("age", is_numerical=True) + ) + assert isinstance(block, Pipeline) + assert _names(block.steps) == ["imputer", "scaler", "rbf"] + + +@pytest.mark.parametrize(("method", "is_numerical"), [("rbf", True), ("one-hot", False)]) +def test_explicit_none_representation_keeps_exact_legacy_calls(make_config, method, is_numerical): + config = make_config() + target = ( + "pretab.compose.factory.get_numerical_transformer_steps" + if is_numerical + else "pretab.compose.factory.get_categorical_transformer_steps" + ) + builder = get_numerical_transformer_steps if is_numerical else get_categorical_transformer_steps + with patch(target, wraps=builder) as steps: + create_transformer(method, is_numerical=is_numerical, config=config) + omitted = steps.call_args + create_transformer(method, is_numerical=is_numerical, config=config, representation=None) + assert steps.call_args == omitted + + +@pytest.mark.parametrize("value", [{"method": "rbf"}, "rbf", False]) +def test_factory_resolved_input_requires_a_typed_value(make_config, value): + with pytest.raises(InvalidParamError, match="must be a RepresentationConfig or None"): + create_transformer("rbf", is_numerical=True, config=make_config(), representation=value) + + +@pytest.mark.parametrize(("selected", "requested", "is_numerical"), [("int", "rbf", False), ("rff", "rff", True)]) +def test_factory_resolved_input_does_not_broaden_method_selection(make_config, selected, requested, is_numerical): + with pytest.raises(InvalidParamError): + create_transformer( + selected, + is_numerical=is_numerical, + config=make_config(), + representation=RepresentationConfig(method=requested), + ) diff --git a/tests/extension/test_registration_discovery.py b/tests/extension/test_registration_discovery.py index 0a3482a..272c3c7 100644 --- a/tests/extension/test_registration_discovery.py +++ b/tests/extension/test_registration_discovery.py @@ -5,6 +5,7 @@ """ import importlib.metadata as importlib_metadata +from dataclasses import fields import numpy as np import pandas as pd @@ -19,6 +20,8 @@ register_representation, ) from pretab.compose import registry +from pretab.compose.config import PreprocessorConfig +from pretab.compose.factory import create_transformer from pretab.exceptions import ConfigWarning @@ -201,6 +204,21 @@ def test_register_categorical_end_to_end_through_preprocessor(): assert pipeline.named_steps["cat_reg"].degree == 2 +def test_registered_categorical_factory_accepts_resolved_family_options(): + register_representation("cat_reg", _CatStringLength, allowed_args=("degree",)) + parameters = Preprocessor( + degree=2, + feature_preprocessing={"city": {"method": "cat_reg", "degree": 5}}, + ).get_resolved_config() + config = PreprocessorConfig.from_params(**{item.name: parameters[item.name] for item in fields(PreprocessorConfig)}) + resolved = config.representation_for("city", is_numerical=False) + block = create_transformer("cat_reg", is_numerical=False, config=config, representation=resolved) + result = block.fit_transform(np.array([["Rome"], ["Berlin"], ["Oslo"]], dtype=object)) + np.testing.assert_array_equal(result[:, 0], [20.0, 30.0, 20.0]) + assert resolved.params["degree"] == 5 + assert config.degree == 2 + + def test_duplicate_registration_requires_override(): register_representation("square_reg", _Square) with pytest.raises(ValueError, match="already registered"): From 13ba90afae7d480b71e741cfe739f4b9f2456c62 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 15:18:27 +0100 Subject: [PATCH 21/86] feat(preprocessor): support structured sklearn configuration --- pretab/compose/factory.py | 8 +- tests/compose/test_factory.py | 22 ++++ tests/integration/test_frozen_lifecycle.py | 27 ++++- tests/integration/test_preprocessor.py | 117 +++++++++++++++++++++ 4 files changed, 172 insertions(+), 2 deletions(-) diff --git a/pretab/compose/factory.py b/pretab/compose/factory.py index d3a3f99..6c77b2d 100644 --- a/pretab/compose/factory.py +++ b/pretab/compose/factory.py @@ -426,7 +426,13 @@ def build_column_transformer( for (kind, feature), name in zip(blocks, _step_names(blocks), strict=True): is_numerical = kind == "num" method = config.method_for(feature, is_numerical=is_numerical) - pipeline = create_transformer(method, is_numerical=is_numerical, config=config) + if isinstance(config.feature_preprocessing.get(feature, method), str): + pipeline = create_transformer(method, is_numerical=is_numerical, config=config) + else: + representation = config.representation_for(feature, is_numerical=is_numerical) + pipeline = create_transformer( + method, is_numerical=is_numerical, config=config, representation=representation + ) transformers.append((name, pipeline, [str(feature)])) return ColumnTransformer( transformers=transformers, diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index 6dcd137..2de21d8 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -198,6 +198,28 @@ def test_build_column_transformer_fits_and_transforms(make_config, sample_frame) assert out.shape[0] == len(sample_frame) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_preprocessor_fits_structured_representation(typed): + settings = {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}} + representation = RepresentationConfig.from_dict(settings) if typed else settings + frame = pd.DataFrame({"age": np.linspace(0, 1, 30)}) + processor = Preprocessor( + numerical_method="none", + feature_preprocessing={"age": representation}, + output_dim=9, + target_aware=False, + placement_strategy="quantile", + scaling="none", + ).fit(frame) + + basis = processor.column_transformer_.named_transformers_["num_age"].named_steps["rbf"] + assert basis.output_dim == 3 + assert basis.gamma == 0.5 + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (30, 3) + + @pytest.mark.parametrize("adaptive", [False, True]) @pytest.mark.parametrize("random_state", [None, 17]) @pytest.mark.parametrize( diff --git a/tests/integration/test_frozen_lifecycle.py b/tests/integration/test_frozen_lifecycle.py index 308f2af..356989e 100644 --- a/tests/integration/test_frozen_lifecycle.py +++ b/tests/integration/test_frozen_lifecycle.py @@ -12,7 +12,7 @@ from sklearn import config_context from sklearn.pipeline import Pipeline -from pretab import FrozenRepresentationError, Preprocessor +from pretab import FrozenRepresentationError, Preprocessor, RepresentationConfig @pytest.fixture @@ -58,6 +58,31 @@ def test_set_params_allowed_before_freeze(frame, target): assert p.output_dim == 9 +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("via_pipeline", [False, True], ids=["direct", "pipeline"]) +def test_frozen_structured_feature_settings_cannot_be_replaced(frame, target, typed, via_pipeline): + settings = {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}} + overrides = {"a": RepresentationConfig.from_dict(settings) if typed else settings} + processor = _make().set_params(feature_preprocessing=overrides).fit(frame, target).freeze() + fingerprint = processor.fingerprint_ + original = processor.transform(frame, return_array=True) + replacement = {"a": RepresentationConfig(method="rbf", output_dim=5)} + caller = Pipeline([("pre", processor)]) if via_pipeline else processor + parameters = {"pre__feature_preprocessing" if via_pipeline else "feature_preprocessing": replacement} + + with pytest.raises(FrozenRepresentationError, match="frozen"): + caller.set_params(**parameters) + + assert processor.get_params()["feature_preprocessing"] is overrides + assert processor.fingerprint_ == fingerprint + assert processor.set_params() is processor + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + fresh = processor.clone_unfitted() + assert fresh.is_frozen() is False + assert fresh.set_params(feature_preprocessing=replacement) is fresh + assert fresh.get_params()["feature_preprocessing"] is replacement + + @pytest.mark.parametrize("method", ["fit", "fit_transform"]) def test_frozen_fit_rejected_without_mutating_state(frame, target, method): p = _make().fit(frame, target).freeze() diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index c28c73b..59f27ce 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -6,9 +6,12 @@ from sklearn.base import clone from sklearn.exceptions import NotFittedError from sklearn.impute import SimpleImputer +from sklearn.linear_model import Ridge +from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.utils.validation import check_is_fitted +from pretab import RepresentationConfig from pretab.exceptions import IncompatibleParamsError, InvalidParamError, PretabDataError from pretab.preprocessor import Preprocessor # Adjust the import as needed @@ -226,6 +229,120 @@ def test_clone_preserves_every_param(): assert cloned.get_params() == pre.get_params() +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("fitted", [False, True], ids=["unfitted", "fitted"]) +def test_structured_feature_params_survive_fit_and_clone(sample_data, typed, fitted): + frame, target = sample_data + frame = frame[["num1"]] + settings = {"method": "RBF", "output_dim": 3, "params": {"gamma": 0.5}} + representation = RepresentationConfig.from_dict(settings) if typed else settings + overrides = {"num1": representation} + processor = Preprocessor( + numerical_method="none", + feature_preprocessing=overrides, + output_dim=9, + target_aware=False, + placement_strategy="quantile", + scaling="none", + ) + if fitted: + processor.fit(frame, target) + for deep in (False, True): + assert processor.get_params(deep=deep)["feature_preprocessing"] is overrides + assert overrides["num1"] is representation + + fresh = clone(processor) + assert isinstance(fresh, Preprocessor) + assert fresh.get_params() == processor.get_params() + assert isinstance(fresh.feature_preprocessing, dict) + assert fresh.feature_preprocessing is not overrides + assert fresh.feature_preprocessing["num1"] == representation + assert fresh.lifecycle_state_ == "UNFITTED" + if not typed: + assert fresh.feature_preprocessing["num1"] is not representation + settings["params"]["gamma"] = 2.0 + assert fresh.feature_preprocessing["num1"]["params"]["gamma"] == 0.5 + + fresh.fit(frame, target) + basis = fresh.column_transformer_.named_transformers_["num_num1"].named_steps["rbf"] + assert basis.gamma == 0.5 + transformed = fresh.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (len(frame), 3) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("fitted", [False, True], ids=["unfitted", "fitted"]) +def test_pipeline_set_params_replaces_structured_feature_settings(sample_data, typed, fitted): + frame, target = sample_data + frame = frame[["num1"]] + processor = Preprocessor(numerical_method="none", target_aware=False, placement_strategy="quantile", scaling="none") + pipeline = Pipeline([("pre", processor)]) + if fitted: + pipeline.fit(frame, target) + settings = {"method": "rbf", "output_dim": 5, "params": {"gamma": 0.75}} + overrides = {"num1": RepresentationConfig.from_dict(settings) if typed else settings} + + assert pipeline.set_params(pre__feature_preprocessing=overrides) is pipeline + assert processor.get_params()["feature_preprocessing"] is overrides + if fitted: + assert pipeline.transform(frame).shape == (len(frame), 1) + + pipeline.fit(frame, target) + basis = processor.column_transformer_.named_transformers_["num_num1"].named_steps["rbf"] + assert basis.gamma == 0.75 + assert pipeline.transform(frame).shape == (len(frame), 5) + assert processor.get_params()["feature_preprocessing"] is overrides + + +@pytest.mark.parametrize("n_jobs", [1, 2], ids=["serial", "processes"]) +def test_grid_search_consumes_structured_feature_settings(sample_data, n_jobs): + frame, target = sample_data + frame = frame[["num1"]] + candidates = [ + {"num1": {"method": "RBF", "output_dim": 2, "params": {"gamma": 0.25}}}, + {"num1": RepresentationConfig(method="rbf", output_dim=5, params={"gamma": 0.75})}, + ] + processor = Preprocessor( + numerical_method="none", output_dim=9, target_aware=False, placement_strategy="quantile", scaling="none" + ) + + def fitted_width(estimator, frame, target): + fitted = estimator.named_steps["pre"] + requested = fitted.feature_preprocessing["num1"] + settings = requested.to_dict() if isinstance(requested, RepresentationConfig) else requested + basis = fitted.column_transformer_.named_transformers_["num_num1"].named_steps["rbf"] + transformed = fitted.transform(frame, return_array=True) + assert transformed.shape[1] == settings["output_dim"] + assert basis.gamma == settings["params"]["gamma"] + assert estimator.named_steps["model"].n_features_in_ == settings["output_dim"] + assert np.isfinite(estimator.predict(frame)).all() + return float(transformed.shape[1]) + + search = GridSearchCV( + Pipeline([("pre", processor), ("model", Ridge())]), + {"pre__feature_preprocessing": candidates}, + scoring=fitted_width, + cv=2, + n_jobs=n_jobs, + ) + search.set_params(error_score="raise") + search.fit(frame, target) + + np.testing.assert_array_equal(search.cv_results_["mean_test_score"], [2.0, 5.0]) + assert search.best_params_["pre__feature_preprocessing"] == candidates[1] + assert search.best_estimator_.named_steps["pre"].transform(frame, return_array=True).shape == (len(frame), 5) + assert processor.lifecycle_state_ == "UNFITTED" + assert processor.feature_preprocessing is None + assert candidates[0]["num1"] == {"method": "RBF", "output_dim": 2, "params": {"gamma": 0.25}} + assert candidates[1]["num1"].to_dict() == { + "method": "rbf", + "output_dim": 5, + "params": {"gamma": 0.75}, + "name": None, + } + + def test_set_params_roundtrip(): pre = Preprocessor() pre.set_params(output_dim=11, numerical_method="rbf") From 88c2ccf9622de8aa87d4f52bfc6aa3f1b4c3c3e4 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 18:59:15 +0100 Subject: [PATCH 22/86] feat(config): report effective per-feature settings --- pretab/compose/config.py | 13 ++- pretab/preprocessor.py | 25 ++++- tests/compose/test_factory.py | 4 +- tests/integration/test_presets.py | 177 +++++++++++++++++++++++++++++- 4 files changed, 209 insertions(+), 10 deletions(-) diff --git a/pretab/compose/config.py b/pretab/compose/config.py index 49b3f9b..7b3dd82 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -462,16 +462,25 @@ def method_for(self, feature, *, is_numerical: bool) -> str: ).method return self.resolve_numerical(raw) if is_numerical else self.resolve_categorical(raw) - def representation_for(self, feature, *, is_numerical: bool) -> RepresentationConfig: + def representation_for(self, feature, *, is_numerical: bool | None = None) -> RepresentationConfig: """Resolve one feature request over applicable constructor-wide controls. Method defaults remain omitted when the existing factory would not forward a constructor-wide value. Inherited inactive adaptive bounds are dropped, but contradictory explicit local bounds are rejected. + Without a detected kind, resolve the declared method's namespace only; + compatibility with the actual input still belongs to fitting. """ - default = self.numerical_method if is_numerical else self.categorical_method + default = self.categorical_method if is_numerical is False else self.numerical_method raw = self.feature_preprocessing.get(feature, default) path = f"feature_preprocessing[{feature!r}]" + if is_numerical is None: + token = _REPRESENTATION_PATH.set(path) + try: + method = _representation_request(raw).method + finally: + _REPRESENTATION_PATH.reset(token) + is_numerical = self.resolve_categorical(method) not in CATEGORICAL_METHODS requested = _normalize_representation_config(raw, is_numerical=is_numerical, path=path) spec = TRANSFORMER_REGISTRY[requested.method] inherited = {} diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 8defcee..655a8aa 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -5,6 +5,7 @@ import os import time import warnings +from dataclasses import fields from typing import cast import numpy as np @@ -893,10 +894,14 @@ def get_resolved_config(self): When ``preset`` is set, its bundled values fill in every parameter the caller left at its default while explicitly-set parameters win; the - ``preset`` key itself is removed. When ``preset`` is ``None`` this is simply - :meth:`get_params` without the ``preset`` entry. The returned dict is the - configuration ``fit`` builds from, so it makes a preset's effect inspectable - before fitting. + ``preset`` key itself is removed. Declared ``feature_preprocessing`` + entries become ordinary mappings with canonical methods and applicable + inherited settings, using the same resolver as fitting. Other global + keys retain their preset-expanded values. + + The result is detached from caller-owned containers and resolves current + parameters before or after fit. It does not describe the last fitted + graph, infer an input schema, or guarantee realized output widths. Returns ------- @@ -906,9 +911,17 @@ def get_resolved_config(self): Raises ------ InvalidParamError - If ``task`` or ``preset`` is invalid, exactly as ``fit`` would raise. + If ``task``, ``preset``, or a declared representation is invalid. """ - return self._resolved_params() + resolved = self._resolved_params() + if resolved["feature_preprocessing"]: + config = PreprocessorConfig.from_params( + **{field.name: resolved[field.name] for field in fields(PreprocessorConfig)} + ) + resolved["feature_preprocessing"] = { + feature: config.representation_for(feature).to_dict() for feature in config.feature_preprocessing + } + return copy.deepcopy(resolved) def get_feature_names_out(self, input_features=None): """ diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index 2de21d8..a379d8f 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -321,6 +321,8 @@ def test_preprocessor_routes_one_normalized_config_through_the_factory(sample_fr } assert set(resolved) == config_fields | facade_fields assert config_fields.isdisjoint(facade_fields) + fit_parameters = {name: resolved[name] for name in config_fields} + fit_parameters["feature_preprocessing"] = feature_overrides normalized_configs: list[PreprocessorConfig] = [] from_params = PreprocessorConfig.from_params @@ -351,7 +353,7 @@ def normalize_config(**parameters): preprocessor.fit(sample_frame, np.array([0, 1, 0, 1, 0, 1])) - normalize.assert_called_once_with(**{name: resolved[name] for name in config_fields}) + normalize.assert_called_once_with(**fit_parameters) (config,) = normalized_configs assert all(item.kwargs["config"] is config for item in create.call_args_list) assert all(item.args[0] is config for item in method_for.call_args_list + imputation_plan.call_args_list) diff --git a/tests/integration/test_presets.py b/tests/integration/test_presets.py index 646d3d8..3cf6648 100644 --- a/tests/integration/test_presets.py +++ b/tests/integration/test_presets.py @@ -1,11 +1,14 @@ """Tests for the ``Preprocessor`` preset aliases and ``get_resolved_config`` (P10.5).""" +from dataclasses import replace + import numpy as np import pandas as pd import pytest from sklearn.base import clone -from pretab import Preprocessor +from pretab import Preprocessor, RepresentationConfig +from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.exceptions import InvalidParamError @@ -29,6 +32,178 @@ def test_no_preset_resolved_config_drops_preset_key(): assert cfg["categorical_method"] == "int" +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +def test_resolved_config_reports_effective_feature_settings(form): + requested = {"string": "RBF", "mapping": {"method": "RBF"}, "value": RepresentationConfig(method="RBF")}[form] + overrides = {"age": requested} + processor = Preprocessor( + preset="expanded", + feature_preprocessing=overrides, + target_aware=False, + placement_strategy="quantile", + random_state=17, + ) + + report = processor.get_resolved_config() + feature = report["feature_preprocessing"]["age"] + assert feature["method"] == "rbf" + assert feature["output_dim"] == 10 + assert feature["target_aware"] is False + assert feature["placement_strategy"] == "quantile" + assert feature["adaptive"] is False + assert feature["params"] == {"task": "regression", "random_state": 17} + assert processor.get_params()["feature_preprocessing"] is overrides + assert overrides["age"] is requested + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize(("method", "canonical"), [("OHE", "one-hot"), ("identity", "none")]) +def test_resolved_config_reports_categorical_declarations_without_numerical_controls(form, method, canonical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + processor = Preprocessor(preset="adaptive", feature_preprocessing={"city": requested}, degree=2) + + report = processor.get_resolved_config() + + assert set(report) == set(processor.get_params()) - {"preset"} + assert report["feature_preprocessing"] == {"city": {"method": canonical, "params": {}, "name": None}} + assert report["adaptive"] is True + assert report["degree"] == 2 + + +@pytest.mark.parametrize("adaptive", [False, True]) +def test_resolved_config_preserves_local_precedence_and_meaningful_none(adaptive): + settings = {"method": "RBF", "output_dim": 3, "params": {"gamma": 0.5, "random_state": None}, "name": "local"} + if adaptive: + settings.update(adaptive=True, min_output_dim=None, max_output_dim=6) + report = Preprocessor( + preset="adaptive", + feature_preprocessing={"age": settings}, + target_aware=False, + placement_strategy="quantile", + random_state=17, + ).get_resolved_config() + feature = report["feature_preprocessing"]["age"] + + assert feature["method"] == "rbf" + assert feature["output_dim"] == 3 + assert feature["adaptive"] is adaptive + assert feature["name"] == "local" + assert feature["params"] == {"gamma": 0.5, "task": "regression", "random_state": None} + if adaptive: + assert feature["min_output_dim"] is None + assert feature["max_output_dim"] == 6 + else: + assert "min_output_dim" not in feature + assert "max_output_dim" not in feature + assert report["adaptive"] is True + assert report["random_state"] == 17 + + +@pytest.mark.parametrize("overrides", [None, {}]) +def test_resolved_config_without_declarations_keeps_shape_and_detaches_globals(overrides): + policy = {"constant": "allow"} + processor = Preprocessor(feature_preprocessing=overrides, policy=policy) + report = processor.get_resolved_config() + + assert set(report) == set(processor.get_params()) - {"preset"} + assert report["feature_preprocessing"] == overrides + assert report["policy"] == policy + assert report["policy"] is not policy + report["policy"]["constant"] = "raise" + assert policy == {"constant": "allow"} + assert processor.get_resolved_config()["policy"] == policy + + +def test_resolved_config_detaches_nested_params_and_observes_later_raw_edits(monkeypatch): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) + nested = {"weights": [1, {"weight": 0.5}]} + overrides = {"age": {"method": "rbf", "params": {"options": nested}}} + processor = Preprocessor(feature_preprocessing=overrides, target_aware=False, placement_strategy="quantile") + nested["weights"].append(2) + first = processor.get_resolved_config() + returned = first["feature_preprocessing"]["age"]["params"]["options"] + assert returned == {"weights": [1, {"weight": 0.5}, 2]} + nested["weights"].append(3) + returned["weights"][1]["weight"] = 9.0 + returned["weights"].append(4) + first["feature_preprocessing"]["age"]["method"] = "none" + + assert nested == {"weights": [1, {"weight": 0.5}, 2, 3]} + second = processor.get_resolved_config() + assert second["feature_preprocessing"]["age"]["method"] == "rbf" + assert second["feature_preprocessing"]["age"]["params"]["options"] == nested + assert processor.get_params()["feature_preprocessing"] is overrides + + +@pytest.mark.parametrize("frozen", [False, True]) +def test_resolved_config_stays_live_without_refitting_or_reading_fitted_outputs(data, monkeypatch, frozen): + frame, target = data + overrides = {"a": {"method": "rbf", "output_dim": 3}} + processor = Preprocessor( + numerical_method="none", + feature_preprocessing=overrides, + target_aware=False, + placement_strategy="quantile", + scaling="none", + ).fit(frame, target) + if frozen: + processor.freeze() + original = processor.transform(frame, return_array=True) + original_names = processor.get_feature_names_out() + first = processor.get_resolved_config() + overrides["a"]["output_dim"] = 5 + fingerprint = processor.fingerprint_ + + def reject_execution(*args, **kwargs): + raise AssertionError("Configuration reporting must not execute a fitted graph") + + with monkeypatch.context() as patcher: + patcher.setattr(type(processor), "fit", reject_execution) + patcher.setattr(type(processor), "transform", reject_execution) + report = processor.get_resolved_config() + + assert first["feature_preprocessing"]["a"]["output_dim"] == 3 + assert report["feature_preprocessing"]["a"]["output_dim"] == 5 + assert set(report["feature_preprocessing"]) == {"a"} + assert processor.column_transformer_.named_transformers_["num_a"].named_steps["rbf"].output_dim == 3 + assert processor.fingerprint_ == fingerprint + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + np.testing.assert_array_equal(processor.get_feature_names_out(), original_names) + overrides["a"]["unexpected"] = True + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['a'\]\.params\['unexpected'\]"): + processor.get_resolved_config() + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + + +@pytest.mark.parametrize( + ("settings", "location"), + [ + ({"method": "unknown"}, "method"), + ({"method": "rff"}, "method"), + ({"method": "rbf", "outpuut_dim": 3}, "outpuut_dim"), + ({"method": "one-hot", "degree": 2}, "degree"), + ({"method": "rbf", "target_aware": True, "placement_strategy": "uniform"}, "placement_strategy"), + ], +) +def test_resolved_config_representation_errors_keep_feature_paths(settings, location): + processor = Preprocessor(feature_preprocessing={"declared": settings}) + with pytest.raises(InvalidParamError) as failure: + processor.get_resolved_config() + assert "feature_preprocessing['declared']" in str(failure.value) + assert location in str(failure.value) + + +@pytest.mark.parametrize("feature", ["a", "not_in_input"]) +def test_resolved_config_does_not_infer_input_schema_or_feature_kind(data, feature): + frame, target = data + processor = Preprocessor(feature_preprocessing={feature: {"method": "OHE"}}) + report = processor.get_resolved_config() + assert report["feature_preprocessing"] == {feature: {"method": "one-hot", "params": {}, "name": None}} + with pytest.raises(InvalidParamError, match="feature_preprocessing"): + processor.fit(frame, target) + + def test_standard_preset_matches_baseline(): # Preprocessor()'s default task is "regression", so the preset resolves # numerical_method to "bspline" (see test_preset_numerical_method_follows_task). From 8b890a741dab34b3646b88e5e5bd5edda57e05ce Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 14 Nov 2026 22:41:49 +0100 Subject: [PATCH 23/86] test(config): consolidate representation compatibility contracts --- tests/compose/test_config.py | 72 +++++++++++++++++++++++++ tests/integration/test_fingerprint.py | 77 +++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index 956bf3c..5da15b2 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -1,8 +1,13 @@ """Unit tests for :class:`pretab.compose.config.PreprocessorConfig`.""" +import json from dataclasses import asdict, replace +from typing import Any +import numpy as np +import pandas as pd import pytest +from sklearn.base import clone from pretab import Preprocessor, RepresentationConfig from pretab.compose.registry import TRANSFORMER_REGISTRY @@ -279,6 +284,73 @@ def test_representation_resolution_forms_are_equivalent(make_config, form, metho assert config.method_for("feature", is_numerical=is_numerical) == expected.method +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize(("method", "is_numerical"), [("RBF", True), ("OHE", False)]) +def test_representation_forms_agree_through_clone_json_report_and_fit(form, method, is_numerical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + overrides = {"feature": requested} + settings: dict[str, Any] = { + "output_dim": 7, + "target_aware": False, + "placement_strategy": "uniform", + "scaling": "none", + "random_state": 17, + } + values = np.linspace(0, 1, 40) if is_numerical else ["a", "b"] * 20 + frame = pd.DataFrame({"feature": values}) + processor = Preprocessor(feature_preprocessing=overrides, **settings) + fresh = clone(processor) + assert isinstance(fresh, Preprocessor) + assert fresh.get_params() == processor.get_params() + assert processor.get_params()["feature_preprocessing"] is overrides + assert overrides["feature"] is requested + + report = fresh.get_resolved_config() + restored_report = json.loads(json.dumps(report, allow_nan=False)) + assert restored_report == report + resolved = RepresentationConfig.from_dict(restored_report["feature_preprocessing"]["feature"]) + assert resolved.to_dict() == report["feature_preprocessing"]["feature"] + + actual = np.asarray(fresh.fit_transform(frame, return_array=True)) + reference = Preprocessor(feature_preprocessing={"feature": method}, **settings).fit(frame) + expected = np.asarray(reference.transform(frame, return_array=True)) + assert actual.dtype == expected.dtype + assert actual.shape == expected.shape + assert actual.tobytes() == expected.tobytes() + np.testing.assert_array_equal(fresh.get_feature_names_out(), reference.get_feature_names_out()) + assert fresh.output_dims_ == reference.output_dims_ + assert fresh.total_output_dim_ == reference.total_output_dim_ + + +@pytest.mark.parametrize("typed", [False, True], ids=["raw", "typed"]) +def test_fit_boundary_detaches_params_without_changing_requested_identity(typed): + params = {"gamma": 0.5} + settings = {"method": "rbf", "output_dim": 3, "params": params} + requested = RepresentationConfig.from_dict(settings) if typed else settings + overrides = {"age": requested} + processor = Preprocessor( + feature_preprocessing=overrides, target_aware=False, placement_strategy="uniform", scaling="none" + ) + params["gamma"] = 0.75 + expected_gamma = 0.5 if typed else 0.75 + frame = pd.DataFrame({"age": np.linspace(0, 1, 40)}) + processor.fit(frame) + original = np.asarray(processor.transform(frame, return_array=True)) + basis = processor.column_transformer_.named_transformers_["num_age"].named_steps["rbf"] + assert basis.gamma == expected_gamma + + report = processor.get_resolved_config() + report["feature_preprocessing"]["age"]["params"]["gamma"] = 9.0 + params["gamma"] = 1.25 + + assert processor.get_params()["feature_preprocessing"] is overrides + assert overrides["age"] is requested + assert basis.gamma == expected_gamma + assert np.asarray(processor.transform(frame, return_array=True)).tobytes() == original.tobytes() + live = processor.get_resolved_config()["feature_preprocessing"]["age"] + assert live["params"]["gamma"] == (0.5 if typed else 1.25) + + def test_normalized_feature_requests_snapshot_nested_values_at_the_boundary(make_config, monkeypatch): spec = TRANSFORMER_REGISTRY["rbf"] monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) diff --git a/tests/integration/test_fingerprint.py b/tests/integration/test_fingerprint.py index 597ad0d..b0598dd 100644 --- a/tests/integration/test_fingerprint.py +++ b/tests/integration/test_fingerprint.py @@ -8,12 +8,22 @@ import subprocess import sys import textwrap +from contextlib import nullcontext +from typing import Any import numpy as np import pandas as pd import pytest +from sklearn.base import clone from pretab import Preprocessor +from pretab.compose.registry import ( + CATEGORICAL_ALIASES, + CATEGORICAL_METHODS, + NUMERICAL_ALIASES, + NUMERICAL_METHODS, + TRANSFORMER_REGISTRY, +) @pytest.fixture @@ -45,6 +55,73 @@ def test_fingerprint_deterministic_same_fit(frame, target): assert _fit(frame, target).fingerprint_ == _fit(frame, target).fingerprint_ +@pytest.mark.parametrize("per_feature", [False, True], ids=["global", "override"]) +@pytest.mark.parametrize( + ("feature", "method", "canonical"), + [ + pytest.param(feature, method, canonical, id=f"{feature}-{method}") + for feature, methods, aliases in ( + ("a", NUMERICAL_METHODS, NUMERICAL_ALIASES), + ("c", CATEGORICAL_METHODS, CATEGORICAL_ALIASES), + ) + for method, canonical in [ + *((name, name) for name in sorted(methods)), + *((alias, name) for alias, name in sorted(aliases.items()) if name in methods), + ] + if TRANSFORMER_REGISTRY[canonical].optional_dependency is None + ], +) +def test_legacy_strings_keep_fitted_artifact_through_report_and_clone( + frame, target, feature, method, canonical, per_feature +): + frame = pd.concat([frame.assign(c=pd.Categorical(frame["c"]).codes)] * 20, ignore_index=True) + target = np.tile(target, 20) + supervised = TRANSFORMER_REGISTRY[canonical].requires_target + parameters: dict[str, Any] = { + "numerical_method": "none", + "categorical_method": "none", + "target_aware": supervised, + "placement_strategy": "cart" if supervised else "uniform", + "random_state": 17, + "scaling": "none", + } + if per_feature: + parameters["feature_preprocessing"] = {feature: method} + else: + parameters["numerical_method" if feature == "a" else "categorical_method"] = method + with ( + pytest.warns(DeprecationWarning, match="OneHotFromOrdinalTransformer is deprecated") + if canonical == "onehot_from_ordinal" + else nullcontext() + ): + processor = Preprocessor(**parameters).fit(frame, target) + original = np.asarray(processor.transform(frame, return_array=True)) + names = processor.get_feature_names_out() + widths = dict(processor.output_dims_) + fingerprint = processor.fingerprint_ + requested = processor.get_params() + + processor.get_resolved_config() + fresh = clone(processor) + assert isinstance(fresh, Preprocessor) + with ( + pytest.warns(DeprecationWarning, match="OneHotFromOrdinalTransformer is deprecated") + if canonical == "onehot_from_ordinal" + else nullcontext() + ): + fresh.fit(frame, target) + for candidate in (processor, fresh): + actual = np.asarray(candidate.transform(frame, return_array=True)) + assert actual.dtype == original.dtype + assert actual.shape == original.shape + assert actual.tobytes() == original.tobytes() + np.testing.assert_array_equal(candidate.get_feature_names_out(), names) + assert candidate.output_dims_ == widths + assert candidate.total_output_dim_ == original.shape[1] + assert candidate.fingerprint_ == fingerprint + assert candidate.get_params() == requested + + def test_fingerprint_survives_round_trip(frame, target): p = _fit(frame, target) restored = Preprocessor.from_spec(p.to_spec()) From 1d314c562ef231c64d05e0d5ecdc9a5f91bc628b Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 00:16:42 +0100 Subject: [PATCH 24/86] docs(config): explain structured representation configuration --- docs/api/preprocessor.rst | 83 +++++++++ docs/core_concepts/configuration.md | 175 +++++++++++++++++-- pretab/preprocessor.py | 13 +- tests/doc_snippets/test_tutorial_snippets.py | 29 ++- 4 files changed, 280 insertions(+), 20 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 934b92c..a3361e7 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -19,6 +19,8 @@ Representation values :class:`~pretab.RepresentationConfig` stores a representation request with read-only, detached parameters and JSON-compatible dictionary conversion. Constructing the value does not fit an estimator or resolve method aliases. +Pass it as a value in ``Preprocessor(feature_preprocessing={...})``; strings +and mappings with a ``method`` key are accepted there as well. .. autosummary:: :toctree: _autosummary @@ -26,6 +28,87 @@ Constructing the value does not fit an estimator or resolve method aliases. RepresentationConfig +Fields and conversion +~~~~~~~~~~~~~~~~~~~~~ + +``method`` + Required method name or alias. Validation against the selected method + happens during configuration resolution or fitting. + +``output_dim`` + Positive requested width, subject to the representation's constraints. + An explicit local width suppresses inherited adaptive sizing unless + local ``adaptive=True`` also opts in. + +``target_aware``, ``placement_strategy`` + Local target-use and placement controls, where the method supports them. + +``adaptive``, ``min_output_dim``, ``max_output_dim`` + Local adaptive sizing and bounds. Bounds must be positive integers or + ``None`` where accepted. Explicit bounds with fixed sizing are invalid. + +``params`` + Family-specific constructor options, such as ``{"gamma": 0.5}`` for + RBF. Common fields belong at the top level, not in this mapping. + +``name`` + Optional nonempty metadata label, default ``None``. It does not rename + input columns or fitted output features. + +Omitted common controls retain ``UNSET`` until resolution. An explicit local +value takes precedence over an applicable constructor-wide value; ``None`` +is an explicit value only for fields that accept it, not an inheritance marker. +Imputation, scaling, missing indicators, and output formatting remain run-wide. + +Nested ``params`` values may contain strings, booleans, integers, finite floats, +``None``, sequences, and mappings with string keys. Construction copies them +into read-only storage. Callables, arbitrary objects, sets, nonfinite floats, +and circular references are rejected. + +``to_dict()`` returns detached dict/list containers, omits ``UNSET`` fields, +and retains explicit ``None`` values. It preserves the requested method +spelling; it does not resolve an alias. The result can be passed through +``json.dumps`` / ``json.loads`` and reconstructed with ``from_dict()``. +``from_dict()`` also accepts family parameters beside ``method`` and collects +them under ``params``. Supplying the same option in both places is an error, +even when the values agree. + +.. note:: + + This is a value object, not a scikit-learn estimator. It has no fitted state + or ``set_params`` method. Replace an entry through the containing + preprocessor's ``set_params(feature_preprocessing=...)``, or through + ``pre__feature_preprocessing`` when its pipeline step is named ``pre``. + The replacement is used by the next fit; it does not refit automatically. + Frozen preprocessors reject configuration replacement. + +Requested and resolved settings +------------------------------- + +``get_params()`` preserves the raw constructor arguments, including caller-owned +override mappings. Raw mapping edits before fit remain observable. Typed values +detach on construction; raw representation settings detach during normalization +and fitting. + +:meth:`~pretab.Preprocessor.get_resolved_config` returns a detached current-request +dict, retaining the existing outer keys and expanding presets. Declared overrides +become canonical method mappings with applicable inherited controls and family +parameters. It does not enumerate undeclared columns, validate actual column +existence or detected kind before fit, or report learned widths or knot state. +Reading it never fits or transforms data. After fit or freeze it still describes +the current request, not the last successful fit. Use ``output_dims_``, +``total_output_dim_``, and :meth:`~pretab.Preprocessor.get_feature_info` for fitted +results. + +Value construction validates field types and portable data. Resolution additionally +validates method names, option applicability, and target/placement combinations; +invalid feature declarations report their configuration path. Actual input checks +belong to fitting. + +See the :doc:`configuration guide <../core_concepts/configuration>` for the +precedence table and three executable examples. Supported legacy string +configuration needs no syntax change, and can be mixed with structured entries. + Configuration, output, and reproducibility ------------------------------------------ diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index 5261fdb..2cc13c3 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -93,6 +93,8 @@ pipe.fit_transform(X, y) # a polars.DataFrame with columns num_age, num_income Columns rarely want identical treatment. The `feature_preprocessing` dict assigns a strategy to individual columns and takes precedence over the global defaults for those columns. +Each value can be a method string, a mapping with a `method` key, or a +{class}`~pretab.RepresentationConfig`. You can mix these forms in the same dict. ```python pre = Preprocessor( @@ -142,6 +144,124 @@ Don't infer the resolved method per column from the constructor arguments alone. [Fit-time logging](outputs_and_inspection.md#fit-time-logging). ``` +## Structured per-feature configuration + +These three examples use the same training data and a scikit-learn regression pipeline. +`income` is deliberately left out of each override map, so it uses the global `"none"` +method and contributes one column. + +```python +import json + +import numpy as np +import pandas as pd +from sklearn.base import clone +from sklearn.linear_model import Ridge +from sklearn.pipeline import Pipeline + +from pretab import Preprocessor, RepresentationConfig + +frame = pd.DataFrame({ + "age": np.linspace(18.0, 70.0, 40), + "income": np.linspace(25000.0, 90000.0, 40), + "city": ["Oslo", "Lima"] * 20, +}) +target = 0.4 * frame["age"] + 0.0002 * frame["income"] +common = { + "numerical_method": "none", + "output_dim": 7, + "target_aware": False, + "placement_strategy": "uniform", + "scaling": "none", + "random_state": 17, +} +``` + +### Method strings + +Strings select the representation and retain the applicable constructor-wide controls. +Here `"RBF"` is an alias for `"rbf"`, and `"OHE"` selects one-hot encoding. + +```python +legacy = Preprocessor( + **common, + feature_preprocessing={"age": "RBF", "city": "OHE"}, +) +legacy_model = Pipeline([("pre", legacy), ("model", Ridge())]).fit(frame, target) + +assert legacy.output_dims_ == {"age": 7, "income": 1, "city": 2} +assert legacy.transform(frame, return_array=True).shape == (40, 10) +assert legacy_model.predict(frame).shape == (40,) +``` + +### Mappings with local settings + +A mapping adds controls for that feature. `age` requests three RBF outputs and a local +`gamma`; it does not change `income` or the two learned city categories. + +```python +mapped = Preprocessor( + **common, + feature_preprocessing={ + "age": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}}, + "city": "one-hot", + }, +) +mapped_model = Pipeline([("pre", mapped), ("model", Ridge())]).fit(frame, target) +report = mapped.get_resolved_config() + +assert report["output_dim"] == 7 +assert report["feature_preprocessing"]["age"]["output_dim"] == 3 +assert report["feature_preprocessing"]["age"]["params"]["gamma"] == 0.5 +assert mapped.output_dims_ == {"age": 3, "income": 1, "city": 2} +assert mapped.transform(frame, return_array=True).shape == (40, 6) +assert mapped_model.predict(frame).shape == (40,) +``` + +Family parameters can also appear beside `method`, for example +`{"method": "rbf", "gamma": 0.5}`. Normalization collects them under `params`. +Do not supply the same parameter in both places. Common controls such as `output_dim` +belong at the top level, not inside `params`. + +### Immutable values and JSON + +`RepresentationConfig` detaches its nested inputs immediately. Its dictionary form can be +stored as JSON, reconstructed, and used with `clone` and `Pipeline`. + +```python +params = {"gamma": 0.5} +value = RepresentationConfig(method="RBF", output_dim=3, params=params) +params["gamma"] = 9.0 +assert value.params["gamma"] == 0.5 + +payload = json.loads(json.dumps(value.to_dict(), allow_nan=False)) +restored = RepresentationConfig.from_dict(payload) +assert restored == value + +typed = Preprocessor( + **common, + feature_preprocessing={"age": restored, "city": {"method": "OHE"}}, +) +fresh = clone(typed) +assert fresh.get_params() == typed.get_params() +typed_model = Pipeline([("pre", fresh), ("model", Ridge())]).fit(frame, target) + +assert fresh.output_dims_ == {"age": 3, "income": 1, "city": 2} +np.testing.assert_array_equal( + fresh.transform(frame, return_array=True), + mapped.transform(frame, return_array=True), +) +assert typed_model.predict(frame).shape == (40,) +``` + +```{important} +Raw mappings passed to `Preprocessor` remain live constructor parameters, as required by +scikit-learn. Edits before fitting affect that fit. Normalization and fitting detach the +representation settings; editing a raw mapping afterward does not refit the learned +transformers. Use `RepresentationConfig` when the request itself should be immutable from +construction onward. Neither form changes an already fitted graph without another fit. +``` + ## Presets Presets are transparent, named bundles of parameters for common intents. They set the same @@ -199,17 +319,27 @@ the preset's value for that knob, including `numerical_method` itself, for examp ## Reading the resolved configuration -Because global defaults, per-feature overrides, and presets interact, PreTab lets you read -back exactly what will be used. `get_resolved_config()` returns the fully resolved settings -as a plain dict. +`get_resolved_config()` returns a detached plain dict for the current request. Outer keys +retain the preset-expanded constructor settings. Each declared `feature_preprocessing` +entry becomes a mapping with its canonical method, applicable inherited controls, local +settings, and `params`. Omitted, inapplicable controls are not added. ```python pre = Preprocessor(preset="expanded", feature_preprocessing={"age": "bspline"}) pre.get_resolved_config() ``` -This is the authoritative answer to "what did my configuration actually become", and it is -useful in tests and reproducible experiments. +You can edit the returned dict, including nested containers, without changing the estimator. +The report includes only declared overrides, not a row for every input column. It can be read +before fitting; actual column existence and compatibility with detected feature kinds are +checked at fit time. + +```{note} +The report stays a current-request view after fitting or freezing. It is not a record of the +last fit, learned knots, or realized output widths. Changing a live raw request can change +the report while the fitted transformer continues to produce its original output. Use +`output_dims_`, `total_output_dim_`, and `get_feature_info()` for fitted results. +``` ## How the layers combine @@ -220,14 +350,39 @@ The resolution order is deterministic. Later layers win. 3. Explicit constructor arguments (`numerical_method`, `output_dim`, and so on). 4. Per-column `feature_preprocessing` entries, for the columns they name. +Within a structured entry, inheritance is per field, not an all-or-nothing replacement. + +| Setting | Effective choice | +| :------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------- | +| Method | The local `method`, otherwise the global method for the detected kind. | +| Common controls | Explicit local values win. Omitted values inherit constructor settings only when the method supports them; other defaults belong to the transformer. | +| Family `params` | Local parameters win over applicable inherited `degree`, `task`, or an explicit `random_state`. Other family defaults are left to the transformer. | +| Fixed local width | An explicit local `output_dim` disables inherited adaptive sizing unless that entry also explicitly sets `adaptive=True`. | +| Adaptive bounds | Omitted bounds inherit only when adaptive sizing is active. Explicit bounds with fixed sizing are rejected; unsupported controls are not forwarded. | +| Run-wide processing | Imputation, scaling, missing indicators, and output formatting remain constructor-wide settings, not representation parameters. | + +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". + ```{warning} -Configuration is validated at `fit` time, not silently coerced. An invalid combination, such -as a method that requires the target used with `target_aware=False`, or a `task` other than -`"regression"` / `"classification"`, raises a typed error. -This is intentional: it surfaces mistakes early rather than producing a quietly wrong -representation. +Value construction validates portable data and field types. `get_resolved_config()` and +`fit` also validate method names, supported options, and target/placement combinations. +Unknown keys and invalid methods raise typed errors with the feature's configuration path. +A local override does not make an invalid constructor-wide task or placement combination +valid. Actual input-column and feature-kind checks still require `fit`. ``` +## Using existing string configurations + +No syntax change is required for supported legacy configuration. Existing method strings, +aliases, global parameters, and per-column string overrides remain supported. Adopt mappings +or typed values only where you need local settings; other entries can stay strings. + +Equivalent fitted outputs do not imply that differently written requests have identical +fingerprints. Keep the requested configuration and dependency versions with your experiment; +see [Reproducibility](reproducibility.md) for fitted artifacts and upgrade precautions. + ## Key parameters at a glance The parameters below are the ones you reach for most. Each links to the page that explains it diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 655a8aa..4f00af3 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -176,10 +176,15 @@ class Preprocessor(TransformerMixin, BaseEstimator): language embeddings). Pass ``None`` (resolved to ``"none"``) to leave categorical columns unchanged. feature_preprocessing : dict, optional - Mapping of individual column names to a method, overriding the global ``numerical_method`` / - ``categorical_method`` for those columns only, e.g. - ``{"age": "cubicspline", "city": "pretrained"}``. Columns absent from the dict fall back to - the global defaults. + Mapping of column names to method strings, mappings with a ``method`` key, or + :class:`~pretab.RepresentationConfig` values. Forms may be mixed, for example + ``{"age": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}}, "city": "one-hot"}``. + Local settings override applicable constructor-wide controls; omitted columns use the + global methods. A local explicit width disables inherited adaptive sizing unless + local ``adaptive=True`` also opts in. Imputation, scaling, and output formatting remain + run-wide. Raw mappings stay live until normalization or fit; typed values detach on + construction. See :meth:`get_resolved_config` for detached effective declarations, + not learned state or realized widths. output_dim : int, default=7 The single width knob shared by every numerical method: the number of non-bias output columns produced per input feature (bins for PLE/binning, centers for the feature maps, diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index b847722..3ddc7af 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -20,15 +20,20 @@ _FENCE = re.compile(r"^```python\n(.*?)^```\s*$", re.DOTALL | re.MULTILINE) -def _code_blocks(path: Path) -> list[tuple[int, str]]: +def _code_blocks(path: Path, section: str | None = None) -> list[tuple[int, str]]: """Return (1-based start line, source) for every python fence in ``path``. - The source is padded with leading blank lines so a traceback raised while - executing it reports the real line number in the markdown file. + Optionally select one second-level section. The source is padded with leading + blank lines so a traceback reports the real line number in the markdown file. """ text = path.read_text(encoding="utf-8") + start = text.index(f"## {section}\n") if section is not None else 0 + stop = text.find("\n## ", start + 1) if section is not None else -1 + stop = len(text) if stop == -1 else stop blocks = [] for match in _FENCE.finditer(text): + if not start <= match.start() < stop: + continue start_line = text.count("\n", 0, match.start()) + 2 padded = "\n" * (start_line - 1) + match.group(1) blocks.append((start_line, padded)) @@ -59,11 +64,23 @@ def isolate_document_state(tmp_path, monkeypatch): registry.CATEGORICAL_METHODS.update(categorical) -@pytest.mark.parametrize("tutorial", _TUTORIALS, ids=[p.stem for p in _TUTORIALS]) +@pytest.mark.parametrize( + ("tutorial", "section"), + [pytest.param(page, None, id=page.stem) for page in _TUTORIALS] + + [ + pytest.param( + ROOT / "docs" / "core_concepts" / "configuration.md", + "Structured per-feature configuration", + id="configuration", + ) + ], +) @pytest.mark.filterwarnings("ignore::pretab.exceptions.LeakageWarning") -def test_tutorial_code_runs(tutorial): +def test_tutorial_code_runs(tutorial, section): namespace: dict = {"__name__": "__main__"} - for start_line, source in _code_blocks(tutorial): + blocks = _code_blocks(tutorial, section) + assert blocks, f"No Python examples found in {tutorial.name}: {section}" + for start_line, source in blocks: try: exec(compile(source, str(tutorial), "exec"), namespace) # noqa: S102 except Exception as exc: From fdafd7bff94db39729e70530459195040a174def Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 01:04:51 +0100 Subject: [PATCH 25/86] feat(config): enable per-feature one-hot options --- docs/api/preprocessor.rst | 7 + pretab/compose/registry.py | 17 ++- tests/compose/test_factory.py | 158 ++++++++++++++++++++ tests/regression/_snapshots/public_api.json | 11 +- 4 files changed, 191 insertions(+), 2 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index a3361e7..1ba7ad7 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -50,6 +50,13 @@ Fields and conversion ``params`` Family-specific constructor options, such as ``{"gamma": 0.5}`` for RBF. Common fields belong at the top level, not in this mapping. + One-hot entries accept encoder options such as ``categories``, ``drop``, + ``handle_unknown``, and ``sparse_output``. For example, + ``{"method": "one-hot", "params": {"drop": "first", "sparse_output": False}}`` + drops one category and requests dense encoding. Encoder ``dtype`` values + must be portable, such as ``"float32"``, rather than NumPy scalar classes. + Use the preprocessor's ``dtype`` to control the final output dtype; + encoder settings do not bypass subsequent output conversion. ``name`` Optional nonempty metadata label, default ``None``. It does not rename diff --git a/pretab/compose/registry.py b/pretab/compose/registry.py index 22d168b..f197352 100644 --- a/pretab/compose/registry.py +++ b/pretab/compose/registry.py @@ -333,7 +333,22 @@ def _spec(name, cls, allowed_args=(), **kwargs): _spec("none", NoTransformer, feature_kind=frozenset({NUMERICAL, CATEGORICAL})), # --- categorical-only methods --- _spec("int", ContinuousOrdinalTransformer, feature_kind=frozenset({CATEGORICAL})), - _spec("one-hot", OneHotEncoder, feature_kind=frozenset({CATEGORICAL}), sparse_output=True), + _spec( + "one-hot", + OneHotEncoder, + ( + "categories", + "drop", + "sparse_output", + "dtype", + "handle_unknown", + "min_frequency", + "max_categories", + "feature_name_combiner", + ), + feature_kind=frozenset({CATEGORICAL}), + sparse_output=True, + ), _spec("onehot_from_ordinal", OneHotFromOrdinalTransformer, feature_kind=frozenset({CATEGORICAL})), _spec( "pretrained", diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index a379d8f..8afd472 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -13,6 +13,7 @@ from pretab import Preprocessor from pretab.compose.config import PreprocessorConfig, RepresentationConfig from pretab.compose.factory import ( + _clamp_spline_basis, _placement_kwargs, build_column_transformer, create_transformer, @@ -220,6 +221,163 @@ def test_preprocessor_fits_structured_representation(typed): assert transformed.shape == (30, 3) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize( + ("method", "canonical", "output_dim", "params"), + [("RBF", "rbf", 3, {"gamma": 0.5}), ("b-spline", "bspline", 6, {"degree": 2})], +) +def test_preprocessor_routes_local_options_through_both_step_builders(typed, method, canonical, output_dim, params): + settings = { + "age": {"method": method, "output_dim": output_dim, "params": params, "name": "age-basis"}, + "city": {"method": "OHE", "params": {"drop": "first", "sparse_output": False}}, + } + overrides = { + feature: RepresentationConfig.from_dict(value) if typed else value for feature, value in settings.items() + } + frame = pd.DataFrame({"age": np.linspace(0, 1, 40), "city": ["a", "b"] * 20}) + processor = Preprocessor( + feature_preprocessing=overrides, + output_dim=11, + degree=3, + random_state=17, + target_aware=False, + placement_strategy="quantile", + scaling="standardization", + ) + + with ( + patch("pretab.compose.factory.create_transformer", wraps=create_transformer) as create, + patch( + "pretab.compose.factory.get_numerical_transformer_steps", wraps=get_numerical_transformer_steps + ) as numerical, + patch( + "pretab.compose.factory.get_categorical_transformer_steps", wraps=get_categorical_transformer_steps + ) as categorical, + ): + processor.fit(frame) + + assert [entry.args[0] for entry in create.call_args_list] == [canonical, "one-hot"] + assert all(isinstance(entry.kwargs["representation"], RepresentationConfig) for entry in create.call_args_list) + numerical.assert_called_once() + options = numerical.call_args.kwargs + assert options["method"] == canonical + assert options["output_dim"] == output_dim + assert options["target_aware"] is False + assert options["placement_strategy"] == "quantile" + assert options["scaling"] == "standardization" + assert "name" not in options + if canonical == "rbf": + assert "degree" not in options + for key, value in params.items(): + assert options[key] == value + categorical.assert_called_once_with( + "one-hot", add_imputer=True, imputer_strategy="most_frequent", drop="first", sparse_output=False + ) + + numeric = processor.column_transformer_.named_transformers_["num_age"] + assert _names(numeric.steps) == ["imputer", "scaler", canonical] + basis = numeric.named_steps[canonical] + assert basis.output_dim == output_dim + assert basis.target_aware is False + assert basis.placement_strategy == "quantile" + for key, value in params.items(): + assert getattr(basis, key) == value + encoder = processor.column_transformer_.named_transformers_["cat_city"].named_steps["onehot"] + assert encoder.drop == "first" + assert encoder.sparse_output is False + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (40, output_dim + 1) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("method", ["bspline", "mspline", "ispline"]) +def test_preprocessor_clamps_each_local_spline_width(typed, method): + settings = { + "age": {"method": method, "output_dim": 3, "placement_strategy": "quantile", "degree": 2}, + "income": {"method": method, "output_dim": 51, "placement_strategy": "uniform", "degree": 3}, + } + overrides = { + feature: RepresentationConfig.from_dict(value) if typed else value for feature, value in settings.items() + } + frame = pd.DataFrame({"age": np.linspace(0, 1, 80) ** 3, "income": np.linspace(2, 8, 80) ** 2}) + with ( + patch("pretab.compose.factory._clamp_spline_basis", wraps=_clamp_spline_basis) as clamp, + pytest.warns(ConfigWarning) as emitted, + ): + processor = Preprocessor( + feature_preprocessing=overrides, + output_dim=11, + target_aware=False, + placement_strategy="uniform", + scaling="none", + ).fit(frame) + + assert clamp.call_args_list == [call(3), call(51)] + assert len(emitted) == 2 + for feature, expected in (("age", 5), ("income", 50)): + basis = processor.column_transformer_.named_transformers_[f"num_{feature}"].named_steps[method] + assert basis.output_dim == expected + assert basis.degree == settings[feature]["degree"] + assert basis.placement_strategy == settings[feature]["placement_strategy"] + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (80, 55) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("handle_unknown", ["error", "ignore"]) +def test_preprocessor_forwards_portable_one_hot_constructor_options(typed, handle_unknown): + params = { + "categories": [["a", "b", "c"]], + "drop": ["a"], + "sparse_output": False, + "dtype": "float32", + "handle_unknown": handle_unknown, + "min_frequency": None, + "max_categories": None, + "feature_name_combiner": "concat", + } + settings = {"method": "one-hot", "params": params} + requested = RepresentationConfig.from_dict(settings) if typed else settings + frame = pd.DataFrame({"city": ["a", "b", "c"] * 10}) + processor = Preprocessor(feature_preprocessing={"city": requested}).fit(frame) + block = processor.column_transformer_.named_transformers_["cat_city"] + encoder = block.named_steps["onehot"] + assert {key: encoder.get_params()[key] for key in params} == params + np.testing.assert_array_equal(processor.transform(frame, return_array=True)[:3], [[0, 0], [1, 0], [0, 1]]) + if handle_unknown == "error": + with pytest.raises(ValueError, match="unknown categories"): + processor.transform(pd.DataFrame({"city": ["unseen"]}), return_array=True) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_preprocessor_applies_each_local_placement_capability(typed): + settings = { + "supervised": {"method": "ple", "output_dim": 3, "target_aware": True, "placement_strategy": "cart"}, + "unsupervised": {"method": "rbf", "output_dim": 4, "target_aware": False, "placement_strategy": "quantile"}, + "penalized": {"method": "pspline", "output_dim": 6, "target_aware": False, "placement_strategy": "uniform"}, + } + overrides = { + feature: RepresentationConfig.from_dict(value) if typed else value for feature, value in settings.items() + } + values = np.linspace(0, 1, 80) + frame = pd.DataFrame({feature: values ** (index + 1) for index, feature in enumerate(settings)}) + with patch("pretab.compose.factory._placement_kwargs", wraps=_placement_kwargs) as placement: + processor = Preprocessor(feature_preprocessing=overrides, scaling="none").fit(frame, np.sin(6 * values)) + + assert [entry.args[0].name for entry in placement.call_args_list] == ["ple", "rbf", "pspline"] + for feature, requested in settings.items(): + basis = processor.column_transformer_.named_transformers_[f"num_{feature}"].named_steps[requested["method"]] + assert basis.output_dim == requested["output_dim"] + assert basis.placement_strategy == requested["placement_strategy"] + if requested["method"] == "rbf": + assert basis.target_aware is False + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (80, 13) + + @pytest.mark.parametrize("adaptive", [False, True]) @pytest.mark.parametrize("random_state", [None, 17]) @pytest.mark.parametrize( diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index e804912..a1a3dcd 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -555,7 +555,16 @@ "transformer_cls": "pretab.kernel_approximation.nystroem.NystroemFeaturesTransformer" }, "one-hot": { - "allowed_args": [], + "allowed_args": [ + "categories", + "drop", + "sparse_output", + "dtype", + "handle_unknown", + "min_frequency", + "max_categories", + "feature_name_combiner" + ], "arity": "univariate", "derived_capabilities": { "is_categorical": true, From 7f94debcb86e2f40d94afbbc4c48ef6e0861f61d Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 01:38:44 +0100 Subject: [PATCH 26/86] test(config): verify per-feature adaptive width precedence --- tests/integration/test_adaptive_output_dim.py | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/tests/integration/test_adaptive_output_dim.py b/tests/integration/test_adaptive_output_dim.py index 3721e13..1aae151 100644 --- a/tests/integration/test_adaptive_output_dim.py +++ b/tests/integration/test_adaptive_output_dim.py @@ -18,7 +18,9 @@ import numpy as np import pandas as pd import pytest +from sklearn.base import clone +from pretab import RepresentationConfig from pretab.exceptions import InvalidParamError from pretab.expansion.spline.b_spline import BSplineTransformer from pretab.expansion.spline.i_spline import ISplineTransformer @@ -177,6 +179,48 @@ def test_adaptive_width_within_window(data, method): assert adaptive < fixed +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("global_adaptive", [False, True], ids=["global-fixed", "global-adaptive"]) +@pytest.mark.parametrize("method", ADAPTIVE_VIA_PREPROCESSOR + BMI_SPLINE_METHODS + TARGET_AWARE_LEGACY_SPLINE_METHODS) +def test_per_feature_explicit_width_and_adaptive_opt_in_are_deterministic(data, typed, global_adaptive, method): + X, y = data + requests = { + "fixed": {"method": method, "output_dim": 10}, + "opt_out": {"method": method, "output_dim": 10, "adaptive": False}, + "opt_in": {"method": method, "output_dim": 10, "adaptive": True}, + "inherited": {"method": method}, + } + features = pd.DataFrame(dict.fromkeys(requests, X["x"])) + pre = Preprocessor( + categorical_method="none", + output_dim=12, + adaptive=global_adaptive, + min_output_dim=5, + max_output_dim=7, + target_aware=True, + placement_strategy="cart", + task="regression", + random_state=17, + feature_preprocessing={ + name: RepresentationConfig.from_dict(settings) if typed else settings for name, settings in requests.items() + }, + ) + repeated = clone(pre) + assert isinstance(repeated, Preprocessor) + blocks = cast("dict[str, np.ndarray]", pre.fit(features, y).transform(features, return_array=False)) + repeated_blocks = cast("dict[str, np.ndarray]", repeated.fit(features, y).transform(features, return_array=False)) + + assert blocks["num_fixed"].shape == blocks["num_opt_out"].shape == (len(features), 10) + assert 5 <= blocks["num_opt_in"].shape[1] <= 7 + if global_adaptive: + assert 5 <= blocks["num_inherited"].shape[1] <= 7 + else: + assert blocks["num_inherited"].shape == (len(features), 12) + np.testing.assert_array_equal(blocks["num_fixed"], blocks["num_opt_out"]) + for name in requests: + np.testing.assert_array_equal(blocks[f"num_{name}"], repeated_blocks[f"num_{name}"]) + + # --------------------------------------------------------------------------- # # Adaptive mode at the transformer level: the B/M/I splines honor the window. # --------------------------------------------------------------------------- # From 5e8cb0a2377fe263ef11f9fed8cc41b1b62801b2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 01:59:34 +0100 Subject: [PATCH 27/86] test(config): verify feature-qualified applicability errors --- tests/integration/test_preprocessor.py | 67 ++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 59f27ce..7a23d24 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -500,6 +500,73 @@ def test_unknown_feature_preprocessing_key_raises(sample_data): Preprocessor(feature_preprocessing={"nnum1": "minmax"}).fit(X, y) +@pytest.mark.parametrize("operation", ["fit", "fit_transform"]) +@pytest.mark.parametrize("syntax", ["shorthand", "nested", "value"]) +@pytest.mark.parametrize( + ("feature", "settings", "option", "constraint"), + [ + pytest.param( + "color", {"method": "one-hot", "degree": 3}, "degree", "is not applicable", id="categorical-degree" + ), + pytest.param("num1", {"method": "rbf", "degree": 3}, "degree", "is not applicable", id="rbf-degree"), + pytest.param("num1", {"method": "minmax", "gamma": 0.5}, "gamma", "is not applicable", id="scaler-gamma"), + pytest.param("color", {"method": "OHE", "gamma": 0.5}, "gamma", "is not applicable", id="alias-gamma"), + pytest.param( + "color", {"method": "one-hot", "output_dim": 3}, "output_dim", "is not applicable", id="categorical-width" + ), + pytest.param( + "color", + {"method": "one-hot", "adaptive": True}, + "adaptive", + "method 'one-hot' does not support adaptive resolution", + id="categorical-adaptive", + ), + pytest.param( + "color", + {"method": "one-hot", "target_aware": True}, + "target_aware", + "method 'one-hot' cannot use the target", + id="forbidden-target", + ), + pytest.param( + "num1", + {"method": "ple", "target_aware": False}, + "target_aware", + "method 'ple' requires the target", + id="required-target", + ), + pytest.param( + "num1", + {"method": "pspline", "placement_strategy": "quantile"}, + "placement_strategy", + "is not supported by method 'pspline'", + id="unsupported-placement", + ), + ], +) +def test_inapplicable_feature_options_report_feature_path( + sample_data, operation, syntax, feature, settings, option, constraint +): + X, y = sample_data + X = X.rename(columns={"cat1": "color"}) + if syntax == "shorthand": + representation = settings + elif syntax == "nested": + representation = RepresentationConfig.from_dict(settings).to_dict() + else: + representation = RepresentationConfig.from_dict(settings) + pre = Preprocessor(feature_preprocessing={feature: representation}) + + with pytest.raises(InvalidParamError) as error: + getattr(pre, operation)(X, y) + + message = str(error.value) + heading = message.splitlines()[0] + assert f"feature_preprocessing[{feature!r}]." in heading + assert option in heading + assert f"Constraint: {constraint}" in message + + # --- positional width check at transform (issue #72) ------------------------------ From 0550c10e4cc28a42e047d5fd1225305ae800d790 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 13:36:35 +0100 Subject: [PATCH 28/86] fix(serialization): round-trip typed representation configs --- docs/api/preprocessor.rst | 14 +++ pretab/compose/serialize.py | 6 +- tests/compose/test_block_layout_contract.py | 105 +++++++++++++++++++- tests/integration/test_serialization.py | 62 ++++++++++-- 4 files changed, 178 insertions(+), 9 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 1ba7ad7..0f2ae02 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -119,6 +119,20 @@ configuration needs no syntax change, and can be mixed with structured entries. Configuration, output, and reproducibility ------------------------------------------ +Fitted preprocessors using string, mapping, or +:class:`~pretab.RepresentationConfig` entries can be saved with +:meth:`~pretab.Preprocessor.to_spec` and restored with +:meth:`~pretab.Preprocessor.from_spec` in the same environment. Restored names, +lineage, widths, output values, and fingerprints retain the fitted state, +including adaptive sizing and separate missing indicators. Representation +summaries describe the representation itself, excluding separate indicators; +output budgets and reported output dimensions include those indicators. + +.. warning:: + + Load specs only from trusted sources. Dependency versions recorded in a + spec do not guarantee compatibility with a different environment. + Supporting types returned or consumed by the preprocessor. .. autosummary:: diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 6705ac8..0bc14d3 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -39,6 +39,7 @@ from ..exceptions import PretabSerializationError from ..placement.base import PlacementResult from ..preprocessing.floats import NoTransformer, ToFloatTransformer +from .config import RepresentationConfig from .inspection import representation_leaf from .registry import TransformerSpec @@ -59,7 +60,7 @@ # let a spec construct an arbitrary sklearn/numpy/scipy dataclass with # attacker-controlled fields. _ALLOWED_DATACLASSES = frozenset( - {RepresentationPolicy, RepresentationSpec, FeatureLineage, PlacementResult, TransformerSpec} + {RepresentationPolicy, RepresentationSpec, FeatureLineage, PlacementResult, TransformerSpec, RepresentationConfig} ) @@ -154,6 +155,9 @@ def _encode(obj): return [_encode(v) for v in obj] if isinstance(obj, BaseEstimator): return {"__estimator__": {"class": _qualname(obj), "state": _encode_mapping(vars(obj))}} + if type(obj) is RepresentationConfig: + fields = {key: _encode(value) for key, value in obj.to_dict().items()} + return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} if dataclasses.is_dataclass(obj) and not isinstance(obj, type): fields = {f.name: _encode(getattr(obj, f.name)) for f in dataclasses.fields(obj)} return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} diff --git a/tests/compose/test_block_layout_contract.py b/tests/compose/test_block_layout_contract.py index 537506e..b178de3 100644 --- a/tests/compose/test_block_layout_contract.py +++ b/tests/compose/test_block_layout_contract.py @@ -1,19 +1,22 @@ """Agreement between fitted block spans and the public output-layout APIs.""" +import json +from contextlib import nullcontext from unittest.mock import Mock import numpy as np import pandas as pd import pytest from scipy import sparse +from sklearn.base import clone from sklearn.pipeline import FeatureUnion, Pipeline from sklearn.utils.validation import check_is_fitted -from pretab import BaseRepresentation, Preprocessor, register_representation +from pretab import BaseRepresentation, Preprocessor, RepresentationConfig, register_representation from pretab.compose import registry from pretab.compose.inspection import block_name, build_feature_lineage, get_output_slices from pretab.embedding.language import LanguageEmbeddingTransformer -from pretab.exceptions import IncompatibleParamsError +from pretab.exceptions import ConfigWarning, IncompatibleParamsError, OutputBudgetError class _PositiveOnly(BaseRepresentation): @@ -190,6 +193,104 @@ def test_fitted_block_layout_agrees_across_views(layout_data, output_format, par np.testing.assert_array_equal(_dense(blocks[name])[:, -1], frame[feature].isna().astype(float)) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize("missing_policy", [None, "separate_state"]) +@pytest.mark.parametrize("sizing", ["fixed", "adaptive", "clamped"]) +def test_structured_fitted_widths_agree_across_views(layout_data, typed, output_format, missing_policy, sizing): + frame, target = layout_data + requests = { + "value": {"method": "rbf", "output_dim": 12, "adaptive": True} + if sizing == "adaptive" + else {"method": "rbf", "output_dim": 2}, + "other": {"method": "bspline", "output_dim": 3 if sizing == "clamped" else 6, "params": {"degree": 2}}, + "city": {"method": "one-hot", "params": {"drop": "first"}}, + } + preprocessor = Preprocessor( + output_dim=12, + adaptive=True, + min_output_dim=3, + max_output_dim=4, + target_aware=True, + placement_strategy="cart", + random_state=17, + missing_policy=missing_policy, + output_format=output_format, + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + ) + with pytest.warns(ConfigWarning) if sizing == "clamped" else nullcontext(): + Pipeline([("preprocessor", preprocessor)]).fit(frame, target) + + _assert_block_layout(preprocessor, frame) + indicator = int(missing_policy == "separate_state") + dimensions = preprocessor.output_dims_ + if sizing == "adaptive": + assert 3 <= dimensions["value"] - indicator <= 4 + assert dimensions["value"] - indicator < requests["value"]["output_dim"] + else: + assert dimensions["value"] == 2 + indicator + assert dimensions["other"] == (5 if sizing == "clamped" else 6) + indicator + assert dimensions["city"] == frame["city"].nunique() - 1 + indicator + + names = preprocessor.get_feature_names_out() + transformed = _dense(preprocessor.transform(frame, return_array=True)) + fingerprint = preprocessor.fingerprint_ + report = preprocessor.reproducibility_report() + spec = json.loads(json.dumps(preprocessor.to_spec(), allow_nan=False)) + representations = {entry["columns"][0]: entry for entry in spec["representations"]} + assert set(representations) == {"value", "other"} + for feature, entry in representations.items(): + assert entry["output_dim"] == len(entry["output_features"]) == dimensions[feature] - indicator + assert spec["feature_names_out"] == list(names) + assert report["n_features_in"] == frame.shape[1] + assert report["n_output_features"] == transformed.shape[1] == sum(dimensions.values()) + assert report["fingerprint"] == fingerprint + assert report["representations"] == {feature: entry["family"] for feature, entry in representations.items()} + + restored = Preprocessor.from_spec(spec) + _assert_block_layout(restored, frame) + assert restored.output_dims_ == dimensions + assert restored.get_feature_info(verbose=False) == preprocessor.get_feature_info(verbose=False) + assert restored.get_feature_lineage() == preprocessor.get_feature_lineage() + assert restored.reproducibility_report() == report + assert restored.fingerprint_ == fingerprint + np.testing.assert_array_equal(restored.get_feature_names_out(), names) + np.testing.assert_array_equal(_dense(restored.transform(frame, return_array=True)), transformed) + + assert preprocessor.estimate_output_shape(frame) == transformed.shape + assert preprocessor.estimate_memory(frame) == transformed.nbytes + limits = { + "max_output_features": transformed.shape[1], + "max_features_per_input": max(dimensions.values()), + "max_dense_memory": transformed.nbytes, + } + bounded = clone(preprocessor) + assert isinstance(bounded, Preprocessor) + bounded.set_params(**limits) + with pytest.warns(ConfigWarning) if sizing == "clamped" else nullcontext(): + bounded.fit(frame, target) + _assert_block_layout(bounded, frame) + assert bounded.output_dims_ == dimensions + np.testing.assert_array_equal(_dense(bounded.transform(frame, return_array=True)), transformed) + + expected_details = { + "max_output_features": f"total output columns ({transformed.shape[1]})", + "max_features_per_input": f"feature 'other' expands to {dimensions['other']} columns", + "max_dense_memory": f"needs ~{transformed.nbytes} bytes", + } + for budget, limit in limits.items(): + rejected = clone(preprocessor) + assert isinstance(rejected, Preprocessor) + rejected.set_params(**{budget: limit - 1}) + with pytest.raises(OutputBudgetError, match=budget) as error: + with pytest.warns(ConfigWarning) if sizing == "clamped" else nullcontext(): + rejected.fit(frame, target) + assert expected_details[budget] in str(error.value) + + @pytest.mark.parametrize("output_format", ["dense", "sparse"]) def test_language_embedding_block_layout(layout_data, monkeypatch, output_format): frame, _ = layout_data diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index 1a6c137..a859824 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -15,8 +15,10 @@ import pandas as pd import pytest -from pretab import Preprocessor, PretabSerializationError, RepresentationPolicy -from pretab.compose.serialize import SCHEMA_VERSION, _encode_mapping +from pretab import Preprocessor, PretabSerializationError, RepresentationConfig, RepresentationPolicy +from pretab.compose.serialize import SCHEMA_VERSION, _decode, _encode, _encode_mapping +from pretab.core.parameters import UNSET +from pretab.exceptions import InvalidParamError from pretab.preprocessing.floats import NoTransformer, ToFloatTransformer @@ -449,7 +451,8 @@ def test_from_spec_refuses_estimator_not_a_base_estimator(): Preprocessor.from_spec(spec) -def test_from_spec_refuses_dataclass_not_in_allowlist(): +@pytest.mark.parametrize("class_name", ["PreprocessorConfig", "_FrozenParams"]) +def test_from_spec_refuses_dataclass_not_in_allowlist(class_name): """An allowed-module, genuinely-a-dataclass class must still be refused unless it is one of the specifically approved dataclasses. @@ -461,15 +464,62 @@ def test_from_spec_refuses_dataclass_not_in_allowlist(): spec = { "schema_version": SCHEMA_VERSION, "state": { - "__dict__": [ - ["evil", {"__dataclass__": {"class": "pretab.compose.config:PreprocessorConfig", "fields": {}}}] - ] + "__dict__": [["evil", {"__dataclass__": {"class": f"pretab.compose.config:{class_name}", "fields": {}}}]] }, } with pytest.raises(PretabSerializationError, match="disallowed dataclass"): Preprocessor.from_spec(spec) +@pytest.mark.parametrize( + "settings", + [ + {"method": "RBF"}, + {"method": "rbf", "output_dim": 3, "adaptive": False, "name": "local"}, + { + "method": "rbf", + "adaptive": True, + "min_output_dim": None, + "max_output_dim": 7, + "params": {"random_state": None, "nested": {"levels": [True, 2, 0.5, None]}}, + }, + ], +) +def test_representation_config_codec_preserves_portable_values(settings): + value = RepresentationConfig.from_dict(settings) + text = json.dumps(_encode(value), allow_nan=False) + assert "_FrozenParams" not in text + restored = _decode(json.loads(text)) + assert type(restored) is RepresentationConfig + assert restored == value + assert restored.to_dict() == value.to_dict() + for field in ("output_dim", "target_aware", "placement_strategy", "adaptive", "min_output_dim", "max_output_dim"): + if field not in settings: + assert getattr(restored, field) is UNSET + detached = restored.to_dict() + detached["params"]["changed"] = True + assert restored == value + + +@pytest.mark.parametrize( + ("fields", "constraint"), + [ + ({"output_dim": 0}, "must be a positive integer"), + ({"adaptive": "yes"}, "must be a boolean"), + ({"params": {"gamma": math.inf}}, "finite JSON-compatible values"), + ], +) +def test_representation_config_decoder_runs_value_validation(fields, constraint): + payload = { + "__dataclass__": { + "class": "pretab.compose.config:RepresentationConfig", + "fields": _encode_mapping({"method": "rbf", **fields}), + } + } + with pytest.raises(InvalidParamError, match=constraint): + _decode(payload) + + def test_from_spec_rejects_bad_source_type(): with pytest.raises(PretabSerializationError): Preprocessor.from_spec(12345) From d5867d3f3d143836e3284aa3e8efdb898071b0ac Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 18:13:14 +0100 Subject: [PATCH 29/86] test(config): verify independent per-feature fitted state --- tests/integration/test_preprocessor.py | 139 ++++++++++++++++++++++++- 1 file changed, 138 insertions(+), 1 deletion(-) diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 7a23d24..c3ebfef 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -8,11 +8,12 @@ from sklearn.impute import SimpleImputer from sklearn.linear_model import Ridge from sklearn.model_selection import GridSearchCV -from sklearn.pipeline import Pipeline +from sklearn.pipeline import FeatureUnion, Pipeline from sklearn.utils.validation import check_is_fitted from pretab import RepresentationConfig from pretab.exceptions import IncompatibleParamsError, InvalidParamError, PretabDataError +from pretab.expansion.functional.rbf import RBFExpansionTransformer from pretab.preprocessor import Preprocessor # Adjust the import as needed @@ -271,6 +272,142 @@ def test_structured_feature_params_survive_fit_and_clone(sample_data, typed, fit assert transformed.shape == (len(frame), 3) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("missing_policy", [None, "separate_state"]) +@pytest.mark.parametrize("target_aware", [False, True], ids=["quantile", "cart"]) +def test_same_method_features_keep_independent_fitted_state(typed, missing_policy, target_aware): + values = np.linspace(1.0, 9.0, 80) + frame = pd.DataFrame({"first": values, "second": values**2 + 20.0}) + frame.loc[3, "first"] = np.nan + frame.loc[7, "second"] = np.nan + target = np.sin(values) + settings = { + "first": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "second": {"method": "rbf", "output_dim": 5, "params": {"gamma": 0.75}}, + } + processor = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(options) if typed else options + for feature, options in settings.items() + }, + target_aware=target_aware, + placement_strategy="cart" if target_aware else "quantile", + scaling="standardization", + random_state=17, + missing_policy=missing_policy, + output_structure="blocks", + ).fit(frame, target) + pipelines = [] + missing_states = [] + for feature in settings: + block = processor.column_transformer_.named_transformers_[f"num_{feature}"] + if missing_policy == "separate_state": + assert isinstance(block, FeatureUnion) + branches = dict(block.transformer_list) + missing_states.append(branches["missing"]) + block = branches["representation"] + assert isinstance(block, Pipeline) + pipelines.append(block) + first, second = pipelines + assert first is not second + if missing_states: + assert missing_states[0] is not missing_states[1] + for name in first.named_steps: + assert first.named_steps[name] is not second.named_steps[name] + first_basis = first.named_steps["rbf"] + second_basis = second.named_steps["rbf"] + assert isinstance(first_basis, RBFExpansionTransformer) + assert isinstance(second_basis, RBFExpansionTransformer) + assert (first_basis.output_dim, first_basis.gamma) == (3, 0.25) + assert (second_basis.output_dim, second_basis.gamma) == (5, 0.75) + assert first_basis.centers_ is not second_basis.centers_ + assert not np.shares_memory(first_basis.centers_[0], second_basis.centers_[0]) + for step, attribute in (("imputer", "statistics_"), ("scaler", "mean_"), ("scaler", "scale_")): + assert not np.shares_memory( + getattr(first.named_steps[step], attribute), getattr(second.named_steps[step], attribute) + ) + sibling_centers = second_basis.centers_[0].copy() + sibling_statistics = second.named_steps["imputer"].statistics_.copy() + sibling_mean = second.named_steps["scaler"].mean_.copy() + sibling_scale = second.named_steps["scaler"].scale_.copy() + reference = processor.transform(frame) + assert isinstance(reference, dict) + indicator = int(missing_policy == "separate_state") + assert processor.output_dims_ == {"first": 3 + indicator, "second": 5 + indicator} + + first_basis.centers_[0] += 0.25 + first.named_steps["imputer"].statistics_ += 1.0 + first.named_steps["scaler"].mean_ += 0.5 + changed = processor.transform(frame) + assert isinstance(changed, dict) + assert not np.array_equal(changed["num_first"], reference["num_first"]) + np.testing.assert_array_equal(changed["num_second"], reference["num_second"]) + + first.fit(frame[["first"]] ** 2, target) + refitted = processor.transform(frame) + assert isinstance(refitted, dict) + np.testing.assert_array_equal(refitted["num_second"], reference["num_second"]) + np.testing.assert_array_equal(second_basis.centers_[0], sibling_centers) + np.testing.assert_array_equal(second.named_steps["imputer"].statistics_, sibling_statistics) + np.testing.assert_array_equal(second.named_steps["scaler"].mean_, sibling_mean) + np.testing.assert_array_equal(second.named_steps["scaler"].scale_, sibling_scale) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("missing_policy", [None, "separate_state"]) +def test_one_hot_features_keep_independent_fitted_state(typed, missing_policy): + frame = pd.DataFrame({"first": ["a", "b", "a", None] * 20, "second": ["x", "y", "z", "x"] * 20}) + settings = { + "first": {"method": "one-hot", "params": {"drop": "first", "sparse_output": False}}, + "second": {"method": "one-hot", "params": {"drop": None, "sparse_output": False}}, + } + processor = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(options) if typed else options + for feature, options in settings.items() + }, + missing_policy=missing_policy, + output_structure="blocks", + ).fit(frame) + pipelines = [] + for feature in settings: + block = processor.column_transformer_.named_transformers_[f"cat_{feature}"] + if missing_policy == "separate_state": + assert isinstance(block, FeatureUnion) + block = dict(block.transformer_list)["representation"] + assert isinstance(block, Pipeline) + pipelines.append(block) + first, second = pipelines + assert first is not second + for name in first.named_steps: + assert first.named_steps[name] is not second.named_steps[name] + first_encoder = first.named_steps["onehot"] + second_encoder = second.named_steps["onehot"] + assert first_encoder.drop == "first" + assert second_encoder.drop is None + assert first_encoder.categories_ is not second_encoder.categories_ + assert not np.shares_memory(first_encoder.categories_[0], second_encoder.categories_[0]) + assert not np.shares_memory(first.named_steps["imputer"].statistics_, second.named_steps["imputer"].statistics_) + sibling_categories = second_encoder.categories_[0].copy() + sibling_statistics = second.named_steps["imputer"].statistics_.copy() + sibling_block = processor.column_transformer_.named_transformers_["cat_second"] + reference = sibling_block.transform(frame[["second"]]) + indicator = int(missing_policy == "separate_state") + assert processor.output_dims_ == {"first": 1 + indicator, "second": 3 + indicator} + + first_encoder.categories_[0][0] = "changed" + first.named_steps["imputer"].statistics_[0] = "changed" + np.testing.assert_array_equal(second_encoder.categories_[0], sibling_categories) + np.testing.assert_array_equal(second.named_steps["imputer"].statistics_, sibling_statistics) + np.testing.assert_array_equal(sibling_block.transform(frame[["second"]]), reference) + + first.fit(frame[["first"]].replace({"a": "q", "b": "r"})) + np.testing.assert_array_equal(first_encoder.categories_[0], ["q", "r"]) + np.testing.assert_array_equal(second_encoder.categories_[0], sibling_categories) + np.testing.assert_array_equal(second.named_steps["imputer"].statistics_, sibling_statistics) + np.testing.assert_array_equal(sibling_block.transform(frame[["second"]]), reference) + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("fitted", [False, True], ids=["unfitted", "fitted"]) def test_pipeline_set_params_replaces_structured_feature_settings(sample_data, typed, fitted): From c8c1df7ea4660158e5d83ef0d659d460f1f9dc1a Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 15 Nov 2026 21:48:02 +0100 Subject: [PATCH 30/86] test(config): pin 2/3/5 per-feature width contract --- docs/core_concepts/configuration.md | 58 ++++++++++++++++++++- tests/compose/test_block_layout_contract.py | 45 ++++++++++++++++ 2 files changed, 102 insertions(+), 1 deletion(-) diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index 2cc13c3..af99109 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -146,7 +146,7 @@ Don't infer the resolved method per column from the constructor arguments alone. ## Structured per-feature configuration -These three examples use the same training data and a scikit-learn regression pipeline. +The first three examples use the same training data and a scikit-learn regression pipeline. `income` is deliberately left out of each override map, so it uses the global `"none"` method and contributes one column. @@ -262,6 +262,62 @@ transformers. Use `RepresentationConfig` when the request itself should be immut construction onward. Neither form changes an already fitted graph without another fit. ``` +### Different widths for the same method + +Each column can use the same representation with a different width. With +`output_structure="blocks"`, numerical block keys have a `num_` prefix, while +`output_dims_` and `get_feature_info()` use the source column names. + +```python +import numpy as np +import pandas as pd + +from pretab import Preprocessor + +numeric_frame = pd.DataFrame({ + "age": np.linspace(18.0, 70.0, 80), + "income": np.linspace(25000.0, 90000.0, 80), + "tenure": np.linspace(0.0, 30.0, 80), +}) +widths = Preprocessor( + feature_preprocessing={ + "age": {"method": "rbf", "output_dim": 2}, + "income": {"method": "rbf", "output_dim": 3}, + "tenure": {"method": "rbf", "output_dim": 5}, + }, + target_aware=False, + placement_strategy="uniform", + scaling="none", + output_structure="blocks", +) +blocks = widths.fit_transform(numeric_frame) + +assert widths.output_dims_ == {"age": 2, "income": 3, "tenure": 5} +assert widths.total_output_dim_ == 10 +numerical, categorical, embeddings = widths.get_feature_info(verbose=False) +assert {name: info["dimension"] for name, info in numerical.items()} == widths.output_dims_ +assert categorical == embeddings == {} +names = widths.get_feature_names_out() +assert names.tolist() == [ + f"num_{feature}_rbf{index}" + for feature, width in widths.output_dims_.items() + for index in range(width) +] +assert {name: block.shape for name, block in blocks.items()} == { + "num_age": (80, 2), + "num_income": (80, 3), + "num_tenure": (80, 5), +} +np.testing.assert_array_equal( + np.hstack([blocks["num_age"], blocks["num_income"], blocks["num_tenure"]]), + widths.transform(numeric_frame, return_array=True), +) +``` + +The blocks contain two, three and five columns in source order. Their concatenation +matches the ten-column matrix returned by `return_array=True`. Size each input +block from the fitted dimensions, not the constructor-wide `output_dim`. + ## Presets Presets are transparent, named bundles of parameters for common intents. They set the same diff --git a/tests/compose/test_block_layout_contract.py b/tests/compose/test_block_layout_contract.py index b178de3..c256b72 100644 --- a/tests/compose/test_block_layout_contract.py +++ b/tests/compose/test_block_layout_contract.py @@ -291,6 +291,51 @@ def test_structured_fitted_widths_agree_across_views(layout_data, typed, output_ assert expected_details[budget] in str(error.value) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_same_method_widths_2_3_5_match_block_contract(typed, output_format): + frame = pd.DataFrame( + { + "age": np.linspace(18.0, 70.0, 80), + "income": np.linspace(25000.0, 90000.0, 80), + "tenure": np.linspace(0.0, 30.0, 80), + } + ) + requests = { + "age": {"method": "rbf", "output_dim": 2}, + "income": {"method": "rbf", "output_dim": 3}, + "tenure": {"method": "rbf", "output_dim": 5}, + } + preprocessor = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + target_aware=False, + placement_strategy="uniform", + scaling="none", + output_structure="blocks", + output_format=output_format, + ) + Pipeline([("preprocessor", preprocessor)]).fit(frame) + + _assert_block_layout(preprocessor, frame) + assert preprocessor.output_dims_ == {"age": 2, "income": 3, "tenure": 5} + assert preprocessor.total_output_dim_ == 10 + assert get_output_slices(preprocessor.column_transformer_) == [ + ("num_age", 0, 2), + ("num_income", 2, 3), + ("num_tenure", 5, 5), + ] + blocks = preprocessor.transform(frame) + assert isinstance(blocks, dict) + assert {name: np.shape(block) for name, block in blocks.items()} == { + "num_age": (80, 2), + "num_income": (80, 3), + "num_tenure": (80, 5), + } + + @pytest.mark.parametrize("output_format", ["dense", "sparse"]) def test_language_embedding_block_layout(layout_data, monkeypatch, output_format): frame, _ = layout_data From 22dbb75f24f76e0e68994947050bd89bd95c5ded Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 16 Nov 2026 15:12:47 +0100 Subject: [PATCH 31/86] test(config): verify structured cross-fitting contracts --- tests/core/test_cross_fitted.py | 217 ++++++++++++++++++++++++++++++++ 1 file changed, 217 insertions(+) diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index 2d750ab..c483c24 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -807,6 +807,223 @@ def test_wrapped_preprocessor_keeps_the_separate_state_missing_branch(array_with np.testing.assert_array_equal(out[:, columns], np.column_stack((expected, np.isnan(X[:, 0]).astype(float)))) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("missing_policy", [None, "impute_with_indicator", "separate_state"]) +def test_structured_cross_fitting_refits_only_target_representation( + array_with_one_missing_value, monkeypatch, typed, missing_policy +): + import pandas as pd + from sklearn.base import clone + from sklearn.pipeline import FeatureUnion, Pipeline + + from pretab import Preprocessor, RepresentationConfig + + values, target = array_with_one_missing_value + frame = pd.DataFrame(values, columns=pd.Index(["supervised", "fixed"]), index=np.arange(len(values)) * 3 + 5) + frame["city"] = np.resize(["a", "b", "c"], len(frame)) + frame.loc[frame.index[7], "city"] = "rare" + requests = { + "supervised": { + "method": "rbf", + "output_dim": 3, + "target_aware": True, + "placement_strategy": "cart", + "params": {"gamma": 0.25}, + }, + "fixed": { + "method": "rbf", + "output_dim": 5, + "target_aware": False, + "placement_strategy": "uniform", + "params": {"gamma": 0.75}, + }, + "city": {"method": "one-hot", "params": {"drop": "first", "sparse_output": False}}, + } + wrapped = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + missing_policy=missing_policy, + random_state=0, + ) + reference = clone(wrapped) + assert isinstance(reference, Preprocessor) + reference.fit(frame, target) + folds = [] + original = Preprocessor._cross_fit_fold + + def record_fold(fitted, train_frame, train_target): + fold = original(fitted, train_frame, train_target) + folds.append(fold) + return fold + + monkeypatch.setattr(Preprocessor, "_cross_fit_fold", record_fold) + cross_fitted = CrossFittedTransformer(wrapped, n_folds=5, random_state=0) + out = cross_fitted.fit_transform(frame, target) + fitted = cross_fitted.estimator_ + assert isinstance(fitted, Preprocessor) + full = np.asarray(cross_fitted.transform(frame)) + np.testing.assert_array_equal(full, reference.transform(frame)) + assert len(folds) == 5 + indicator = int(missing_policy is not None) + separate = int(missing_policy == "separate_state") + assert fitted.output_dims_ == {"supervised": 3 + indicator, "fixed": 5 + separate, "city": 3 + separate} + assert out.shape == full.shape == (len(frame), 11 + indicator + 2 * separate) + all_blocks = fitted.column_transformer_.named_transformers_ + full_block = all_blocks["num_supervised"] + if indicator: + assert isinstance(full_block, FeatureUnion) + representation = dict(full_block.transformer_list)["representation"] + else: + representation = full_block + assert isinstance(representation, Pipeline) + for fold in folds: + fold_blocks = fold.column_transformer_.named_transformers_ + fold_block = fold_blocks["num_supervised"] + if indicator: + assert isinstance(fold_block, FeatureUnion) + assert dict(fold_block.transformer_list)["missing"] is dict(full_block.transformer_list)["missing"] + fold_representation = dict(fold_block.transformer_list)["representation"] + else: + fold_representation = fold_block + assert isinstance(fold_representation, Pipeline) + assert fold_representation.named_steps["imputer"] is representation.named_steps["imputer"] + assert fold_representation.named_steps["minmax"] is representation.named_steps["minmax"] + assert fold_representation.named_steps["rbf"] is not representation.named_steps["rbf"] + assert fold_representation.named_steps["rbf"].output_dim == 3 + assert fold_representation.named_steps["rbf"].gamma == 0.25 + assert fold_blocks["num_fixed"] is all_blocks["num_fixed"] + assert fold_blocks["cat_city"] is all_blocks["cat_city"] + assert fold.output_dims_ == fitted.output_dims_ + np.testing.assert_array_equal(fold.get_feature_names_out(), fitted.get_feature_names_out()) + supervised = [ + record.output_index + for record in fitted.get_feature_lineage() + if record.source_features == ("supervised",) and record.uses_target + ] + assert len(supervised) == 3 + expected = _refit_representation_per_fold(representation, frame[["supervised"]], target) + np.testing.assert_array_equal(out[:, supervised], expected) + assert not np.allclose(out[:, supervised], full[:, supervised]) + unchanged = [index for index in range(out.shape[1]) if index not in supervised] + np.testing.assert_array_equal(out[:, unchanged], full[:, unchanged]) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("container", ["dense", "sparse", "auto", "pandas", "polars"]) +def test_structured_cross_fitting_preserves_output_container(array_with_rare_category, typed, container): + import pandas as pd + from scipy import sparse + + from pretab import Preprocessor, RepresentationConfig + + polars = pytest.importorskip("polars") if container == "polars" else None + values, target = array_with_rare_category + frame = pd.DataFrame( + values, + columns=pd.Index(["signal", "count", "city"]), + index=pd.Index(np.arange(len(values))[::-1] * 3, name="row"), + ) + requests = { + "signal": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "city": {"method": "one-hot", "params": {"drop": "first"}}, + } + parameters = { + "feature_preprocessing": { + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + "random_state": 0, + "dtype": np.float32, + } + wrapped = Preprocessor(output_format=container if container in {"sparse", "auto"} else "dense", **parameters) + if container in {"pandas", "polars"}: + wrapped.set_output(transform=container) + cross_fitted, out = _cross_fit(wrapped, frame, target) + full = cross_fitted.transform(frame) + assert type(out) is type(full) + if container == "sparse": + assert sparse.isspmatrix_csr(out) + if sparse.issparse(out): + assert sparse.issparse(full) + assert out.format == full.format == "csr" + out_values = out.toarray() + elif isinstance(out, pd.DataFrame): + assert isinstance(full, pd.DataFrame) + pd.testing.assert_index_equal(out.index, frame.index) + pd.testing.assert_index_equal(out.columns, full.columns) + assert out.columns.tolist() == cross_fitted.get_feature_names_out().tolist() + assert out.dtypes.equals(full.dtypes) + out_values = out.to_numpy() + elif container == "polars": + assert polars is not None + assert isinstance(out, polars.DataFrame) + assert out.columns == full.columns == cross_fitted.get_feature_names_out().tolist() + assert out.schema == full.schema + out_values = out.to_numpy() + else: + assert isinstance(out, np.ndarray) + out_values = out + _, dense = _cross_fit(Preprocessor(**parameters), frame, target) + assert out_values.shape == (len(frame), 7) + assert out_values.dtype == np.float32 + np.testing.assert_array_equal(out_values, dense) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_structured_cross_fitting_checks_each_block_width(array_with_one_missing_value, monkeypatch, typed): + from pretab import Preprocessor, RepresentationConfig + from pretab.expansion.functional.rbf import RBFExpansionTransformer + + values, target = array_with_one_missing_value + requests = { + "feature_0": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "feature_1": { + "method": "rbf", + "output_dim": 5, + "target_aware": False, + "placement_strategy": "uniform", + }, + } + original = RBFExpansionTransformer.fit + + def change_fold_width(estimator, fold_values, fold_target=None): + if len(fold_values) < len(values) and estimator.gamma == 0.25: + estimator.set_params(output_dim=2) + return original(estimator, fold_values, fold_target) + + monkeypatch.setattr(RBFExpansionTransformer, "fit", change_fold_width) + wrapped = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + random_state=0, + ) + with pytest.raises( + IncompatibleParamsError, + match="fixed output width for block 'num_feature_0'; expected 3, got 2", + ) as error: + _cross_fit(wrapped, values, target) + assert "same columns on every fold" in str(error.value) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_structured_cross_fitting_still_rejects_dictionary_output(integer_array, typed): + from pretab import Preprocessor, RepresentationConfig + + values, target = integer_array + settings = {"method": "rbf", "output_dim": 3} + wrapped = Preprocessor( + feature_preprocessing={"feature_0": RepresentationConfig.from_dict(settings) if typed else settings}, + output_structure="blocks", + random_state=0, + ) + with pytest.raises(IncompatibleParamsError, match="dict of blocks"): + _cross_fit(wrapped, values, target) + + # --- DataFrame input is passed through (issue #58) -------------------------------- From 72ec2568302a8e7f2b6724e69329a01465bfaba2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 16 Nov 2026 19:51:54 +0100 Subject: [PATCH 32/86] test(config): verify structured inputs and feature order --- tests/integration/test_column_labels.py | 87 ++++++++++++++++++++++++- tests/integration/test_polars_input.py | 58 ++++++++++++++++- 2 files changed, 143 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_column_labels.py b/tests/integration/test_column_labels.py index 798efab..504d6e9 100644 --- a/tests/integration/test_column_labels.py +++ b/tests/integration/test_column_labels.py @@ -18,7 +18,7 @@ from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline -from pretab import Preprocessor +from pretab import Preprocessor, RepresentationConfig from pretab.compose.inspection import refit_block_representation from pretab.core.supervised import CrossFittedTransformer from pretab.exceptions import PretabDataError @@ -38,6 +38,91 @@ def _blocks(out): return cast("dict[str, np.ndarray]", out) +@pytest.mark.parametrize("input_kind", ["pandas", "numpy", "polars"]) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("reverse_settings", [False, True], ids=["forward", "reversed"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_mixed_structured_inputs_keep_feature_order(input_kind, typed, reverse_settings, output_format): + from scipy import sparse + + frame = pd.DataFrame( + { + "feature_0": np.resize([3, 1, 2, 1], 80), + "feature_1": np.arange(18, 98), + "feature_2": np.resize([1, 0], 80), + "feature_3": np.arange(80), + "feature_4": np.resize([10, 20, 30, 10], 80), + } + ) + settings = { + "feature_0": "one-hot", + "feature_1": {"method": "rbf", "output_dim": 2, "params": {"gamma": 0.25}}, + "feature_2": "int", + "feature_3": "rbf", + "feature_4": {"method": "one-hot", "params": {"drop": "first", "sparse_output": False}}, + } + parameters = { + "numerical_method": "none", + "output_dim": 3, + "target_aware": False, + "placement_strategy": "uniform", + "scaling": "none", + "cat_cutoff": 5, + "random_state": 17, + } + reference = Preprocessor(feature_preprocessing=settings, **parameters).fit(frame) + expected = reference.transform(frame, return_array=True) + entries = list(settings.items())[::-1] if reverse_settings else list(settings.items()) + overrides = { + feature: RepresentationConfig.from_dict(options) if typed and isinstance(options, dict) else options + for feature, options in entries + } + if input_kind == "polars": + polars = pytest.importorskip("polars") + incoming = polars.DataFrame(frame.to_dict(orient="list")) + elif input_kind == "numpy": + incoming = frame.to_numpy() + else: + incoming = frame + original = deepcopy(incoming) + preprocessor = Preprocessor(feature_preprocessing=overrides, output_format=output_format, **parameters) + transformed = preprocessor.fit_transform(incoming) + assert not isinstance(transformed, dict) + assert sparse.issparse(transformed) == (output_format == "sparse") + actual = transformed.toarray() if sparse.issparse(transformed) else np.asarray(transformed) + np.testing.assert_array_equal(actual, expected) + assert preprocessor.numerical_features_ == ["feature_1", "feature_3"] + assert preprocessor.categorical_features_ == ["feature_0", "feature_2", "feature_4"] + dimensions = {"feature_1": 2, "feature_3": 3, "feature_0": 3, "feature_2": 1, "feature_4": 2} + assert preprocessor.output_dims_ == dimensions + assert list(preprocessor.output_dims_) == list(dimensions) + assert preprocessor.total_output_dim_ == 11 + assert preprocessor.get_feature_info(verbose=False) == reference.get_feature_info(verbose=False) + assert preprocessor.get_feature_lineage() == reference.get_feature_lineage() + np.testing.assert_array_equal(preprocessor.get_feature_names_out(), reference.get_feature_names_out()) + blocks = preprocessor.transform(incoming, return_array=False) + assert isinstance(blocks, dict) + assert list(blocks) == ["num_feature_1", "num_feature_3", "cat_feature_0", "cat_feature_2", "cat_feature_4"] + assert [np.shape(block)[1] for block in blocks.values()] == list(dimensions.values()) + stacked = np.hstack([block.toarray() if sparse.issparse(block) else np.asarray(block) for block in blocks.values()]) + np.testing.assert_array_equal(stacked, expected) + if isinstance(incoming, np.ndarray): + with pytest.raises(PretabDataError, match="X has 4 features, but Preprocessor is expecting 5"): + preprocessor.transform(incoming[:, :-1]) + np.testing.assert_array_equal(incoming, original) + else: + if isinstance(incoming, pd.DataFrame): + reordered = incoming.iloc[:, ::-1] + assert isinstance(original, pd.DataFrame) + pd.testing.assert_frame_equal(incoming, original) + else: + reordered = incoming.select(incoming.columns[::-1]) + assert incoming.equals(original) + result = preprocessor.transform(reordered, return_array=True) + assert not isinstance(result, dict) + np.testing.assert_array_equal(result.toarray() if sparse.issparse(result) else np.asarray(result), expected) + + @pytest.fixture(params=["string", "integer"]) def input_route_frame(request): frame = pd.DataFrame( diff --git a/tests/integration/test_polars_input.py b/tests/integration/test_polars_input.py index 0e27e55..b7e932c 100644 --- a/tests/integration/test_polars_input.py +++ b/tests/integration/test_polars_input.py @@ -12,7 +12,7 @@ import pandas as pd import pytest -from pretab import Preprocessor +from pretab import Preprocessor, RepresentationConfig from pretab.exceptions import DataWarning pl = pytest.importorskip("polars") @@ -81,6 +81,62 @@ def test_polars_input_matches_pandas_input(frames, params): np.testing.assert_allclose(np.asarray(from_polars.transform(reordered)), expected) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_mixed_structured_inputs_preserve_polars_column_types(frames, typed, output_format): + from scipy import sparse + + pandas_frame, polars_frame, _ = frames + original = polars_frame.clone() + settings = { + "flag": "int", + "city": {"method": "one-hot", "params": {"drop": "first"}}, + "visits": "rbf", + "plan": "one-hot", + "income": {"method": "rbf", "output_dim": 2, "params": {"gamma": 0.25}}, + } + options = { + "feature_preprocessing": { + feature: RepresentationConfig.from_dict(value) if typed and isinstance(value, dict) else value + for feature, value in settings.items() + }, + "numerical_method": "none", + "output_dim": 3, + "target_aware": False, + "placement_strategy": "uniform", + "scaling": "none", + "random_state": 17, + "output_format": output_format, + } + from_pandas = Preprocessor(**options).fit(pandas_frame) + from_polars = Preprocessor(**options).fit(polars_frame) + expected = from_pandas.transform(pandas_frame) + assert not isinstance(expected, dict) + expected = expected.toarray() if sparse.issparse(expected) else np.asarray(expected) + assert from_polars.numerical_features_ == ["income", "visits"] + assert from_polars.categorical_features_ == ["rooms", "plan", "city", "flag"] + dimensions = {"income": 2, "visits": 3, "rooms": 1, "plan": 2, "city": 2, "flag": 1} + assert from_polars.output_dims_ == dimensions + assert list(from_polars.output_dims_) == list(dimensions) + assert from_polars.get_feature_info(verbose=False) == from_pandas.get_feature_info(verbose=False) + assert from_polars.get_feature_lineage() == from_pandas.get_feature_lineage() + np.testing.assert_array_equal(from_polars.get_feature_names_out(), from_pandas.get_feature_names_out()) + for preprocessor, incoming in ( + (from_polars, polars_frame.select(polars_frame.columns[::-1])), + (from_polars, pandas_frame.iloc[:, ::-1]), + (from_pandas, polars_frame.select(polars_frame.columns[::-1])), + ): + result = preprocessor.transform(incoming) + assert not isinstance(result, dict) + assert sparse.issparse(result) == (output_format == "sparse") + np.testing.assert_array_equal(result.toarray() if sparse.issparse(result) else np.asarray(result), expected) + blocks = preprocessor.transform(incoming, return_array=False) + assert isinstance(blocks, dict) + assert list(blocks) == ["num_income", "num_visits", "cat_rooms", "cat_plan", "cat_city", "cat_flag"] + assert [np.shape(block)[1] for block in blocks.values()] == list(dimensions.values()) + assert polars_frame.equals(original) + + def test_polars_input_with_polars_output(frames): _, polars_frame, y = frames pre = Preprocessor(numerical_method="minmax").set_output(transform="polars").fit(polars_frame, y) From 3d2b5e2687baf511f0fc88f4039ef3ed6d5b79aa Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 16 Nov 2026 21:39:26 +0100 Subject: [PATCH 33/86] docs(config): demonstrate per-feature configuration lifecycle --- docs/tutorials/sklearn_pipeline.md | 142 ++++++++++++- examples/per-feature-configuration.ipynb | 213 +++++++++++++++++++ tests/doc_snippets/test_tutorial_snippets.py | 24 ++- 3 files changed, 374 insertions(+), 5 deletions(-) create mode 100644 examples/per-feature-configuration.ipynb diff --git a/docs/tutorials/sklearn_pipeline.md b/docs/tutorials/sklearn_pipeline.md index 0f5f343..5a9c966 100644 --- a/docs/tutorials/sklearn_pipeline.md +++ b/docs/tutorials/sklearn_pipeline.md @@ -5,7 +5,9 @@ they drop straight into a `ColumnTransformer` and `Pipeline`, and work with `cross_val_score`, `GridSearchCV`, and every other `sklearn` utility. The high-level `Preprocessor` composes the same way (it returns a single stacked array by default), but this page focuses on wiring each column's transformer by hand for fine-grained, per-transformer -control: addressable hyperparameters (`step__param`), one estimator per column. +control: addressable hyperparameters (`step__param`), one estimator per column. The +[mixed-column example](#configure-mixed-columns-with-preprocessor) then uses `Preprocessor` +to configure, inspect and save the fitted preprocessing step. This tutorial builds the regression task from the [nonlinear regression tutorial](nonlinear_regression.md) as a single, self-contained @@ -108,6 +110,144 @@ best CV R2: 0.949 Every pretab transformer participates in the search grid just like a native `sklearn` step. +## Configure mixed columns with Preprocessor + +Run this example in the +{download}`companion notebook <../../examples/per-feature-configuration.ipynb>`. + +`Preprocessor` can select column types and build the preprocessing step for you. +This independent example uses three numerical columns, a Boolean column and a +string category. Keep their dtypes in a `DataFrame`: Booleans are categorical, +while these floating-point columns are numerical. + +```python +import json + +import numpy as np +import pandas as pd +from sklearn.linear_model import Ridge +from sklearn.pipeline import Pipeline + +from pretab import Preprocessor, RepresentationConfig + +frame = pd.DataFrame({ + "age": np.linspace(18.0, 70.0, 80), + "income": np.linspace(25000.0, 90000.0, 80), + "tenure": np.linspace(0.0, 30.0, 80), + "active": [True, False] * 40, + "city": ["Oslo", "Lima", "Perth", "Oslo"] * 20, +}) +target = 0.4 * frame["age"] + 2.0 * frame["active"] +``` + +### Request local settings + +Method strings, mappings and immutable `RepresentationConfig` values can coexist. +The three numerical columns use RBF expansions with different widths. The Boolean +uses integer encoding, and the city encoder drops its first learned category. +Override declaration order does not determine output order. + +```python +pre = Preprocessor( + numerical_method="none", + output_dim=7, + target_aware=False, + placement_strategy="uniform", + scaling="none", + output_format="dense", + random_state=17, + feature_preprocessing={ + "city": {"method": "one-hot", "params": {"drop": "first"}}, + "tenure": RepresentationConfig(method="rbf", output_dim=5), + "active": "int", + "income": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "age": RepresentationConfig(method="RBF", output_dim=2), + }, +) +requested = pre.get_params(deep=False) +assert requested["output_dim"] == 7 +assert requested["feature_preprocessing"]["age"].output_dim == 2 +``` + +### Read the resolved configuration + +`get_resolved_config()` normalizes aliases and applies configuration precedence +without fitting. The constructor-wide width remains seven, but each numerical +override supplies its own width. This report does not contain learned categories +or guarantee the realized output width. + +```python +resolved = pre.get_resolved_config() +assert resolved["output_dim"] == 7 +assert resolved["feature_preprocessing"]["age"]["method"] == "rbf" +assert resolved["feature_preprocessing"]["age"]["output_dim"] == 2 +assert resolved["feature_preprocessing"]["income"]["params"]["gamma"] == 0.25 +assert not hasattr(pre, "output_dims_") +``` + +### Inspect the fitted state and width + +Fit inside the pipeline so training and prediction use the same preprocessing. +The fitted dimensions account for the learned city vocabulary and its dropped +category, not just the requested RBF widths. + +```python +mixed_model = Pipeline([("pre", pre), ("ridge", Ridge(alpha=1.0))]) +mixed_model.fit(frame, target) + +assert pre.numerical_features_ == ["age", "income", "tenure"] +assert pre.categorical_features_ == ["active", "city"] +expected_dims = {"age": 2, "income": 3, "tenure": 5, "active": 1, "city": 2} +assert pre.output_dims_ == expected_dims +assert list(pre.output_dims_) == list(expected_dims) +assert pre.total_output_dim_ == 13 + +numerical, categorical, embeddings = pre.get_feature_info(verbose=False) +assert {name: info["dimension"] for name, info in numerical.items()} == { + "age": 2, "income": 3, "tenure": 5, +} +assert {name: info["dimension"] for name, info in categorical.items()} == { + "active": 1, "city": 2, +} +assert embeddings == {} +matrix = pre.transform(frame, return_array=True) +assert isinstance(matrix, np.ndarray) +assert matrix.shape == (80, 13) +assert pre.get_feature_names_out().shape == (13,) +predictions = mixed_model.predict(frame) +assert isinstance(predictions, np.ndarray) +assert predictions.shape == (80,) +``` + +```{important} +Use fitted attributes and inspection methods to size downstream inputs. Numerical +outputs precede categorical outputs, with source-column order within each kind. +Changing constructor parameters after fitting changes the request, not the +learned transformers. Fit again to apply a new request. +``` + +### Save and restore the fitted preprocessor + +`to_spec()` captures the fitted preprocessing state, including the typed local +settings. Pass the JSON-decoded specification to `from_spec()` to restore it +without fitting again. This saves the preprocessing step, not the Ridge model. + +```python +spec = json.loads(json.dumps(pre.to_spec(), allow_nan=False)) +replayed = Preprocessor.from_spec(spec) + +assert replayed.output_dims_ == expected_dims +assert replayed.total_output_dim_ == 13 +np.testing.assert_array_equal(replayed.get_feature_names_out(), pre.get_feature_names_out()) +np.testing.assert_array_equal(replayed.transform(frame, return_array=True), matrix) +assert replayed.fingerprint_ == pre.fingerprint_ +``` + +For precedence and copy semantics, see +[Structured per-feature configuration](../core_concepts/configuration.md#structured-per-feature-configuration). +For artifact trust and persistence details, see +[Reproducibility](../core_concepts/reproducibility.md). + ## When to use which - **Standalone transformers** (this page) compose inside one `Pipeline` and integrate with diff --git a/examples/per-feature-configuration.ipynb b/examples/per-feature-configuration.ipynb new file mode 100644 index 0000000..f01bfb6 --- /dev/null +++ b/examples/per-feature-configuration.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b5803dce", + "metadata": {}, + "source": [ + "# Per-feature configuration and fitted widths\n", + "\n", + "Configure numerical, Boolean and categorical columns, inspect actual fitted widths, and restore the preprocessing state from JSON. The same code appears in the [pipeline tutorial](../docs/tutorials/sklearn_pipeline.md#configure-mixed-columns-with-preprocessor).\n", + "\n", + "## Training data\n", + "\n", + "Keep column dtypes in a DataFrame. The three floating-point columns are numerical; `active` and `city` are categorical. The chosen RBF placement does not use the target." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "77b32509", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.pipeline import Pipeline\n", + "\n", + "from pretab import Preprocessor, RepresentationConfig\n", + "\n", + "frame = pd.DataFrame({\n", + " \"age\": np.linspace(18.0, 70.0, 80),\n", + " \"income\": np.linspace(25000.0, 90000.0, 80),\n", + " \"tenure\": np.linspace(0.0, 30.0, 80),\n", + " \"active\": [True, False] * 40,\n", + " \"city\": [\"Oslo\", \"Lima\", \"Perth\", \"Oslo\"] * 20,\n", + "})\n", + "target = 0.4 * frame[\"age\"] + 2.0 * frame[\"active\"]" + ] + }, + { + "cell_type": "markdown", + "id": "51327e9b", + "metadata": {}, + "source": [ + "## Request local settings\n", + "\n", + "Mix method strings, mappings and immutable `RepresentationConfig` values. RBF widths are local to each numerical column. The Boolean uses integer encoding; the city encoder drops its first learned category. The deliberately reversed override map does not set output order.\n", + "\n", + "`get_params()` reads the constructor request, including the global width of seven." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "2887c806", + "metadata": {}, + "outputs": [], + "source": [ + "pre = Preprocessor(\n", + " numerical_method=\"none\",\n", + " output_dim=7,\n", + " target_aware=False,\n", + " placement_strategy=\"uniform\",\n", + " scaling=\"none\",\n", + " output_format=\"dense\",\n", + " random_state=17,\n", + " feature_preprocessing={\n", + " \"city\": {\"method\": \"one-hot\", \"params\": {\"drop\": \"first\"}},\n", + " \"tenure\": RepresentationConfig(method=\"rbf\", output_dim=5),\n", + " \"active\": \"int\",\n", + " \"income\": {\"method\": \"rbf\", \"output_dim\": 3, \"params\": {\"gamma\": 0.25}},\n", + " \"age\": RepresentationConfig(method=\"RBF\", output_dim=2),\n", + " },\n", + ")\n", + "requested = pre.get_params(deep=False)\n", + "assert requested[\"output_dim\"] == 7\n", + "assert requested[\"feature_preprocessing\"][\"age\"].output_dim == 2" + ] + }, + { + "cell_type": "markdown", + "id": "9fba5c2e", + "metadata": {}, + "source": [ + "## Read the resolved configuration\n", + "\n", + "`get_resolved_config()` applies precedence and normalizes aliases without fitting. It reports settings, not learned categories or realized output widths. The global width stays seven while the local age width is two." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "17994994", + "metadata": {}, + "outputs": [], + "source": [ + "resolved = pre.get_resolved_config()\n", + "assert resolved[\"output_dim\"] == 7\n", + "assert resolved[\"feature_preprocessing\"][\"age\"][\"method\"] == \"rbf\"\n", + "assert resolved[\"feature_preprocessing\"][\"age\"][\"output_dim\"] == 2\n", + "assert resolved[\"feature_preprocessing\"][\"income\"][\"params\"][\"gamma\"] == 0.25\n", + "assert not hasattr(pre, \"output_dims_\")" + ] + }, + { + "cell_type": "markdown", + "id": "2efc8799", + "metadata": {}, + "source": [ + "## Inspect fitted state and actual widths\n", + "\n", + "Fit inside the pipeline so training and prediction use the same preprocessing. The fitted widths are:\n", + "\n", + "| Column | Width |\n", + "| --- | ---: |\n", + "| `age` | 2 |\n", + "| `income` | 3 |\n", + "| `tenure` | 5 |\n", + "| `active` | 1 |\n", + "| `city` | 2 |\n", + "\n", + "The city width depends on its three learned categories and `drop=\"first\"`. Numerical outputs precede categorical outputs, in source order within each kind. Use fitted dimensions to size downstream inputs. Changing a request after fitting does not refit the learned transformers." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "b5cf1598", + "metadata": {}, + "outputs": [], + "source": [ + "mixed_model = Pipeline([(\"pre\", pre), (\"ridge\", Ridge(alpha=1.0))])\n", + "mixed_model.fit(frame, target)\n", + "\n", + "assert pre.numerical_features_ == [\"age\", \"income\", \"tenure\"]\n", + "assert pre.categorical_features_ == [\"active\", \"city\"]\n", + "expected_dims = {\"age\": 2, \"income\": 3, \"tenure\": 5, \"active\": 1, \"city\": 2}\n", + "assert pre.output_dims_ == expected_dims\n", + "assert list(pre.output_dims_) == list(expected_dims)\n", + "assert pre.total_output_dim_ == 13\n", + "\n", + "numerical, categorical, embeddings = pre.get_feature_info(verbose=False)\n", + "assert {name: info[\"dimension\"] for name, info in numerical.items()} == {\n", + " \"age\": 2, \"income\": 3, \"tenure\": 5,\n", + "}\n", + "assert {name: info[\"dimension\"] for name, info in categorical.items()} == {\n", + " \"active\": 1, \"city\": 2,\n", + "}\n", + "assert embeddings == {}\n", + "matrix = pre.transform(frame, return_array=True)\n", + "assert isinstance(matrix, np.ndarray)\n", + "assert matrix.shape == (80, 13)\n", + "assert pre.get_feature_names_out().shape == (13,)\n", + "predictions = mixed_model.predict(frame)\n", + "assert isinstance(predictions, np.ndarray)\n", + "assert predictions.shape == (80,)" + ] + }, + { + "cell_type": "markdown", + "id": "9532ddb0", + "metadata": {}, + "source": [ + "## Save and restore fitted preprocessing\n", + "\n", + "`to_spec()` captures fitted preprocessing state, including typed local settings. Round-trip it through strict JSON, then use `from_spec()` without fitting again. This saves the preprocessing step, not the Ridge model.\n", + "\n", + "For persistence and artifact trust details, see the [reproducibility guide](../docs/core_concepts/reproducibility.md)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "9e4a8347", + "metadata": {}, + "outputs": [], + "source": [ + "spec = json.loads(json.dumps(pre.to_spec(), allow_nan=False))\n", + "replayed = Preprocessor.from_spec(spec)\n", + "\n", + "assert replayed.output_dims_ == expected_dims\n", + "assert replayed.total_output_dim_ == 13\n", + "np.testing.assert_array_equal(replayed.get_feature_names_out(), pre.get_feature_names_out())\n", + "np.testing.assert_array_equal(replayed.transform(frame, return_array=True), matrix)\n", + "assert replayed.fingerprint_ == pre.fingerprint_" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index 3ddc7af..146f6e7 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -1,12 +1,13 @@ """Executes the python code fences in the tutorial pages so API drift breaks CI instead of the docs quietly going stale. -Notebook execution (``myst-nb`` / ``nbmake``) is intentionally out of scope for -1.0; this is the lighter-weight alternative: each tutorial's ```python blocks run -in one shared namespace, in source order, exactly as written on the page. Blocks -that only show expected console output (```text fences) are not touched. +Each tutorial's ```python blocks run in one shared namespace, in source order, +exactly as written on the page. Blocks that only show expected console output +(```text fences) are not touched. The companion notebook is kept in sync with its +executed tutorial section without notebook-rendering dependencies in CI. """ +import json import re from pathlib import Path @@ -85,3 +86,18 @@ def test_tutorial_code_runs(tutorial, section): exec(compile(source, str(tutorial), "exec"), namespace) # noqa: S102 except Exception as exc: raise AssertionError(f"{tutorial.name}:{start_line} raised {exc!r}") from exc + + +def test_per_feature_notebook_matches_tutorial(): + notebook_path = ROOT / "examples" / "per-feature-configuration.ipynb" + notebook = json.loads(notebook_path.read_text(encoding="utf-8")) + notebook_sources = ["".join(cell["source"]).strip() for cell in notebook["cells"] if cell["cell_type"] == "code"] + tutorial_sources = [ + source.strip() + for _, source in _code_blocks( + TUTORIALS_DIR / "sklearn_pipeline.md", "Configure mixed columns with Preprocessor" + ) + ] + assert notebook["nbformat"] == 4 + assert len(notebook_sources) == 5 + assert notebook_sources == tutorial_sources From 52e9f462ed5e6f97262e12b3923862f7896a9cf9 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 16 Nov 2026 23:54:58 +0100 Subject: [PATCH 34/86] refactor(compose): share read-only fitted block layout --- pretab/compose/inspection.py | 59 +++++++++++++++++++++++--------- pretab/compose/serialize.py | 10 +++--- pretab/preprocessor.py | 23 +++++++------ tests/compose/test_inspection.py | 56 ++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+), 32 deletions(-) diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index e1ab0b0..ab9e1ed 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -8,6 +8,8 @@ """ import copy +from collections.abc import Iterator +from dataclasses import dataclass from typing import Any, cast import numpy as np @@ -54,6 +56,30 @@ def block_name(step_name, columns): return step_name if block is None else f"{block[0]}_{block[1]}" +@dataclass(frozen=True) +class _FittedBlock: + """Read-only block metadata retaining the fitted transformer and selector references.""" + + step_name: str + transformer: Any + columns: Any + _column_transformer: Any + + @property + def public_name(self) -> str: + return block_name(self.step_name, self.columns) + + @property + def span(self) -> slice: + return self._column_transformer.output_indices_[self.step_name] + + +def _iter_fitted_blocks(column_transformer) -> Iterator[_FittedBlock]: + """Yield every fitted block in order, leaving filtering and span access to callers.""" + for name, transformer, columns in column_transformer.transformers_: + yield _FittedBlock(name, transformer, columns, column_transformer) + + def get_output_slices(column_transformer): """Return ordered ``(name, start, width)`` spans for each output block. @@ -63,16 +89,16 @@ def get_output_slices(column_transformer): """ indices = column_transformer.output_indices_ slices = [] - for name, transformer, columns in column_transformer.transformers_: - if transformer == "drop": + for block in _iter_fitted_blocks(column_transformer): + if block.transformer == "drop" or block.step_name not in indices: continue - span = indices.get(name) + span = block.span if span is None: continue width = span.stop - span.start if width == 0: continue - slices.append((block_name(name, columns), span.start, width)) + slices.append((block.public_name, span.start, width)) return slices @@ -93,7 +119,8 @@ def feature_names_out(column_transformer, input_features=None): rename = {str(label): str(name) for label, name in zip(fitted_labels, input_features, strict=True)} raw_names = [] - for name, transformer, columns in column_transformer.transformers_: + for block in _iter_fitted_blocks(column_transformer): + name, transformer, columns = block.step_name, block.transformer, block.columns if transformer == "drop" or len(columns) == 0: continue labels = [rename[str(column)] for column in columns] @@ -144,9 +171,9 @@ def clean_feature_names(column_transformer, names, *, rename=None): """ rename = rename or {} step_to_columns = { - name: [rename.get(str(column), column) for column in columns] - for name, _transformer, columns in column_transformer.transformers_ - if name != "remainder" and len(columns) == 1 + block.step_name: [rename.get(str(column), column) for column in block.columns] + for block in _iter_fitted_blocks(column_transformer) + if block.step_name != "remainder" and len(block.columns) == 1 } cleaned = [] for raw in names: @@ -214,14 +241,11 @@ def build_feature_info(column_transformer, *, embeddings, embedding_dimensions): else {} ) - for ( - name, - transformer_pipeline, - columns, - ) in column_transformer.transformers_: + for block in _iter_fitted_blocks(column_transformer): + name, transformer_pipeline, columns = block.step_name, block.transformer, block.columns if transformer_pipeline == "drop" or len(columns) == 0: continue - span = column_transformer.output_indices_[name] + span = block.span dimension = span.stop - span.start separate_state = _separate_state_branches(transformer_pipeline) if separate_state is not None: @@ -416,8 +440,11 @@ def build_feature_lineage(column_transformer): output_indices = column_transformer.output_indices_ feature_names_in = getattr(column_transformer, "feature_names_in_", None) records = [] - for name, transformer, columns in column_transformer.transformers_: - span = output_indices.get(name) + for block in _iter_fitted_blocks(column_transformer): + name, transformer, columns = block.step_name, block.transformer, block.columns + if name not in output_indices: + continue + span = block.span if span is None: continue width = span.stop - span.start diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 0bc14d3..0930c07 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -40,7 +40,7 @@ from ..placement.base import PlacementResult from ..preprocessing.floats import NoTransformer, ToFloatTransformer from .config import RepresentationConfig -from .inspection import representation_leaf +from .inspection import _iter_fitted_blocks, representation_leaf from .registry import TransformerSpec SCHEMA_VERSION = 1 @@ -311,14 +311,14 @@ def _representation_summary(preprocessor) -> list: column_transformer = getattr(preprocessor, "column_transformer_", None) if column_transformer is None: return summary - for name, transformer, columns in column_transformer.transformers_: - if name == "remainder": + for block in _iter_fitted_blocks(column_transformer): + if block.step_name == "remainder": continue - leaf = representation_leaf(transformer) + leaf = representation_leaf(block.transformer) spec_fn = getattr(leaf, "get_representation_spec", None) if spec_fn is None: continue - block_columns = [str(col) for col in columns] + block_columns = [str(col) for col in block.columns] # A leaf with more inputs than its block has columns (one fitted behind # the imputer's built-in missing indicator, add_missing_indicator=True) # names its own inputs. diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 4f00af3..4360eb2 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -24,7 +24,7 @@ with_string_labels, ) from .compose.inspection import ( - block_name, + _iter_fitted_blocks, block_uses_target, build_feature_info, build_feature_lineage, @@ -1015,20 +1015,20 @@ def output_dims_(self) -> dict: """ check_is_fitted(self) column_transformer = self.column_transformer_ - output_indices = column_transformer.output_indices_ input_labels = self._input_labels() dims: dict = {} - for name, _transformer, columns in column_transformer.transformers_: - span = output_indices[name] + for block in _iter_fitted_blocks(column_transformer): + span = block.span width = span.stop - span.start if width == 0: continue - if name == "remainder": + if block.step_name == "remainder": # Passthrough columns: one output column per untransformed feature. for full in column_transformer.get_feature_names_out()[span]: feature = full.split("__", 1)[-1] if "__" in full else full dims[feature] = dims.get(feature, 0) + 1 else: + columns = block.columns dims[input_labels.get(columns[0], columns[0])] = width return dims @@ -1176,16 +1176,17 @@ def _cross_fit_fold(self, X, y): X_ct = self._column_transformer_input(self._align_input(X)) column_transformer = copy.copy(self.column_transformer_) column_transformer.transformers_ = [] - for name, transformer, columns in self.column_transformer_.transformers_: + for block in _iter_fitted_blocks(self.column_transformer_): + name, transformer, columns = block.step_name, block.transformer, block.columns fold_transformer = transformer if name != "remainder" and block_uses_target(transformer): fold_transformer = refit_block_representation(transformer, X_ct[list(columns)], y) - span = self.column_transformer_.output_indices_[name] + span = block.span expected_width = span.stop - span.start width = len(fold_transformer.get_feature_names_out(list(columns))) if width != expected_width: raise IncompatibleParamsError( - f"Cross-fitting requires a fixed output width for block {block_name(name, columns)!r}; " + f"Cross-fitting requires a fixed output width for block {block.public_name!r}; " f"expected {expected_width}, got {width}. The block's width depends on the training rows; " "configure the representation to produce the same columns on every fold." ) @@ -1353,9 +1354,9 @@ def get_feature_info(self, verbose=True): def _log_internal_decisions(self): """Log fitted internal decisions (bins / knots / centers) at DEBUG.""" - for step_name, transformer, columns in self.column_transformer_.transformers_: - name = block_name(step_name, columns) - last_step = representation_leaf(transformer) + for block in _iter_fitted_blocks(self.column_transformer_): + name = block.public_name + last_step = representation_leaf(block.transformer) for attr in ( "thresholds_", "knots_", diff --git a/tests/compose/test_inspection.py b/tests/compose/test_inspection.py index 4d95607..cf7dc9b 100644 --- a/tests/compose/test_inspection.py +++ b/tests/compose/test_inspection.py @@ -1,6 +1,8 @@ """Unit tests for :mod:`pretab.compose.inspection`.""" import warnings +from types import SimpleNamespace +from typing import Any, cast from unittest.mock import Mock import numpy as np @@ -12,6 +14,7 @@ from pretab.compose.factory import build_column_transformer, get_categorical_transformer_steps from pretab.compose.inspection import ( + _iter_fitted_blocks, _locate_block_representation, block_uses_target, build_feature_info, @@ -129,6 +132,59 @@ def test_get_output_slices_are_ordered_and_named(fitted_ct): assert all(width >= 1 for _, _, width in slices) +def test_fitted_block_view_retains_entries_and_fitted_references(): + transformer = Mock(spec=["fit", "transform", "get_feature_names_out", "get_representation_spec"]) + columns = ["age__years"] + ct = SimpleNamespace( + transformers_=[ + ("num_0", transformer, columns), + ("cat_city", "drop", ["city"]), + ("empty", "passthrough", []), + ("unmapped", "passthrough", ["other"]), + ("remainder", "passthrough", [1]), + ], + output_indices_={ + "num_0": slice(0, 2), + "cat_city": slice(0, 0), + "empty": slice(2, 2), + "remainder": slice(2, 3), + }, + ) + original_blocks = ct.transformers_.copy() + original_indices = ct.output_indices_.copy() + + blocks = list(_iter_fitted_blocks(ct)) + + assert [block.step_name for block in blocks] == [entry[0] for entry in original_blocks] + for block, (_, fitted, selector) in zip(blocks, original_blocks, strict=True): + assert block.transformer is fitted + assert block.columns is selector + assert blocks[0].public_name == "num_age__years" + assert blocks[0].span is ct.output_indices_["num_0"] + with pytest.raises(AttributeError): + cast(Any, blocks[0]).step_name = "replacement" + with pytest.raises(KeyError, match="unmapped"): + _ = blocks[3].span + assert get_output_slices(ct) == [("num_age__years", 0, 2), ("remainder", 2, 1)] + assert ct.transformers_ == original_blocks + assert ct.output_indices_ == original_indices + assert transformer.mock_calls == [] + + +def test_fitted_block_view_does_not_eagerly_read_names_or_spans(): + columns = slice(0, 2) + transformer = object() + ct = SimpleNamespace(transformers_=[("joint", transformer, columns)]) + + block = next(_iter_fitted_blocks(ct)) + + assert block.step_name == "joint" + assert block.transformer is transformer + assert block.columns is columns + with pytest.raises(AttributeError, match="output_indices_"): + _ = block.span + + def test_build_feature_info_splits_numerical_and_categorical(fitted_ct): ct, _ = fitted_ct numerical, categorical, embeddings = build_feature_info(ct, embeddings=False, embedding_dimensions={}) From bca971dfe99fba5225cafef8e0b2e052150a004b Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 17 Nov 2026 00:57:29 +0100 Subject: [PATCH 35/86] feat(compose): declare grouped representation capabilities --- pretab/compose/registry.py | 18 +++++ tests/compose/test_registry_contract.py | 53 +++++++++++++ tests/integration/test_serialization.py | 26 ++++++ tests/regression/_snapshots/public_api.json | 87 +++++++++++++++++++++ 4 files changed, 184 insertions(+) diff --git a/pretab/compose/registry.py b/pretab/compose/registry.py index f197352..1433c97 100644 --- a/pretab/compose/registry.py +++ b/pretab/compose/registry.py @@ -126,6 +126,15 @@ class TransformerSpec: sparse_output : bool Whether the method can emit a sparse matrix (e.g. one-hot). Surfaced through :func:`pretab.list_representations`. + group_compatible : bool + Whether the method declares support for explicit column groups. + Independent of single-column ``preprocessor_compatible`` selection. + min_arity : int + Minimum declared group size, relevant only when ``group_compatible`` + is true. Does not constrain standalone transformer input dimensions. + max_arity : int or None + Maximum declared group size, or ``None`` for no declared upper bound. + Relevant only when ``group_compatible`` is true. """ name: str @@ -140,6 +149,9 @@ class TransformerSpec: optional_dependency: str | None = None periodic: bool = False sparse_output: bool = False + group_compatible: bool = False + min_arity: int = 1 + max_arity: int | None = 1 @property def is_numerical(self) -> bool: @@ -286,6 +298,9 @@ def _spec(name, cls, allowed_args=(), **kwargs): arity="multivariate", placement_strategies=_UNSUPERVISED_STRATEGIES, preprocessor_compatible=False, + group_compatible=True, + min_arity=2, + max_arity=None, ), # --- numerical: kernel-based thin-plate spline (knot-free, multivariate) --- _spec( @@ -294,6 +309,9 @@ def _spec(name, cls, allowed_args=(), **kwargs): ("n_components", "landmark_strategy", "rank_strategy", "random_state"), arity="multivariate", preprocessor_compatible=False, + group_compatible=True, + min_arity=2, + max_arity=None, ), # --- numerical: kernel-approximation feature maps (multivariate, standalone) --- _spec( diff --git a/tests/compose/test_registry_contract.py b/tests/compose/test_registry_contract.py index 8611fc5..bf298ef 100644 --- a/tests/compose/test_registry_contract.py +++ b/tests/compose/test_registry_contract.py @@ -64,6 +64,59 @@ def test_arity_valid(name, spec): assert spec.arity in _VALID_ARITY +@pytest.mark.parametrize("name, spec", _SPEC_ITEMS, ids=_SPEC_IDS) +def test_group_capabilities_are_explicit_and_independent_of_single_column_selection(name, spec): + expected = (True, 2, None) if name in {"tensorspline", "tprs"} else (False, 1, 1) + assert (spec.group_compatible, spec.min_arity, spec.max_arity) == expected + if spec.group_compatible: + assert spec.feature_kind == frozenset({"numerical"}) + assert spec.is_multivariate + assert spec.preprocessor_compatible is False + assert name not in NUMERICAL_METHODS + + +def test_legacy_positional_spec_uses_group_defaults(): + spec = TransformerSpec( + "legacy", + TRANSFORMER_REGISTRY["rbf"].transformer_cls, + ("gamma",), + frozenset({"numerical"}), + "multivariate", + "optional", + frozenset({"uniform", "cart"}), + True, + False, + None, + True, + True, + ) + + assert spec.name == "legacy" + assert spec.allowed_args == ("gamma",) + assert spec.is_multivariate + assert spec.target_aware_capable + assert spec.supports_adaptive_resolution + assert spec.preprocessor_compatible is False + assert spec.optional_dependency is None + assert spec.periodic and spec.sparse_output + assert (spec.group_compatible, spec.min_arity, spec.max_arity) == (False, 1, 1) + + +@pytest.mark.parametrize("name", ["tensorspline", "tprs", "rff", "nystroem"]) +@pytest.mark.parametrize("n_features", [1, 3]) +def test_group_arity_metadata_does_not_constrain_standalone_inputs(name, n_features): + data = np.random.default_rng(0).uniform(size=(40, n_features)) + options = {"output_dim": 4} if name == "tensorspline" else {"n_components": 4, "random_state": 0} + transformer = TRANSFORMER_REGISTRY[name].transformer_cls(**options) + + transformed = transformer.fit_transform(data) + + expected_width = 4**n_features if name == "tensorspline" else 4 + assert transformed.shape == (40, expected_width) + assert transformer.n_features_in_ == n_features + assert np.isfinite(transformed).all() + + @pytest.mark.parametrize("name, spec", _SPEC_ITEMS, ids=_SPEC_IDS) def test_target_usage_valid(name, spec): assert spec.target_usage in _VALID_TARGET_USAGE diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index a859824..0532aa5 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -16,6 +16,7 @@ import pytest from pretab import Preprocessor, PretabSerializationError, RepresentationConfig, RepresentationPolicy +from pretab.compose.registry import TransformerSpec from pretab.compose.serialize import SCHEMA_VERSION, _decode, _encode, _encode_mapping from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError @@ -520,6 +521,31 @@ def test_representation_config_decoder_runs_value_validation(fields, constraint) _decode(payload) +@pytest.mark.parametrize( + ("group_fields", "expected"), + [ + ({}, (False, 1, 1)), + ({"group_compatible": False, "min_arity": 1, "max_arity": 1}, (False, 1, 1)), + ({"group_compatible": True, "min_arity": 2, "max_arity": None}, (True, 2, None)), + ], + ids=["legacy", "standalone", "group"], +) +def test_registry_spec_decoder_uses_additive_group_metadata(group_fields, expected): + payload = { + "__dataclass__": { + "class": "pretab.compose.registry:TransformerSpec", + "fields": {"name": "custom", "transformer_cls": _encode(NoTransformer), **group_fields}, + } + } + + restored = _decode(json.loads(json.dumps(payload, allow_nan=False))) + + assert isinstance(restored, TransformerSpec) + assert restored.name == "custom" + assert restored.transformer_cls is NoTransformer + assert (restored.group_compatible, restored.min_arity, restored.max_arity) == expected + + def test_from_spec_rejects_bad_source_type(): with pytest.raises(PretabSerializationError): Preprocessor.from_spec(12345) diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index a1a3dcd..7c2f431 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -241,6 +241,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "box-cox", "optional_dependency": null, "periodic": false, @@ -271,6 +274,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "bspline", "optional_dependency": null, "periodic": false, @@ -303,6 +309,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "cubicspline", "optional_dependency": null, "periodic": false, @@ -326,6 +335,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "custombin", "optional_dependency": null, "periodic": false, @@ -354,6 +366,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "fourier", "optional_dependency": null, "periodic": true, @@ -377,6 +392,9 @@ "target_aware_capable": false }, "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "int", "optional_dependency": null, "periodic": false, @@ -407,6 +425,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "ispline", "optional_dependency": null, "periodic": false, @@ -430,6 +451,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "minmax", "optional_dependency": null, "periodic": false, @@ -460,6 +484,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "mspline", "optional_dependency": null, "periodic": false, @@ -491,6 +518,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "naturalspline", "optional_dependency": null, "periodic": false, @@ -514,6 +544,9 @@ "target_aware_capable": false }, "feature_kind": ["categorical", "numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "none", "optional_dependency": null, "periodic": false, @@ -544,6 +577,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "nystroem", "optional_dependency": null, "periodic": false, @@ -576,6 +612,9 @@ "target_aware_capable": false }, "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "one-hot", "optional_dependency": null, "periodic": false, @@ -599,6 +638,9 @@ "target_aware_capable": false }, "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "onehot_from_ordinal", "optional_dependency": null, "periodic": false, @@ -629,6 +671,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "ple", "optional_dependency": null, "periodic": false, @@ -652,6 +697,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "polynomial", "optional_dependency": null, "periodic": false, @@ -675,6 +723,9 @@ "target_aware_capable": false }, "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "pretrained", "optional_dependency": "embeddings", "periodic": false, @@ -698,6 +749,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "pspline", "optional_dependency": null, "periodic": false, @@ -721,6 +775,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "quantile", "optional_dependency": null, "periodic": false, @@ -752,6 +809,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "rbf", "optional_dependency": null, "periodic": false, @@ -782,6 +842,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "relu", "optional_dependency": null, "periodic": false, @@ -805,6 +868,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "rff", "optional_dependency": null, "periodic": false, @@ -828,6 +894,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "robust", "optional_dependency": null, "periodic": false, @@ -858,6 +927,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "sigmoid", "optional_dependency": null, "periodic": false, @@ -881,6 +953,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "standardization", "optional_dependency": null, "periodic": false, @@ -912,6 +987,9 @@ "target_aware_capable": true }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "tanh", "optional_dependency": null, "periodic": false, @@ -935,6 +1013,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": true, + "max_arity": null, + "min_arity": 2, "name": "tensorspline", "optional_dependency": null, "periodic": false, @@ -963,6 +1044,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": true, + "max_arity": null, + "min_arity": 2, "name": "tprs", "optional_dependency": null, "periodic": false, @@ -986,6 +1070,9 @@ "target_aware_capable": false }, "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, "name": "yeo-johnson", "optional_dependency": null, "periodic": false, From 07547b2cac4f824d72c77f96685dfe584da30b79 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Wed, 18 Nov 2026 23:12:10 +0100 Subject: [PATCH 36/86] feat(compose): add ordered feature group configuration --- docs/api/preprocessor.rst | 1 + pretab/__init__.py | 3 +- pretab/compose/__init__.py | 4 +- pretab/compose/config.py | 143 ++++++++++++++++++- pretab/compose/serialize.py | 1 + pretab/preprocessor.py | 46 +++++- tests/compose/test_config.py | 146 ++++++++++++++++++++ tests/compose/test_representation_config.py | 60 +++++++- tests/integration/test_preprocessor.py | 1 + tests/integration/test_public_api.py | 10 +- tests/integration/test_serialization.py | 24 ++++ tests/regression/_snapshots/public_api.json | 6 +- 12 files changed, 425 insertions(+), 20 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 0f2ae02..c704148 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -26,6 +26,7 @@ and mappings with a ``method`` key are accepted there as well. :toctree: _autosummary :nosignatures: + FeatureGroup RepresentationConfig Fields and conversion diff --git a/pretab/__init__.py b/pretab/__init__.py index 5114e7b..96563c4 100644 --- a/pretab/__init__.py +++ b/pretab/__init__.py @@ -1,5 +1,5 @@ from ._version import __version__ -from .compose import RepresentationConfig +from .compose import FeatureGroup, RepresentationConfig from .compose.search import RepresentationSearchCV from .core.logging import configure_logging, set_verbosity from .core.policy import RepresentationPolicy @@ -25,6 +25,7 @@ __all__ = [ "BaseRepresentation", "CrossFittedTransformer", + "FeatureGroup", "FeatureLineage", "FrozenRepresentationError", "LeakageWarning", diff --git a/pretab/compose/__init__.py b/pretab/compose/__init__.py index e19799f..d6b522d 100644 --- a/pretab/compose/__init__.py +++ b/pretab/compose/__init__.py @@ -5,6 +5,6 @@ ``output`` and ``inspection`` modules. """ -from .config import RepresentationConfig +from .config import FeatureGroup, RepresentationConfig -__all__ = ["RepresentationConfig"] +__all__ = ["FeatureGroup", "RepresentationConfig"] diff --git a/pretab/compose/config.py b/pretab/compose/config.py index 7b3dd82..c820083 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -20,6 +20,7 @@ from dataclasses import dataclass, field, fields, replace from difflib import get_close_matches from math import isfinite +from re import fullmatch from typing import Any from ..core.dependencies import _check_optional_dependency @@ -34,7 +35,7 @@ resolve_method, ) -__all__ = ["PreprocessorConfig", "RepresentationConfig"] +__all__ = ["FeatureGroup", "PreprocessorConfig", "RepresentationConfig"] # Valid values for the high-level ``missing_policy`` orchestration knob. ``None`` # keeps the explicit imputation parameters authoritative (historical behaviour). @@ -42,6 +43,7 @@ _REPRESENTATION_PATH = ContextVar("representation_config_path", default="RepresentationConfig") +_FEATURE_GROUP_PATH = ContextVar("feature_group_path", default="FeatureGroup") def _representation_error(param, value, constraint, *, valid=None): @@ -210,14 +212,20 @@ def from_dict(cls, data: Mapping[str, Any]) -> RepresentationConfig: def _validate_representation_capabilities( - config: RepresentationConfig, *, is_numerical: bool, source: str | Mapping[str, Any] | RepresentationConfig + config: RepresentationConfig, + *, + is_numerical: bool, + source: str | Mapping[str, Any] | RepresentationConfig, + is_group: bool = False, ) -> None: """Check explicit settings against the live spec without choosing defaults.""" spec = TRANSFORMER_REGISTRY[config.method] kind = "numerical" if is_numerical else "categorical" if kind not in spec.feature_kind: raise _representation_error("method", config.method, f"does not support {kind} features") - if not spec.preprocessor_compatible: + if is_group and not spec.group_compatible: + raise _representation_error("method", config.method, "does not support explicit feature groups") + if not is_group and not spec.preprocessor_compatible: raise _representation_error("method", config.method, "is not selectable through Preprocessor") for key, value in config.params.items(): if key not in spec.allowed_args: @@ -279,11 +287,65 @@ def _representation_request(value: str | Mapping[str, Any] | RepresentationConfi raise _representation_error("value", value, "must be a string, mapping, or RepresentationConfig") +@dataclass(frozen=True) +class FeatureGroup: + """Immutable declaration of ordered source columns and their representation. + + Parameters + ---------- + name : str + ASCII identifier beginning with a letter, without double underscores. + columns : sequence + Nonempty ordered source labels. Labels retain their original types; + integer labels identify named columns rather than positions. + representation : str, mapping, or RepresentationConfig + Representation request. Mappings use the same common fields and family + options as :class:`RepresentationConfig`. + + Notes + ----- + Columns become a tuple and representation settings detach into an immutable + value. This declaration has no fitted state and does not resolve an input + schema or perform a transformation. + """ + + name: str + columns: Sequence[Any] + representation: str | Mapping[str, Any] | RepresentationConfig + + def __post_init__(self) -> None: + path = _FEATURE_GROUP_PATH.get() + if type(self.name) is not str or fullmatch(r"[A-Za-z][A-Za-z0-9_]*", self.name) is None or "__" in self.name: + raise invalid_param_error(path, "name", self.name, "must be an ASCII identifier without double underscores") + if not isinstance(self.columns, Sequence) or isinstance(self.columns, (str, bytes, bytearray, memoryview)): + raise invalid_param_error(path, "columns", self.columns, "must be a nonempty ordered sequence of labels") + if not self.columns: + raise invalid_param_error(path, "columns", self.columns, "must be a nonempty ordered sequence of labels") + columns = tuple(self.columns) + for index, label in enumerate(columns): + try: + hash(label) + except TypeError as error: + raise invalid_param_error( + path, f"columns[{index}]", label, "must be a hashable column label" + ) from error + token = _REPRESENTATION_PATH.set(f"{path}.representation") + try: + representation = _representation_request(self.representation) + if representation.name is not None and representation.name != self.name: + raise _representation_error("name", representation.name, "must match the group name") + finally: + _REPRESENTATION_PATH.reset(token) + object.__setattr__(self, "columns", columns) + object.__setattr__(self, "representation", representation) + + def _normalize_representation_config( value: str | Mapping[str, Any] | RepresentationConfig, *, is_numerical: bool, path: str = "RepresentationConfig", + is_group: bool = False, ) -> RepresentationConfig: """Normalize one request in its known feature-kind namespace. @@ -296,7 +358,7 @@ def _normalize_representation_config( token = _REPRESENTATION_PATH.set(path) try: config = _representation_request(value) - canonical = NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS + canonical = TRANSFORMER_REGISTRY if is_group else (NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS) aliases = NUMERICAL_ALIASES if is_numerical else CATEGORICAL_ALIASES method = resolve_method(config.method, canonical, aliases) if method not in canonical: @@ -316,12 +378,64 @@ def _normalize_representation_config( constraint += f". Did you mean {', '.join(repr(match) for match in matches)}?" raise _representation_error(location, config.params[key], constraint, valid=applicable) normalized = config if method == config.method else replace(config, method=method) - _validate_representation_capabilities(normalized, is_numerical=is_numerical, source=value) + _validate_representation_capabilities(normalized, is_numerical=is_numerical, source=value, is_group=is_group) return normalized finally: _REPRESENTATION_PATH.reset(token) +def _normalize_feature_groups(value) -> tuple[FeatureGroup, ...]: + if value is None: + return () + mapping_form = isinstance(value, Mapping) + if mapping_form: + entries = value.items() + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray, memoryview)): + entries = enumerate(value) + else: + raise invalid_param_error("Preprocessor", "feature_groups", value, "must be an ordered mapping or sequence") + groups = [] + names = set() + for key, entry in entries: + path = f"feature_groups[{key!r}]" + token = _FEATURE_GROUP_PATH.set(path) + try: + if mapping_form: + if not isinstance(key, str): + raise invalid_param_error(path, "name", key, "must be a string") + if not isinstance(entry, Mapping) or set(entry) != {"columns", "representation"}: + raise invalid_param_error( + "Preprocessor", path, entry, "mapping entries must contain exactly columns and representation" + ) + group = FeatureGroup(name=key, columns=entry["columns"], representation=entry["representation"]) + elif isinstance(entry, FeatureGroup): + group = entry + elif isinstance(entry, Mapping) and set(entry) == {"name", "columns", "representation"}: + group = FeatureGroup( + name=entry["name"], columns=entry["columns"], representation=entry["representation"] + ) + else: + raise invalid_param_error( + "Preprocessor", + path, + entry, + "must be a FeatureGroup or a mapping with name, columns and representation", + ) + if group.name in names: + raise invalid_param_error(path, "name", group.name, "must be unique among feature groups") + representation = _normalize_representation_config( + group.representation, + is_numerical=True, + is_group=True, + path=f"feature_groups[{group.name!r}].representation", + ) + groups.append(replace(group, representation=representation)) + names.add(group.name) + finally: + _FEATURE_GROUP_PATH.reset(token) + return tuple(groups) + + def _normalize_method(method, canonical, aliases) -> str: """Resolve a global method name to canonical form, mapping ``None`` to ``"none"``.""" if method is None: @@ -359,6 +473,7 @@ class PreprocessorConfig: add_missing_indicator: bool missing_policy: str | None verbose: int + feature_groups: tuple[FeatureGroup, ...] = () @classmethod def from_params( @@ -384,6 +499,7 @@ def from_params( add_missing_indicator, missing_policy, verbose, + feature_groups=None, ) -> PreprocessorConfig: """Normalize and validate raw Preprocessor parameters into a config. @@ -435,6 +551,7 @@ def from_params( add_missing_indicator=add_missing_indicator, missing_policy=missing_policy, verbose=verbose, + feature_groups=_normalize_feature_groups(feature_groups), ) @staticmethod @@ -481,7 +598,19 @@ def representation_for(self, feature, *, is_numerical: bool | None = None) -> Re finally: _REPRESENTATION_PATH.reset(token) is_numerical = self.resolve_categorical(method) not in CATEGORICAL_METHODS - requested = _normalize_representation_config(raw, is_numerical=is_numerical, path=path) + return self._resolve_representation(raw, is_numerical=is_numerical, path=path) + + def group_representation_for(self, group: FeatureGroup) -> RepresentationConfig: + """Resolve a group's representation over applicable constructor controls.""" + return self._resolve_representation( + group.representation, + is_numerical=True, + is_group=True, + path=f"feature_groups[{group.name!r}].representation", + ) + + def _resolve_representation(self, raw, *, is_numerical: bool, path: str, is_group: bool = False): + requested = _normalize_representation_config(raw, is_numerical=is_numerical, path=path, is_group=is_group) spec = TRANSFORMER_REGISTRY[requested.method] inherited = {} if "output_dim" in spec.allowed_args or spec.supports_adaptive_resolution: @@ -503,7 +632,7 @@ def representation_for(self, feature, *, is_numerical: bool | None = None) -> Re params.update(requested.params) settings = {key: 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) + return _normalize_representation_config(resolved, is_numerical=is_numerical, path=path, is_group=is_group) @property def seed_kwargs(self) -> dict: diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 0930c07..a2a1ae6 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -383,5 +383,6 @@ def preprocessor_from_spec(data: dict): obj = Preprocessor.__new__(Preprocessor) obj.__dict__.update(_decode_mapping(data["state"])) + obj.__dict__.setdefault("feature_groups", None) _repair_legacy_sparse_feature_counts(obj) return obj diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 4360eb2..3aaf9e2 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -351,6 +351,12 @@ class Preprocessor(TransformerMixin, BaseEstimator): and one-hot encodes categoricals, and ``"adaptive"`` sizes each feature's width from the data within ``[7, 15]``. Call :meth:`get_resolved_config` to see the effective parameters. ``None`` (default) uses the individual parameters unchanged. + feature_groups : mapping or sequence, default=None + Ordered named declarations of source columns and representation settings. + Constructor inputs remain unchanged; :meth:`get_resolved_config` returns + detached declarations with canonical methods and applicable settings. + ``None`` or an empty collection keeps single-column processing. Nonempty + declarations are rejected by ``fit``. Attributes ---------- @@ -501,6 +507,8 @@ def __init__( dtype=None, verbose=0, preset=None, + *, + feature_groups=None, ): """ Initialize the Preprocessor with various transformation options for tabular data. @@ -538,9 +546,12 @@ def __init__( self.dtype = dtype self.verbose = verbose self.preset = preset + self.feature_groups = feature_groups def __setstate__(self, state): super().__setstate__(state) + if not hasattr(self, "feature_groups"): + self.feature_groups = None _repair_legacy_sparse_feature_counts(self) def fit(self, X, y=None, embeddings=None): @@ -613,8 +624,17 @@ def fit(self, X, y=None, embeddings=None): add_missing_indicator=resolved["add_missing_indicator"], missing_policy=resolved["missing_policy"], verbose=resolved["verbose"], + feature_groups=resolved["feature_groups"], ) + if config.feature_groups: + raise invalid_param_error( + type(self).__name__, + "feature_groups", + tuple(group.name for group in config.feature_groups), + "nonempty group declarations cannot be fitted through the single-column composition route", + ) + fitted_on_array = not has_column_labels(X) X = to_dataframe(X) @@ -901,8 +921,10 @@ def get_resolved_config(self): caller left at its default while explicitly-set parameters win; the ``preset`` key itself is removed. Declared ``feature_preprocessing`` entries become ordinary mappings with canonical methods and applicable - inherited settings, using the same resolver as fitting. Other global - keys retain their preset-expanded values. + inherited settings, using the same resolver as fitting. Explicit + ``feature_groups`` become an ordered list of mappings with original + source labels and resolved representation settings. Other global keys + retain their preset-expanded values. The result is detached from caller-owned containers and resolves current parameters before or after fit. It does not describe the last fitted @@ -919,13 +941,23 @@ def get_resolved_config(self): If ``task``, ``preset``, or a declared representation is invalid. """ resolved = self._resolved_params() - if resolved["feature_preprocessing"]: + if resolved["feature_preprocessing"] or resolved["feature_groups"] is not None: config = PreprocessorConfig.from_params( **{field.name: resolved[field.name] for field in fields(PreprocessorConfig)} ) - resolved["feature_preprocessing"] = { - feature: config.representation_for(feature).to_dict() for feature in config.feature_preprocessing - } + if resolved["feature_preprocessing"]: + resolved["feature_preprocessing"] = { + feature: config.representation_for(feature).to_dict() for feature in config.feature_preprocessing + } + if resolved["feature_groups"] is not None: + resolved["feature_groups"] = [ + { + "name": group.name, + "columns": list(group.columns), + "representation": config.group_representation_for(group).to_dict(), + } + for group in config.feature_groups + ] return copy.deepcopy(resolved) def get_feature_names_out(self, input_features=None): @@ -1451,6 +1483,8 @@ def _canonical_spec(self) -> dict: for key, value in spec["state"].items() if key not in {"output_report_", "_frozen", "_stale_reason"} } + if not getattr(self, "feature_groups", None): + state.pop("feature_groups", None) return { "schema_version": spec["schema_version"], "pretab_version": spec["pretab_version"], diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index 5da15b2..ab46c79 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -1,5 +1,6 @@ """Unit tests for :class:`pretab.compose.config.PreprocessorConfig`.""" +import inspect import json from dataclasses import asdict, replace from typing import Any @@ -10,6 +11,7 @@ from sklearn.base import clone from pretab import Preprocessor, RepresentationConfig +from pretab.compose.config import FeatureGroup from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError @@ -59,6 +61,7 @@ def test_resolved_config_matches_inline_preset_contract(task, preset, overrides) "output_format": "dense", "dtype": None, "verbose": 0, + "feature_groups": None, **overrides, } @@ -131,10 +134,153 @@ def test_normalized_config_retains_every_representation_setting(make_config): **parameters, "numerical_method": "cubicspline", "categorical_method": "one-hot", + "feature_groups": (), } assert config.feature_preprocessing is not parameters["feature_preprocessing"] +@pytest.mark.parametrize("form", ["mapping", "sequence", "values"]) +def test_group_normalization_preserves_declaration_and_source_order(make_config, form): + declarations = [ + {"name": "second", "columns": [1, "latitude"], "representation": {"method": "thinplate", "n_components": 4}}, + {"name": "first", "columns": ["b", "a"], "representation": "tensor"}, + ] + requested = { + "mapping": { + item["name"]: {key: value for key, value in item.items() if key != "name"} for item in declarations + }, + "sequence": declarations, + "values": [FeatureGroup(**item) for item in declarations], + }[form] + config = make_config(feature_groups=requested) + + assert isinstance(config.feature_groups, tuple) + assert [group.name for group in config.feature_groups] == ["second", "first"] + assert [group.columns for group in config.feature_groups] == [(1, "latitude"), ("b", "a")] + assert [group.representation for group in config.feature_groups] == [ + RepresentationConfig("tprs", params={"n_components": 4}), + RepresentationConfig("tensorspline"), + ] + declarations[0]["columns"].append("changed") + assert config.feature_groups[0].columns == (1, "latitude") + + +@pytest.mark.parametrize("requested", [None, {}, [], ()]) +def test_empty_groups_normalize_to_an_empty_tuple(make_config, requested): + assert make_config(feature_groups=requested).feature_groups == () + + +def test_group_representation_uses_existing_inheritance_and_local_priority(make_config): + config = make_config( + feature_groups={ + "surface": {"columns": ["b", "a"], "representation": {"method": "tensor", "output_dim": 4, "degree": 2}}, + "location": {"columns": ["x", "y"], "representation": {"method": "thinplate", "n_components": 6}}, + }, + output_dim=9, + degree=3, + random_state=17, + ) + + surface, location = [config.group_representation_for(group) for group in config.feature_groups] + assert surface == RepresentationConfig( + "tensorspline", output_dim=4, placement_strategy="uniform", params={"degree": 2} + ) + assert location == RepresentationConfig("tprs", params={"n_components": 6, "random_state": 17}) + + +@pytest.mark.parametrize( + "requested", + [ + "location", + {"x", "y"}, + ["x", "y"], + {"location": {"columns": ["x", "y"]}}, + {"location": {"columns": ["x", "y"], "representation": "tprs", "name": "location"}}, + [{"columns": ["x", "y"], "representation": "tprs"}], + [{"name": "location", "columns": ["x", "y"], "representation": "tprs", "extra": True}], + {"location": {"columns": ["x", "y"], "representation": "rff"}}, + {"location": {"columns": ["x", "y"], "representation": {"method": "tprs", "n_componnts": 4}}}, + {"location": {"columns": ["x", "y"], "representation": {"method": "tprs", "name": "other"}}}, + [FeatureGroup("location", ["x", "y"], "tprs"), FeatureGroup("location", ["a", "b"], "tensor")], + ], +) +def test_invalid_group_declarations_raise_contextual_errors(make_config, requested): + with pytest.raises(InvalidParamError, match="feature_groups"): + make_config(feature_groups=requested) + + +def test_group_parameter_is_last_keyword_only_and_remains_raw_for_sklearn(): + declarations = { + "location": {"columns": [1, "latitude"], "representation": {"method": "thinplate", "n_components": 4}} + } + processor = Preprocessor(feature_groups=declarations, random_state=17) + parameters = inspect.signature(Preprocessor).parameters + + assert list(parameters)[-1] == "feature_groups" + assert parameters["feature_groups"].kind is inspect.Parameter.KEYWORD_ONLY + assert parameters["feature_groups"].default is None + assert processor.get_params(deep=False)["feature_groups"] is declarations + resolved = processor.get_resolved_config() + assert resolved["feature_groups"] == [ + { + "name": "location", + "columns": [1, "latitude"], + "representation": RepresentationConfig("tprs", params={"n_components": 4, "random_state": 17}).to_dict(), + } + ] + resolved["feature_groups"][0]["columns"].append("changed") + resolved["feature_groups"][0]["representation"]["params"]["n_components"] = 8 + assert processor.get_resolved_config()["feature_groups"][0]["representation"]["params"]["n_components"] == 4 + declarations["location"]["representation"]["n_components"] = 6 + assert processor.get_resolved_config()["feature_groups"][0]["representation"]["params"]["n_components"] == 6 + assert processor.feature_groups is declarations + + +@pytest.mark.parametrize("typed", [False, True]) +def test_group_requests_clone_and_set_params_without_normalizing_constructor_values(typed): + requested = ( + [FeatureGroup("location", ["x", "y"], "thinplate")] + if typed + else {"location": {"columns": ["x", "y"], "representation": "thinplate"}} + ) + processor = Preprocessor(feature_groups=requested) + copied = clone(processor) + assert isinstance(copied, Preprocessor) + assert copied.feature_groups == requested + assert copied.feature_groups is not requested + assert copied.get_resolved_config() == processor.get_resolved_config() + processor.set_params(feature_groups=None) + assert processor.feature_groups is None + assert processor.get_resolved_config()["feature_groups"] is None + + +@pytest.mark.parametrize("requested", [None, {}, [], ()]) +def test_empty_groups_preserve_single_column_values_names_and_fingerprint(sample_frame, requested): + parameters = {"numerical_method": "rbf", "target_aware": False, "placement_strategy": "uniform"} + reference = Preprocessor(**parameters).fit(sample_frame) + processor = Preprocessor(feature_groups=requested, **parameters).fit(sample_frame) + + np.testing.assert_array_equal(processor.transform(sample_frame), reference.transform(sample_frame)) + np.testing.assert_array_equal(processor.get_feature_names_out(), reference.get_feature_names_out()) + assert processor.output_dims_ == reference.output_dims_ + assert processor.fingerprint_ == reference.fingerprint_ + assert processor.feature_groups is requested + expected_config = reference.get_resolved_config() + expected_config["feature_groups"] = None if requested is None else [] + assert processor.get_resolved_config() == expected_config + + +def test_nonempty_groups_cannot_be_silently_ignored_by_single_column_fitting(monkeypatch): + def reject_conversion(_data): + raise AssertionError("Group refusal must precede data conversion and estimator fitting") + + monkeypatch.setattr("pretab.preprocessor.to_dataframe", reject_conversion) + processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) + with pytest.raises(InvalidParamError, match="single-column composition route"): + processor.fit(object()) + assert not hasattr(processor, "column_transformer_") + + def test_none_method_normalizes_to_none(make_config): cfg = make_config(numerical_method=None, categorical_method=None) assert cfg.numerical_method == "none" diff --git a/tests/compose/test_representation_config.py b/tests/compose/test_representation_config.py index e46fc27..f94578c 100644 --- a/tests/compose/test_representation_config.py +++ b/tests/compose/test_representation_config.py @@ -12,13 +12,71 @@ from sklearn.base import clone from pretab import Preprocessor -from pretab.compose.config import RepresentationConfig, _normalize_representation_config +from pretab.compose.config import FeatureGroup, RepresentationConfig, _normalize_representation_config from pretab.compose.factory import get_categorical_transformer_steps, get_numerical_transformer_steps from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError, OptionalDependencyError +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +def test_feature_group_value_accepts_existing_representation_forms(form): + requested = {"string": "tprs", "mapping": {"method": "tprs"}, "value": RepresentationConfig("tprs")}[form] + group = FeatureGroup("location", [1, "latitude"], requested) + + assert group.columns == (1, "latitude") + assert group.representation == RepresentationConfig("tprs") + with pytest.raises(FrozenInstanceError): + cast(Any, group).name = "replacement" + + +def test_feature_group_value_detaches_columns_and_nested_settings(): + columns = ["longitude", "latitude"] + settings = {"method": "tprs", "params": {"options": {"levels": [1, 2]}}} + group = FeatureGroup("location", columns, settings) + columns.reverse() + settings["params"]["options"]["levels"].append(3) + + assert group.columns == ("longitude", "latitude") + assert isinstance(group.representation, RepresentationConfig) + assert group.representation.params["options"]["levels"] == (1, 2) + with pytest.raises(TypeError): + group.representation.params["options"]["levels"][0] = 9 + + +@pytest.mark.parametrize("name", ["", " ", "_location", "1location", "a-b", "a b", "a__b", "caf\u00e9", None, True, 1]) +def test_feature_group_value_rejects_invalid_identifiers(name): + with pytest.raises(InvalidParamError, match=r"FeatureGroup\.name"): + FeatureGroup(name, ["x", "y"], "tprs") + + +@pytest.mark.parametrize( + "columns", [[], (), "xy", b"xy", {"x", "y"}, {"x": 1}, slice(0, 2), lambda: ["x"], None, [["x"]]] +) +def test_feature_group_value_rejects_unordered_or_invalid_columns(columns): + with pytest.raises(InvalidParamError, match=r"FeatureGroup\.columns"): + FeatureGroup("location", columns, "tprs") + + +@pytest.mark.parametrize( + "restore", + [ + copy.copy, + copy.deepcopy, + lambda value: pickle.loads(pickle.dumps(value)), # noqa: S301 + lambda value: clone(value, safe=False), + ], +) +def test_feature_group_value_preserves_immutable_settings_through_copy_and_pickle(restore): + group = FeatureGroup("location", [1, "y"], {"method": "tprs", "params": {"options": {"levels": [1, 2]}}}) + restored = restore(group) + + assert restored == group and restored is not group + assert restored.columns == (1, "y") + with pytest.raises(TypeError): + restored.representation.params["options"]["levels"][0] = 9 + + @pytest.fixture def nested_registry_option(monkeypatch): for method in ("rbf", "cubicspline"): diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index c3ebfef..3f257cd 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -202,6 +202,7 @@ def test_dict_keys_reflect_column_names(sample_data): "dtype", "verbose", "preset", + "feature_groups", } diff --git a/tests/integration/test_public_api.py b/tests/integration/test_public_api.py index cfc4a35..b82d49e 100644 --- a/tests/integration/test_public_api.py +++ b/tests/integration/test_public_api.py @@ -225,7 +225,15 @@ def test_representation_config_public_exports_are_identical(): assert pretab.RepresentationConfig is RepresentationConfig assert pretab_compose.RepresentationConfig is RepresentationConfig assert "RepresentationConfig" in pretab.__all__ - assert pretab_compose.__all__ == ["RepresentationConfig"] + assert pretab_compose.__all__ == ["FeatureGroup", "RepresentationConfig"] + + +def test_feature_group_public_exports_are_identical(): + from pretab.compose.config import FeatureGroup + + assert pretab.FeatureGroup is FeatureGroup + assert pretab_compose.FeatureGroup is FeatureGroup + assert "FeatureGroup" in pretab.__all__ def test_transformers_public_surface_is_resolvable(): diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index 0532aa5..64290ea 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -14,6 +14,7 @@ import numpy as np import pandas as pd import pytest +from sklearn.base import clone from pretab import Preprocessor, PretabSerializationError, RepresentationConfig, RepresentationPolicy from pretab.compose.registry import TransformerSpec @@ -41,6 +42,29 @@ def target(): return rng.random(60) +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +def test_legacy_state_without_groups_restores_the_constructor_default(frame, restore_format): + processor = Preprocessor(numerical_method="rbf", target_aware=False, placement_strategy="uniform").fit(frame) + expected = processor.transform(frame) + fingerprint = processor.fingerprint_ + if restore_format == "pickle": + del processor.feature_groups + restored = pickle.loads(pickle.dumps(processor)) # noqa: S301 + else: + spec = processor.to_spec() + del spec["state"]["feature_groups"] + del spec["params"]["feature_groups"] + restored = Preprocessor.from_spec(spec) + + assert restored.get_params(deep=False)["feature_groups"] is None + assert restored.get_resolved_config()["feature_groups"] is None + assert restored.fingerprint_ == fingerprint + np.testing.assert_array_equal(restored.transform(frame), expected) + copied = clone(restored) + assert isinstance(copied, Preprocessor) + assert copied.feature_groups is None + + # Representation configs that round-trip; each is (params, id). _CONFIGS = [ {"numerical_method": "rbf", "target_aware": False, "placement_strategy": "quantile"}, diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index 7c2f431..f910577 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -142,6 +142,7 @@ "pretab": [ "BaseRepresentation", "CrossFittedTransformer", + "FeatureGroup", "FeatureLineage", "FrozenRepresentationError", "LeakageWarning", @@ -162,7 +163,7 @@ "register_representation", "set_verbosity" ], - "pretab.compose": ["RepresentationConfig"], + "pretab.compose": ["FeatureGroup", "RepresentationConfig"], "pretab.compose.registry": [ "CATEGORICAL_ALIASES", "CATEGORICAL_METHODS", @@ -1119,8 +1120,9 @@ "signatures": { "pretab.BaseRepresentation": "()", "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None)", + "pretab.FeatureGroup": "(name: 'str', columns: 'Sequence[Any]', representation: 'str | Mapping[str, Any] | RepresentationConfig') -> None", "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool) -> None", - "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None)", + "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None, *, feature_groups=None)", "pretab.RepresentationConfig": "(method: 'str', output_dim: 'int | _Unset' = UNSET, target_aware: 'bool | _Unset' = UNSET, placement_strategy: 'str | _Unset' = UNSET, adaptive: 'bool | _Unset' = UNSET, min_output_dim: 'int | _Unset | None' = UNSET, max_output_dim: 'int | _Unset | None' = UNSET, params: 'Mapping[str, Any]' = , name: 'str | None' = None) -> None", "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", "pretab.RepresentationSearchCV": "(estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None)", From f2dc827147eb2f4f317c6cca0053493efdd8625c Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 00:16:38 +0100 Subject: [PATCH 37/86] feat(compose): validate feature group conflicts before fitting --- pretab/compose/config.py | 46 +++- pretab/preprocessor.py | 9 + tests/compose/test_config.py | 12 +- tests/compose/test_feature_groups_config.py | 288 ++++++++++++++++++++ 4 files changed, 348 insertions(+), 7 deletions(-) create mode 100644 tests/compose/test_feature_groups_config.py diff --git a/pretab/compose/config.py b/pretab/compose/config.py index c820083..353dc62 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -25,7 +25,7 @@ from ..core.dependencies import _check_optional_dependency from ..core.parameters import UNSET, _Unset, validate_placement, validate_task -from ..exceptions import InvalidParamError, invalid_param_error +from ..exceptions import IncompatibleParamsError, InvalidParamError, invalid_param_error from .registry import ( CATEGORICAL_ALIASES, CATEGORICAL_METHODS, @@ -609,6 +609,50 @@ def group_representation_for(self, group: FeatureGroup) -> RepresentationConfig: path=f"feature_groups[{group.name!r}].representation", ) + def validate_feature_groups(self, columns, numerical_features, *, y=None) -> None: + """Check group ownership and capabilities against the detected input schema.""" + available = set(columns) + numerical = set(numerical_features) + owners = {} + for group in self.feature_groups: + path = f"feature_groups[{group.name!r}]" + representation = self.group_representation_for(group) + spec = TRANSFORMER_REGISTRY[representation.method] + for index, label in enumerate(group.columns): + location = f"columns[{index}]" + if label in owners: + owner, source_index = owners[label] + raise invalid_param_error( + path, + location, + label, + f"already assigned to feature_groups[{owner!r}].columns[{source_index}]", + ) + if label in self.feature_preprocessing: + raise invalid_param_error( + path, location, label, f"must not also be assigned in feature_preprocessing[{label!r}]" + ) + if label not in available: + raise invalid_param_error(path, location, label, "must name a column present in X", valid=columns) + kind = "numerical" if label in numerical else "categorical" + if kind not in spec.feature_kind: + raise invalid_param_error( + path, location, label, f"detected {kind} source is not supported by method {spec.name!r}" + ) + owners[label] = (group.name, index) + arity = len(group.columns) + if arity < spec.min_arity or (spec.max_arity is not None and arity > spec.max_arity): + bounds = ( + f"at least {spec.min_arity}" if spec.max_arity is None else f"{spec.min_arity} to {spec.max_arity}" + ) + raise invalid_param_error( + path, "columns", group.columns, f"method {spec.name!r} requires {bounds} source columns" + ) + if y is None and (spec.requires_target or representation.target_aware is True): + raise IncompatibleParamsError( + f"{path}.representation.method = {spec.name!r} requires y at fit time; got y=None." + ) + def _resolve_representation(self, raw, *, is_numerical: bool, path: str, is_group: bool = False): requested = _normalize_representation_config(raw, is_numerical=is_numerical, path=path, is_group=is_group) spec = TRANSFORMER_REGISTRY[requested.method] diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 3aaf9e2..f291b8c 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -628,6 +628,15 @@ def fit(self, X, y=None, embeddings=None): ) if config.feature_groups: + group_frame = to_dataframe(X) + group_numerical, _ = detect_column_types( + group_frame, + cat_cutoff=resolved["cat_cutoff"], + treat_all_integers_as_numerical=resolved["treat_all_integers_as_numerical"], + estimator_name=type(self).__name__, + ) + config.validate_feature_groups(group_frame.columns, group_numerical, y=y) + with_string_labels(group_frame) raise invalid_param_error( type(self).__name__, "feature_groups", diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index ab46c79..d4d527f 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -270,14 +270,14 @@ def test_empty_groups_preserve_single_column_values_names_and_fingerprint(sample assert processor.get_resolved_config() == expected_config -def test_nonempty_groups_cannot_be_silently_ignored_by_single_column_fitting(monkeypatch): - def reject_conversion(_data): - raise AssertionError("Group refusal must precede data conversion and estimator fitting") +def test_nonempty_groups_cannot_be_silently_ignored_by_single_column_fitting(sample_frame, monkeypatch): + def reject_construction(*args, **kwargs): + raise AssertionError("Group refusal must precede factory construction and estimator fitting") - monkeypatch.setattr("pretab.preprocessor.to_dataframe", reject_conversion) - processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) + monkeypatch.setattr("pretab.preprocessor.build_column_transformer", reject_construction) + processor = Preprocessor(feature_groups={"location": {"columns": ["age", "second"], "representation": "tprs"}}) with pytest.raises(InvalidParamError, match="single-column composition route"): - processor.fit(object()) + processor.fit(sample_frame.assign(second=sample_frame["age"] + 1)) assert not hasattr(processor, "column_transformer_") diff --git a/tests/compose/test_feature_groups_config.py b/tests/compose/test_feature_groups_config.py new file mode 100644 index 0000000..9775911 --- /dev/null +++ b/tests/compose/test_feature_groups_config.py @@ -0,0 +1,288 @@ +"""Pre-fit ownership and input-capability contracts for explicit groups.""" + +from copy import deepcopy +from dataclasses import replace +from re import escape + +import numpy as np +import pandas as pd +import pytest + +from pretab import FeatureGroup, Preprocessor, RepresentationConfig +from pretab.compose.config import PreprocessorConfig +from pretab.compose.registry import TRANSFORMER_REGISTRY +from pretab.exceptions import IncompatibleParamsError, InvalidParamError, OptionalDependencyError, PretabDataError + + +@pytest.fixture +def group_frame(): + return pd.DataFrame( + { + "x": [0.0, 1.0, 2.0], + "y": [2.0, 3.0, 4.0], + "z": [4.0, 5.0, 6.0], + "flag": [True, False, True], + } + ) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize( + ("columns", "other_groups", "overrides", "expected"), + [ + (["x", "x"], {}, None, "feature_groups['location'].columns[1]"), + ( + ["x", "y"], + {"other": {"columns": ["y", "z"], "representation": "tprs"}}, + None, + "feature_groups['other'].columns[0]", + ), + (["x", "y"], {}, {"x": "tprs"}, "feature_preprocessing['x']"), + (["x", "absent"], {}, None, "feature_groups['location'].columns[1]"), + (["x"], {}, None, "feature_groups['location'].columns"), + (["x", "flag"], {}, None, "feature_groups['location'].columns[1]"), + ], + ids=["duplicate", "overlap", "override", "missing", "min-arity", "boolean"], +) +def test_group_conflicts_precede_factory(group_frame, monkeypatch, method, columns, other_groups, overrides, expected): + def reject_construction(*args, **kwargs): + raise AssertionError("Group validation must precede factory construction") + + monkeypatch.setattr("pretab.preprocessor.build_column_transformer", reject_construction) + groups = {"location": {"columns": columns, "representation": method}, **other_groups} + original = deepcopy(groups) + processor = Preprocessor(feature_groups=groups, feature_preprocessing=overrides) + with pytest.raises(InvalidParamError, match=escape(expected)) as failure: + processor.fit(group_frame) + assert "location" in str(failure.value) + assert groups == original + assert not hasattr(processor, "column_transformer_") + assert not hasattr(processor, "numerical_features_") + + +@pytest.mark.parametrize("method", ["tensor", "thinplate"]) +@pytest.mark.parametrize("mapping_form", [False, True]) +def test_valid_groups_keep_declared_order_and_unclaimed_sources(make_config, group_frame, method, mapping_form): + declaration = FeatureGroup("location", ["z", "x"], method) + groups = {"location": {"columns": ["z", "x"], "representation": method}} if mapping_form else [declaration] + config = make_config(feature_groups=groups) + original = config.feature_groups + before = group_frame.copy(deep=True) + assert config.validate_feature_groups(group_frame.columns, ["x", "y", "z"]) is None + assert config.feature_groups is original + assert original[0].columns == ("z", "x") + assert original[0].representation.method == {"tensor": "tensorspline", "thinplate": "tprs"}[method] + assert isinstance(declaration.representation, RepresentationConfig) + assert declaration.representation.method == method + pd.testing.assert_frame_equal(group_frame, before) + + +@pytest.mark.parametrize( + ("bounds", "columns", "constraint"), + [ + ({"min_arity": 3}, ["x", "y"], "at least 3"), + ({"max_arity": 2}, ["x", "y", "z"], "2 to 2"), + ], +) +def test_group_arity_uses_live_registry_bounds(group_frame, monkeypatch, bounds, columns, constraint): + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "tprs", replace(spec, **bounds)) + processor = Preprocessor(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) + with pytest.raises(InvalidParamError, match=escape("feature_groups['location'].columns")) as failure: + processor.fit(group_frame) + assert constraint in str(failure.value) + + +@pytest.mark.parametrize( + "values", + [ + pd.Series([True, False, True]), + pd.Series([True, None, False], dtype="boolean"), + pd.Series(["a", "b", "a"], dtype="string"), + pd.Series([1.0, 2.0, 1.0], dtype="category"), + pd.Series([1, 1, 2]), + pd.Series([1, None, 2], dtype="Int64"), + ], + ids=["boolean", "nullable-boolean", "string", "category", "low-cardinality-integer", "nullable-integer"], +) +def test_categorical_sources_are_not_coerced_to_numerical(group_frame, values): + processor = Preprocessor( + cat_cutoff=3, + feature_groups={"location": {"columns": ["x", "source"], "representation": "tprs"}}, + ) + with pytest.raises(InvalidParamError, match=escape("feature_groups['location'].columns[1]")) as failure: + processor.fit(group_frame.assign(source=values)) + assert "detected categorical" in str(failure.value) + assert "'source'" in str(failure.value) + + +@pytest.mark.parametrize("dtype", ["int64", "Int64"]) +def test_explicit_integer_routing_remains_available_to_groups(group_frame, dtype): + processor = Preprocessor( + cat_cutoff=3, + treat_all_integers_as_numerical=True, + feature_groups={"location": {"columns": ["x", "code"], "representation": "tprs"}}, + ) + with pytest.raises(InvalidParamError, match="single-column composition route"): + processor.fit(group_frame.assign(code=pd.Series([1, 1, 2], dtype=dtype))) + + +@pytest.mark.parametrize( + ("named", "columns", "missing_index"), + [ + (True, [7, 3], None), + (True, ["7", "3"], 0), + (True, [0, 1], 0), + (False, ["feature_1", "feature_0"], None), + (False, [1, 0], 0), + (False, ["feature_0", "absent"], 1), + ], +) +def test_group_sources_follow_existing_label_route(named, columns, missing_index): + values = np.array([[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]]) + data = pd.DataFrame(values, columns=pd.Index([7, 3])) if named else values + before = data.copy() + processor = Preprocessor(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) + expected = ( + "single-column composition route" + if missing_index is None + else escape(f"feature_groups['location'].columns[{missing_index}]") + ) + with pytest.raises(InvalidParamError, match=expected): + processor.fit(data) + if named: + pd.testing.assert_frame_equal(data, before) + else: + np.testing.assert_array_equal(data, before) + + +def test_groups_do_not_bypass_existing_string_label_collision_validation(): + data = pd.DataFrame([[0.0, 1.0], [2.0, 3.0]], columns=pd.Index([1, "1"], dtype=object)) + processor = Preprocessor(feature_groups={"location": {"columns": [1, "1"], "representation": "tprs"}}) + with pytest.raises(PretabDataError, match="converted to strings"): + processor.fit(data) + assert list(data.columns) == [1, "1"] + + +@pytest.mark.parametrize("groups", [None, {}, [], ()]) +def test_empty_groups_do_not_enter_group_preflight(group_frame, monkeypatch, groups): + def unexpected(*args, **kwargs): + pytest.fail("The no-groups route must not call group preflight") + + monkeypatch.setattr(PreprocessorConfig, "validate_feature_groups", unexpected) + processor = Preprocessor(numerical_method="standardization", categorical_method="int", feature_groups=groups).fit( + group_frame + ) + assert processor.feature_groups is groups + + +@pytest.mark.parametrize("usage", ["required", "optional"]) +@pytest.mark.parametrize("has_target", [False, True]) +def test_group_target_requirements_keep_typed_errors(group_frame, monkeypatch, usage, has_target): + def unexpected(*args, **kwargs): + pytest.fail("Group target validation must not construct a transformer") + + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace(spec, target_usage=usage, placement_strategies=frozenset({"cart"}), transformer_cls=unexpected), + ) + processor = Preprocessor( + feature_groups={ + "location": { + "columns": ["x", "y"], + "representation": {"method": "tprs", "target_aware": True, "placement_strategy": "cart"}, + } + } + ) + target = np.array([0.0, 1.0, 2.0]) if has_target else None + if has_target: + with pytest.raises(InvalidParamError, match="single-column composition route"): + processor.fit(group_frame, target) + else: + with pytest.raises(IncompatibleParamsError, match=escape("feature_groups['location'].representation.method")): + processor.fit(group_frame) + assert not hasattr(processor, "column_transformer_") + + +@pytest.mark.parametrize("local_off", [False, True]) +def test_group_target_check_uses_resolved_settings(group_frame, monkeypatch, local_off): + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace(spec, target_usage="optional", placement_strategies=frozenset({"uniform", "cart"})), + ) + representation = {"method": "tprs", "target_aware": False, "placement_strategy": "uniform"} if local_off else "tprs" + processor = Preprocessor( + target_aware=True, + placement_strategy="cart", + feature_groups={"location": {"columns": ["x", "y"], "representation": representation}}, + ) + error = InvalidParamError if local_off else IncompatibleParamsError + expected = "single-column composition route" if local_off else "requires y at fit time" + with pytest.raises(error, match=expected): + processor.fit(group_frame) + + +@pytest.mark.parametrize("available", [False, True]) +def test_group_dependency_check_is_contextual_without_import_or_construction(group_frame, monkeypatch, available): + discovered = [] + + def discover(module_name): + discovered.append(module_name) + return object() if available else None + + def unexpected(*args, **kwargs): + pytest.fail("Group validation must not import optional packages or construct a transformer") + + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, "tprs", replace(spec, optional_dependency="embeddings", transformer_cls=unexpected) + ) + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", discover) + monkeypatch.setattr("pretab.core.dependencies.importlib.import_module", unexpected) + processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) + if available: + with pytest.raises(InvalidParamError, match="single-column composition route"): + processor.fit(group_frame) + else: + with pytest.raises(OptionalDependencyError) as failure: + processor.fit(group_frame) + assert "feature_groups['location'].representation.method" in str(failure.value) + assert "pip install pretab[embeddings]" in str(failure.value) + assert discovered + assert set(discovered) == {"sentence_transformers"} + + +def test_group_placement_dependency_keeps_context_and_install_hint(group_frame, monkeypatch): + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace(spec, target_usage="optional", placement_strategies=frozenset({"lightgbm"})), + ) + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", lambda module_name: None) + processor = Preprocessor( + feature_groups={ + "location": { + "columns": ["x", "y"], + "representation": {"method": "tprs", "target_aware": True, "placement_strategy": "lightgbm"}, + } + } + ) + with pytest.raises(OptionalDependencyError) as failure: + processor.fit(group_frame, np.array([0.0, 1.0, 2.0])) + assert "feature_groups['location'].representation.placement_strategy" in str(failure.value) + assert "pip install pretab[lightgbm]" in str(failure.value) + + +def test_builtin_group_preflight_does_not_discover_unselected_extras(group_frame, monkeypatch): + def unexpected(*args, **kwargs): + pytest.fail("No optional dependency is selected") + + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", unexpected) + processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) + with pytest.raises(InvalidParamError, match="single-column composition route"): + processor.fit(group_frame) From c41c3b35404f7a4825d641a4be9c34c4f2415f4d Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 09:46:43 +0100 Subject: [PATCH 38/86] feat(compose): construct ordered feature group pipelines --- pretab/compose/factory.py | 103 +++++++++++++++--- tests/compose/test_factory.py | 190 +++++++++++++++++++++++++++++++++- 2 files changed, 277 insertions(+), 16 deletions(-) diff --git a/pretab/compose/factory.py b/pretab/compose/factory.py index 6c77b2d..d96e84f 100644 --- a/pretab/compose/factory.py +++ b/pretab/compose/factory.py @@ -1,8 +1,8 @@ -"""Build the per-column transformer pipelines and combine them. +"""Build single-column and grouped transformer pipelines and combine them. -This module turns a resolved method name plus a :class:`PreprocessorConfig` into -scikit-learn transformer steps, wraps them in a per-column -:class:`~sklearn.pipeline.Pipeline`, and assembles every column into the final +This module turns resolved requests plus a :class:`PreprocessorConfig` into +scikit-learn transformer steps, wraps them in a shared +:class:`~sklearn.pipeline.Pipeline` construction path, and assembles the blocks into a :class:`~sklearn.compose.ColumnTransformer`. The class to instantiate, the constructor arguments it accepts, and which placement keyword arguments apply are all taken from :data:`~pretab.compose.registry.TRANSFORMER_REGISTRY`. @@ -25,6 +25,7 @@ CATEGORICAL_METHODS, NUMERICAL_ALIASES, NUMERICAL_METHODS, + TRANSFORMER_REGISTRY, TransformerSpec, get_spec, resolve_method, @@ -140,7 +141,28 @@ def get_numerical_transformer_steps( **kwargs, ): """Return the ordered ``(name, transformer)`` steps for a numerical ``method``.""" - method = resolve_method(method, NUMERICAL_METHODS, NUMERICAL_ALIASES) + return _get_numerical_transformer_steps( + method, add_imputer, imputer_strategy, imputer_kwargs, add_missing_indicator, scaling, kwargs + ) + + +def _get_numerical_transformer_steps( + method, + add_imputer, + imputer_strategy, + imputer_kwargs, + add_missing_indicator, + scaling, + kwargs, + *, + is_group=False, +): + methods = ( + {name for name, spec in TRANSFORMER_REGISTRY.items() if spec.group_compatible and spec.is_numerical} + if is_group + else NUMERICAL_METHODS + ) + method = resolve_method(method, methods, NUMERICAL_ALIASES) steps = [] if add_imputer: @@ -164,13 +186,13 @@ def get_numerical_transformer_steps( if scaling in scalers and scaling != method and method != "none": steps.append(scalers[scaling]) - if method not in NUMERICAL_METHODS: + if method not in methods: raise invalid_param_error( "get_numerical_transformer_steps", "method", method, "unrecognized numerical preprocessing method", - valid=set(NUMERICAL_METHODS), + valid=set(methods), ) spec = get_spec(method) @@ -290,6 +312,17 @@ def create_transformer( run is configured with ``target_aware=False``; such a combination cannot be satisfied and is rejected instead of silently ignored. """ + return _create_transformer(method, is_numerical=is_numerical, config=config, representation=representation) + + +def _create_transformer( + method: str, + *, + is_numerical: bool, + config: PreprocessorConfig, + representation: RepresentationConfig | None = None, + is_group: bool = False, +) -> Pipeline | FeatureUnion: if representation is None: shared_kwargs = { "task": config.task, @@ -308,7 +341,7 @@ def create_transformer( "create_transformer", "representation", representation, "must be a RepresentationConfig or None" ) representation = _normalize_representation_config( - representation, is_numerical=is_numerical, path="create_transformer.representation" + representation, is_numerical=is_numerical, path="create_transformer.representation", is_group=is_group ) resolved_method = config.resolve_numerical(method) if is_numerical else config.resolve_categorical(method) if resolved_method != representation.method: @@ -323,7 +356,11 @@ def create_transformer( shared_kwargs = {key: value for key, value in settings.items() if key not in {"method", "params", "name"}} shared_kwargs.update(settings["params"]) - known = method in NUMERICAL_METHODS if is_numerical else method in CATEGORICAL_METHODS + known = ( + method in TRANSFORMER_REGISTRY + if is_group + else (method in NUMERICAL_METHODS if is_numerical else method in CATEGORICAL_METHODS) + ) if known: spec = get_spec(method) if representation is None and spec.requires_target and not config.target_aware: @@ -333,7 +370,18 @@ def create_transformer( ) plan = config.imputation_plan(is_numerical=is_numerical) - if is_numerical: + if is_group: + steps = _get_numerical_transformer_steps( + method, + plan["add_imputer"], + plan["strategy"], + None, + False, + config.scaling, + shared_kwargs, + is_group=True, + ) + elif is_numerical: steps = get_numerical_transformer_steps( method=method, add_imputer=plan["add_imputer"], @@ -409,21 +457,48 @@ def build_column_transformer( *, sparse_threshold: float = 0.3, ) -> ColumnTransformer: - """Assemble the per-column pipelines into the final ColumnTransformer. + """Assemble single-column and declared group pipelines into a ColumnTransformer. Numerical steps are prefixed ``num_`` and categorical steps ``cat_`` to match the block names the Preprocessor exposes (see :func:`_step_names` for labels that cannot be embedded in a step name); untransformed columns pass through via - ``remainder="passthrough"``. Each step selects its column by + ``remainder="passthrough"``. Single-column steps select their column by the label's string form: scikit-learn reads an integer selector as a *position*, so the Preprocessor fits and transforms the ColumnTransformer on a frame whose labels are strings (see :func:`~pretab.compose.feature_detection.with_string_labels`). + Groups select ordered lists of those internal labels and own their sources + exclusively. Blocks are ordered as numerical singles, declared groups, then + categorical singles. Group steps use ``group_``; a collision with an + input label or single-column block key is rejected before construction. """ - blocks = [("num", feature) for feature in numerical_features] - blocks += [("cat", feature) for feature in categorical_features] + groups = {group.name: group for group in config.feature_groups} + claimed = {label for group in config.feature_groups for label in group.columns} + blocks = [("num", feature) for feature in numerical_features if feature not in claimed] + blocks += [("group", group.name) for group in config.feature_groups] + blocks += [("cat", feature) for feature in categorical_features if feature not in claimed] + if groups: + raw_labels = {str(label) for label in [*numerical_features, *categorical_features]} + single_names = {f"{kind}_{feature}" for kind, feature in blocks if kind != "group"} + for group in config.feature_groups: + public_name = f"group_{group.name}" + if public_name in raw_labels or public_name in single_names: + raise invalid_param_error( + f"feature_groups[{group.name!r}]", + "name", + group.name, + f"public block key {public_name!r} conflicts with an input label or single-column block", + ) transformers = [] for (kind, feature), name in zip(blocks, _step_names(blocks), strict=True): + if kind == "group": + group = groups[feature] + representation = config.group_representation_for(group) + pipeline = _create_transformer( + representation.method, is_numerical=True, config=config, representation=representation, is_group=True + ) + transformers.append((name, pipeline, [str(label) for label in group.columns])) + continue is_numerical = kind == "num" method = config.method_for(feature, is_numerical=is_numerical) if isinstance(config.feature_preprocessing.get(feature, method), str): diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index 8afd472..fe46757 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -1,14 +1,17 @@ """Unit tests for :mod:`pretab.compose.factory`.""" -from dataclasses import fields +from dataclasses import fields, replace from unittest.mock import Mock, call, patch import numpy as np import pandas as pd import pytest from scipy.sparse import issparse +from sklearn.base import clone from sklearn.compose import ColumnTransformer +from sklearn.impute import SimpleImputer from sklearn.pipeline import FeatureUnion, Pipeline +from sklearn.preprocessing import MinMaxScaler, StandardScaler from pretab import Preprocessor from pretab.compose.config import PreprocessorConfig, RepresentationConfig @@ -20,7 +23,8 @@ get_categorical_transformer_steps, get_numerical_transformer_steps, ) -from pretab.compose.registry import TransformerSpec, get_spec +from pretab.compose.feature_detection import with_string_labels +from pretab.compose.registry import TRANSFORMER_REGISTRY, TransformerSpec, get_spec from pretab.core.parameters import UNSET from pretab.exceptions import ConfigWarning, InvalidParamError @@ -199,6 +203,188 @@ def test_build_column_transformer_fits_and_transforms(make_config, sample_frame) assert out.shape[0] == len(sample_frame) +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_grouped_factory_selects_sources_once_in_declared_order(make_config, method): + config = make_config(feature_groups={"location": {"columns": ["y", "x"], "representation": method}}) + transformer = build_column_transformer(config, ["x", "untouched", "y"], ["city"]) + + assert [(name, columns) for name, _, columns in transformer.transformers] == [ + ("num_untouched", ["untouched"]), + ("group_location", ["y", "x"]), + ("cat_city", ["city"]), + ] + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_grouped_factory_preserves_declaration_order_between_singles(make_config, reverse): + groups = [ + {"name": "first", "columns": ["y", "x"], "representation": "tensor"}, + {"name": "second", "columns": ["w", "z"], "representation": "thinplate"}, + ] + if reverse: + groups.reverse() + config = make_config(feature_groups=groups) + transformer = build_column_transformer(config, ["w", "x", "untouched", "y", "z"], ["city"]) + assert [(name, columns) for name, _, columns in transformer.transformers] == [ + ("num_untouched", ["untouched"]), + *[(f"group_{group['name']}", group["columns"]) for group in groups], + ("cat_city", ["city"]), + ] + assert [group.name for group in config.feature_groups] == [group["name"] for group in groups] + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("scaling", [None, "standardization", "minmax"]) +@pytest.mark.parametrize("missing_policy", ["impute", "impute_with_indicator", "separate_state"]) +def test_grouped_factory_matches_joint_reference_without_indicator_inputs(make_config, method, scaling, missing_policy): + frame = pd.DataFrame(np.random.default_rng(42).normal(size=(24, 2)), columns=pd.Index(["x", "y"])) + frame.loc[[1, 7], "x"] = np.nan + before = frame.copy(deep=True) + options = ( + {"output_dim": 3, "degree": 2, "diff_order": 1, "placement_strategy": "quantile"} + if method == "tensorspline" + else {"n_components": 4, "landmark_strategy": "subsample", "rank_strategy": "nystroem", "random_state": 0} + ) + config = make_config( + numerical_method="ple", + output_dim=13, + degree=5, + adaptive=True, + target_aware=True, + placement_strategy="cart", + scaling=scaling, + missing_policy=missing_policy, + random_state=17, + feature_groups={"location": {"columns": ["y", "x"], "representation": {"method": method, **options}}}, + ) + transformer = build_column_transformer(config, ["x", "y"], [], sparse_threshold=0.0) + result = transformer.fit_transform(frame) + assert isinstance(result, np.ndarray) + block = transformer.named_transformers_["group_location"] + pipeline = dict(block.transformer_list)["representation"] if isinstance(block, FeatureUnion) else block + assert isinstance(pipeline, Pipeline) + leaf = pipeline.named_steps[method] + assert leaf.n_features_in_ == 2 + assert pipeline.named_steps["imputer"].statistics_.shape == (2,) + assert pipeline.named_steps["imputer"].add_indicator is False + for key, value in options.items(): + assert getattr(leaf, key) == value + + reference_steps: list[tuple[str, object]] = [ + ("imputer", SimpleImputer(strategy="median", keep_empty_features=True)) + ] + if scaling is not None: + scaler = StandardScaler() if scaling == "standardization" else MinMaxScaler(feature_range=(-1, 1)) + reference_steps.append(("scaler", scaler)) + reference_steps.append((method, get_spec(method).transformer_cls(**options))) + reference = Pipeline(reference_steps) + expected = reference.fit_transform(frame[["y", "x"]]) + width = expected.shape[1] + assert width == (9 if method == "tensorspline" else 4) + np.testing.assert_allclose(result[:, :width], expected, rtol=1e-12, atol=1e-12) + + missing_columns = ["x"] if missing_policy == "impute_with_indicator" else ["y", "x"] + indicator_width = 0 if missing_policy == "impute" else len(missing_columns) + assert result.shape == (len(frame), width + indicator_width) + assert isinstance(block, Pipeline if missing_policy == "impute" else FeatureUnion) + if indicator_width: + np.testing.assert_array_equal(result[:, width:], frame[missing_columns].isna().to_numpy(dtype=float)) + + heldout = frame.iloc[:4].copy() + heldout.loc[0, "y"] = np.nan + transformed = transformer.transform(heldout[["y", "x"]]) + assert isinstance(transformed, np.ndarray) + np.testing.assert_allclose(transformed[:, :width], reference.transform(heldout[["y", "x"]]), rtol=1e-12, atol=1e-12) + if indicator_width: + np.testing.assert_array_equal(transformed[:, width:], heldout[missing_columns].isna().to_numpy(dtype=float)) + assert transformed.shape[1] == result.shape[1] + pd.testing.assert_frame_equal(frame, before) + + +def test_grouped_factory_maps_integer_labels_without_positional_selection(make_config): + frame = pd.DataFrame(np.random.default_rng(0).normal(size=(16, 3)), columns=pd.Index([7, 3, 9])) + config = make_config( + feature_groups={ + "location": { + "columns": [3, 7], + "representation": {"method": "tprs", "n_components": 2, "landmark_strategy": "subsample"}, + } + }, + random_state=0, + ) + transformer = build_column_transformer(config, [7, 3, 9], []) + assert [(name, columns) for name, _, columns in transformer.transformers] == [ + ("num_9", ["9"]), + ("group_location", ["3", "7"]), + ] + normalized = with_string_labels(frame) + result = transformer.fit_transform(normalized) + np.testing.assert_array_equal(result, transformer.transform(normalized[["9", "3", "7"]])) + assert config.feature_groups[0].columns == (3, 7) + assert list(frame.columns) == [7, 3, 9] + + +def test_grouped_factory_keeps_private_step_names_safe_and_unique(make_config): + frame = pd.DataFrame(np.random.default_rng(1).normal(size=(16, 4)), columns=pd.Index(["_unsafe", "col0", "x", "y"])) + frame["__city"] = ["a", "b"] * 8 + config = make_config( + feature_groups={ + "num_col0": { + "columns": ["x", "y"], + "representation": {"method": "tprs", "n_components": 2, "landmark_strategy": "subsample"}, + } + }, + random_state=0, + ) + transformer = build_column_transformer(config, ["_unsafe", "col0", "x", "y"], ["__city"]) + names = [name for name, _, _ in transformer.transformers] + assert names == ["num_col0_1", "num_col0", "group_num_col0", "cat_col3"] + assert len(set(names)) == len(names) + assert all("__" not in name for name in names) + cloned = clone(transformer) + assert isinstance(cloned, ColumnTransformer) + np.testing.assert_array_equal(transformer.fit_transform(frame), cloned.fit_transform(frame)) + + +@pytest.mark.parametrize("claimed_collision", [False, True]) +def test_group_public_key_collision_precedes_all_construction(make_config, monkeypatch, claimed_collision): + columns = ["group_location", "y"] if claimed_collision else ["x", "y"] + config = make_config(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) + + def unexpected(*args, **kwargs): + pytest.fail("A group public-key collision must be rejected before constructing any block") + + monkeypatch.setattr("pretab.compose.factory._create_transformer", unexpected) + with pytest.raises(InvalidParamError, match=r"feature_groups\['location'\].name.*location") as failure: + build_column_transformer(config, ["untouched", "x", "y", "group_location"], []) + assert "public block key 'group_location'" in str(failure.value) + + +@pytest.mark.parametrize("method", ["tensor", "thinplate"]) +def test_grouped_factory_capability_is_rechecked_before_construction(make_config, monkeypatch, method): + config = make_config(feature_groups={"location": {"columns": ["x", "y"], "representation": method}}) + canonical = config.group_representation_for(config.feature_groups[0]).method + spec = get_spec(canonical) + monkeypatch.setitem(TRANSFORMER_REGISTRY, canonical, replace(spec, group_compatible=False)) + with pytest.raises(InvalidParamError, match="does not support explicit feature groups"): + build_column_transformer(config, ["x", "y"], []) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs", "rff", "nystroem"]) +def test_grouped_factory_does_not_unlock_single_column_step_selection(method): + with pytest.raises(InvalidParamError, match="unrecognized numerical preprocessing method"): + get_numerical_transformer_steps(method, is_group=True) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_grouped_representation_cannot_enter_public_single_column_builder(make_config, method): + with pytest.raises(InvalidParamError, match=r"create_transformer\.representation\.method") as failure: + create_transformer( + method, is_numerical=True, config=make_config(), representation=RepresentationConfig(method=method) + ) + assert "unrecognized numerical preprocessing method" in str(failure.value) + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) def test_preprocessor_fits_structured_representation(typed): settings = {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}} From 3ca0f4ec436e3357501e9b7c61382004c2321aa6 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 10:41:12 +0100 Subject: [PATCH 39/86] feat(compose): expose grouped output layout and lineage --- pretab/compose/inspection.py | 46 +++++++++-- pretab/core/representation.py | 4 + pretab/preprocessor.py | 28 ++++--- tests/compose/test_block_layout_contract.py | 90 +++++++++++++++++++++ tests/compose/test_config.py | 22 ++--- tests/compose/test_feature_groups_config.py | 43 ++++++---- tests/compose/test_inspection.py | 82 +++++++++++++++++++ tests/integration/test_feature_lineage.py | 23 ++++++ tests/regression/_snapshots/public_api.json | 2 +- 9 files changed, 297 insertions(+), 43 deletions(-) diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index ab9e1ed..b8cdab8 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -11,6 +11,7 @@ from collections.abc import Iterator from dataclasses import dataclass from typing import Any, cast +from urllib.parse import quote import numpy as np from sklearn.base import clone @@ -69,6 +70,10 @@ class _FittedBlock: def public_name(self) -> str: return block_name(self.step_name, self.columns) + @property + def group_id(self) -> str | None: + return self.step_name if self.step_name.startswith("group_") else None + @property def span(self) -> slice: return self._column_transformer.output_indices_[self.step_name] @@ -168,13 +173,20 @@ def clean_feature_names(column_transformer, names, *, rename=None): column labels to the input feature names ``names`` were built from (see :func:`feature_names_out`); a step of a renamed column is then reported under the new name, e.g. ``num_feature_0`` as ``num_age``. + Group names retain their public block key and prepend percent-escaped source + labels in declared order to the leaf output name. """ rename = rename or {} - step_to_columns = { - block.step_name: [rename.get(str(column), column) for column in block.columns] - for block in _iter_fitted_blocks(column_transformer) - if block.step_name != "remainder" and len(block.columns) == 1 - } + step_to_columns = {} + group_ids = set() + for block in _iter_fitted_blocks(column_transformer): + if block.step_name == "remainder": + continue + if block.group_id is not None: + group_ids.add(block.group_id) + elif len(block.columns) != 1: + continue + step_to_columns[block.step_name] = [rename.get(str(column), column) for column in block.columns] cleaned = [] for raw in names: raw = str(raw) @@ -183,6 +195,10 @@ def clean_feature_names(column_transformer, names, *, rename=None): if not sep or columns is None: cleaned.append(raw) continue + if step_name in group_ids: + sources = "+".join(quote(str(column), safe="") for column in columns) + cleaned.append(f"{step_name}__{sources}__{inner_name}") + continue block = _block(step_name, columns) if block is not None: kind_prefix, feature = block @@ -261,6 +277,16 @@ def build_feature_info(column_transformer, *, embeddings, embedding_dimensions): ) preprocessing_type = " -> ".join(steps) + group_id = block.group_id + if group_id is not None: + numerical_feature_info[group_id] = { + "preprocessing": preprocessing_type, + "dimension": dimension, + "categories": None, + "group": group_id.removeprefix("group_"), + "source_features": tuple(columns), + } + continue for feature_name in columns: categories = None if "continuous_ordinal" in steps: @@ -450,6 +476,7 @@ def build_feature_lineage(column_transformer): width = span.stop - span.start if width == 0: continue + group_id = block.group_id if transformer == "passthrough" or name == "remainder": for offset in range(width): index = span.start + offset @@ -492,20 +519,26 @@ def build_feature_lineage(column_transformer): component_index=offset, uses_target=uses_target, is_interaction=is_interaction, + group_id=group_id, ) ) + indicator = missing_indicator.steps[-1][1] if isinstance(missing_indicator, Pipeline) else missing_indicator + missing_sources = getattr(indicator, "features_", range(len(columns))) for offset in range(missing_width): index = span.start + representation_width + offset records.append( FeatureLineage( output_feature=output_names[index], output_index=index, - source_features=source_features, + source_features=(str(columns[missing_sources[offset]]),) + if group_id is not None + else source_features, family="missing_state", component="indicator", component_index=offset, uses_target=False, is_interaction=False, + group_id=group_id, ) ) continue @@ -523,6 +556,7 @@ def build_feature_lineage(column_transformer): component_index=offset, uses_target=uses_target, is_interaction=is_interaction, + group_id=group_id, ) ) records.sort(key=lambda record: record.output_index) diff --git a/pretab/core/representation.py b/pretab/core/representation.py index bf1bf8e..d023a58 100644 --- a/pretab/core/representation.py +++ b/pretab/core/representation.py @@ -173,6 +173,8 @@ class FeatureLineage: Whether the producing transformer consumed ``y``. is_interaction : bool Whether the column mixes multiple input features. + group_id : str or None, default=None + Public block key of an explicit feature group, or ``None`` for singles. """ output_feature: str @@ -183,6 +185,7 @@ class FeatureLineage: component_index: int uses_target: bool is_interaction: bool + group_id: str | None = None def to_dict(self) -> dict: """Return a JSON-serializable dictionary representation.""" @@ -195,6 +198,7 @@ def to_dict(self) -> dict: "component_index": self.component_index, "uses_target": self.uses_target, "is_interaction": self.is_interaction, + **({"group_id": self.group_id} if self.group_id is not None else {}), } diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index f291b8c..face0f6 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -355,8 +355,8 @@ class Preprocessor(TransformerMixin, BaseEstimator): Ordered named declarations of source columns and representation settings. Constructor inputs remain unchanged; :meth:`get_resolved_config` returns detached declarations with canonical methods and applicable settings. - ``None`` or an empty collection keeps single-column processing. Nonempty - declarations are rejected by ``fit``. + ``None`` or an empty collection keeps single-column processing. Each + nonempty declaration fits one joint block over its ordered sources. Attributes ---------- @@ -637,12 +637,6 @@ def fit(self, X, y=None, embeddings=None): ) config.validate_feature_groups(group_frame.columns, group_numerical, y=y) with_string_labels(group_frame) - raise invalid_param_error( - type(self).__name__, - "feature_groups", - tuple(group.name for group in config.feature_groups), - "nonempty group declarations cannot be fitted through the single-column composition route", - ) fitted_on_array = not has_column_labels(X) X = to_dataframe(X) @@ -1045,11 +1039,12 @@ def total_output_dim_(self) -> int: @property def output_dims_(self) -> dict: - """Per-feature expanded output-column counts. + """Expanded output-column counts per single feature or group. Fitted attribute (available only after ``fit``). Maps each input feature - (by name) to the number of columns it contributes to the transformed - array, complementing the scalar :attr:`total_output_dim_`. The values sum + (by name), or each ``group_`` block, to its actual transformed width, + complementing the scalar :attr:`total_output_dim_`. Group members do not + receive separate widths. The values sum to :attr:`total_output_dim_`. Useful when features get different ``output_dim`` values (via ``feature_preprocessing``) or expand to a non-uniform width (e.g. one-hot encoded categoricals). @@ -1063,7 +1058,9 @@ def output_dims_(self) -> dict: width = span.stop - span.start if width == 0: continue - if block.step_name == "remainder": + if block.group_id is not None: + dims[block.group_id] = width + elif block.step_name == "remainder": # Passthrough columns: one output column per untransformed feature. for full in column_transformer.get_feature_names_out()[span]: feature = full.split("__", 1)[-1] if "__" in full else full @@ -1363,7 +1360,9 @@ def get_feature_info(self, verbose=True): ------- tuple of dicts numerical_feature_info : dict - Metadata for numerical features. + Metadata for numerical singles and groups. Each group appears + once under ``group_`` with its actual joint dimension, + ``group`` name, and ordered original-label ``source_features``. categorical_feature_info : dict Metadata for categorical features. embedding_feature_info : dict @@ -1379,6 +1378,9 @@ def get_feature_info(self, verbose=True): ) input_labels = self._input_labels() numerical_feature_info = {input_labels.get(key, key): info for key, info in numerical_feature_info.items()} + for info in numerical_feature_info.values(): + if "group" in info: + info["source_features"] = tuple(input_labels.get(column, column) for column in info["source_features"]) categorical_feature_info = {input_labels.get(key, key): info for key, info in categorical_feature_info.items()} if verbose: diff --git a/tests/compose/test_block_layout_contract.py b/tests/compose/test_block_layout_contract.py index c256b72..b7cbe18 100644 --- a/tests/compose/test_block_layout_contract.py +++ b/tests/compose/test_block_layout_contract.py @@ -193,6 +193,96 @@ def test_fitted_block_layout_agrees_across_views(layout_data, output_format, par np.testing.assert_array_equal(_dense(blocks[name])[:, -1], frame[feature].isna().astype(float)) +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_grouped_block_layout_agrees_across_views(layout_data, method, missing, output_format): + frame, target = layout_data + frame = frame.assign(spare=np.linspace(2.0, 7.0, len(frame))) + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + preprocessor = Preprocessor( + numerical_method="none", + categorical_method="one-hot", + target_aware=False, + placement_strategy="uniform", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + output_format=output_format, + output_structure="blocks", + feature_groups={"location": {"columns": ["other", "value"], "representation": representation}}, + ).fit(frame, target) + matrix = preprocessor.transform(frame, return_array=True) + blocks = preprocessor.transform(frame) + assert isinstance(blocks, dict) + assert list(blocks) == ["num_spare", "group_location", "cat_city"] + names = preprocessor.get_feature_names_out() + lineage = preprocessor.get_feature_lineage() + numerical, categorical, embeddings = preprocessor.get_feature_info(verbose=False) + dimensions = preprocessor.output_dims_ + assert list(dimensions) == ["spare", "group_location", "city"] + assert list(numerical) == ["spare", "group_location"] + assert list(categorical) == ["city"] + assert embeddings == {} + assert "location" not in numerical + assert numerical["group_location"]["source_features"] == ("other", "value") + assert [record.output_feature for record in lineage] == list(names) + assert [record.output_index for record in lineage] == list(range(len(names))) + offset = 0 + for (name, start, width), key in zip(get_output_slices(preprocessor.column_transformer_), dimensions, strict=True): + assert start == offset + assert width == dimensions[key] == {**numerical, **categorical}[key]["dimension"] + assert width == len(names[start : start + width]) == np.shape(blocks[name])[1] + np.testing.assert_array_equal(_dense(blocks[name]), _dense(matrix)[:, start : start + width]) + offset += width + assert offset == sum(dimensions.values()) == preprocessor.total_output_dim_ == len(names) == len(lineage) + assert offset == np.shape(matrix)[1] + np.testing.assert_array_equal(np.hstack([_dense(block) for block in blocks.values()]), _dense(matrix)) + span = preprocessor.column_transformer_.output_indices_["group_location"] + records = lineage[span] + basis_width = 9 if method == "tensorspline" else 3 + assert all(record.group_id == "group_location" for record in records) + assert all(record.source_features == ("other", "value") for record in records[:basis_width]) + indicators = records[basis_width:] + expected_sources = {"none": [], "observed": [("value",)], "all": [("other",), ("value",)]}[missing] + assert [record.source_features for record in indicators] == expected_sources + for index, record in enumerate(indicators): + assert record.family == "missing_state" and record.component == "indicator" + assert not record.is_interaction and not record.uses_target + source = record.source_features[0] + np.testing.assert_array_equal(_dense(blocks["group_location"])[:, basis_width + index], frame[source].isna()) + assert dimensions["group_location"] == basis_width + len(expected_sources) + + +def test_group_metadata_preserves_original_integer_labels_and_renamed_display_names(): + frame = pd.DataFrame(np.random.default_rng(42).normal(size=(24, 3)), columns=pd.Index([7, 3, 11])) + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + feature_groups={ + "location": { + "columns": [11, 7], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + } + }, + ).fit(frame) + assert preprocessor.output_dims_ == {3: 1, "group_location": 9} + numerical, categorical, embeddings = preprocessor.get_feature_info(verbose=False) + assert list(numerical) == [3, "group_location"] + assert numerical["group_location"]["source_features"] == (11, 7) + assert categorical == embeddings == {} + original = preprocessor.get_feature_names_out() + renamed = preprocessor.get_feature_names_out(["west%", "single", "east+"]) + assert all(name.startswith("group_location__east%2B+west%25__") for name in renamed[1:]) + assert len(renamed) == len(original) == preprocessor.total_output_dim_ + np.testing.assert_array_equal(preprocessor.get_feature_names_out(), original) + assert all(record.source_features == ("11", "7") for record in preprocessor.get_feature_lineage()[1:]) + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("output_format", ["dense", "sparse"]) @pytest.mark.parametrize("missing_policy", [None, "separate_state"]) diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index d4d527f..794b4b4 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -270,15 +270,19 @@ def test_empty_groups_preserve_single_column_values_names_and_fingerprint(sample assert processor.get_resolved_config() == expected_config -def test_nonempty_groups_cannot_be_silently_ignored_by_single_column_fitting(sample_frame, monkeypatch): - def reject_construction(*args, **kwargs): - raise AssertionError("Group refusal must precede factory construction and estimator fitting") - - monkeypatch.setattr("pretab.preprocessor.build_column_transformer", reject_construction) - processor = Preprocessor(feature_groups={"location": {"columns": ["age", "second"], "representation": "tprs"}}) - with pytest.raises(InvalidParamError, match="single-column composition route"): - processor.fit(sample_frame.assign(second=sample_frame["age"] + 1)) - assert not hasattr(processor, "column_transformer_") +def test_nonempty_groups_cannot_be_silently_ignored_by_single_column_fitting(sample_frame): + processor = Preprocessor( + feature_groups={ + "location": { + "columns": ["age", "second"], + "representation": {"method": "tprs", "n_components": 2, "landmark_strategy": "subsample"}, + } + } + ).fit(sample_frame.assign(second=sample_frame["age"] + 1)) + names = processor.column_transformer_.named_transformers_ + assert "group_location" in names + assert "num_age" not in names and "num_second" not in names + assert processor.output_dims_["group_location"] == 2 def test_none_method_normalizes_to_none(make_config): diff --git a/tests/compose/test_feature_groups_config.py b/tests/compose/test_feature_groups_config.py index 9775911..b62bf88 100644 --- a/tests/compose/test_feature_groups_config.py +++ b/tests/compose/test_feature_groups_config.py @@ -14,6 +14,14 @@ from pretab.exceptions import IncompatibleParamsError, InvalidParamError, OptionalDependencyError, PretabDataError +@pytest.fixture +def stop_after_group_preflight(monkeypatch): + def reached(*args, **kwargs): + raise RuntimeError("group preflight complete") + + monkeypatch.setattr("pretab.preprocessor.build_column_transformer", reached) + + @pytest.fixture def group_frame(): return pd.DataFrame( @@ -117,13 +125,13 @@ def test_categorical_sources_are_not_coerced_to_numerical(group_frame, values): @pytest.mark.parametrize("dtype", ["int64", "Int64"]) -def test_explicit_integer_routing_remains_available_to_groups(group_frame, dtype): +def test_explicit_integer_routing_remains_available_to_groups(group_frame, dtype, stop_after_group_preflight): processor = Preprocessor( cat_cutoff=3, treat_all_integers_as_numerical=True, feature_groups={"location": {"columns": ["x", "code"], "representation": "tprs"}}, ) - with pytest.raises(InvalidParamError, match="single-column composition route"): + with pytest.raises(RuntimeError, match="group preflight complete"): processor.fit(group_frame.assign(code=pd.Series([1, 1, 2], dtype=dtype))) @@ -138,17 +146,18 @@ def test_explicit_integer_routing_remains_available_to_groups(group_frame, dtype (False, ["feature_0", "absent"], 1), ], ) -def test_group_sources_follow_existing_label_route(named, columns, missing_index): +def test_group_sources_follow_existing_label_route(named, columns, missing_index, stop_after_group_preflight): values = np.array([[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]]) data = pd.DataFrame(values, columns=pd.Index([7, 3])) if named else values before = data.copy() processor = Preprocessor(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) expected = ( - "single-column composition route" + "group preflight complete" if missing_index is None else escape(f"feature_groups['location'].columns[{missing_index}]") ) - with pytest.raises(InvalidParamError, match=expected): + error = RuntimeError if missing_index is None else InvalidParamError + with pytest.raises(error, match=expected): processor.fit(data) if named: pd.testing.assert_frame_equal(data, before) @@ -178,7 +187,9 @@ def unexpected(*args, **kwargs): @pytest.mark.parametrize("usage", ["required", "optional"]) @pytest.mark.parametrize("has_target", [False, True]) -def test_group_target_requirements_keep_typed_errors(group_frame, monkeypatch, usage, has_target): +def test_group_target_requirements_keep_typed_errors( + group_frame, monkeypatch, usage, has_target, stop_after_group_preflight +): def unexpected(*args, **kwargs): pytest.fail("Group target validation must not construct a transformer") @@ -198,7 +209,7 @@ def unexpected(*args, **kwargs): ) target = np.array([0.0, 1.0, 2.0]) if has_target else None if has_target: - with pytest.raises(InvalidParamError, match="single-column composition route"): + with pytest.raises(RuntimeError, match="group preflight complete"): processor.fit(group_frame, target) else: with pytest.raises(IncompatibleParamsError, match=escape("feature_groups['location'].representation.method")): @@ -207,7 +218,7 @@ def unexpected(*args, **kwargs): @pytest.mark.parametrize("local_off", [False, True]) -def test_group_target_check_uses_resolved_settings(group_frame, monkeypatch, local_off): +def test_group_target_check_uses_resolved_settings(group_frame, monkeypatch, local_off, stop_after_group_preflight): spec = TRANSFORMER_REGISTRY["tprs"] monkeypatch.setitem( TRANSFORMER_REGISTRY, @@ -220,14 +231,16 @@ def test_group_target_check_uses_resolved_settings(group_frame, monkeypatch, loc placement_strategy="cart", feature_groups={"location": {"columns": ["x", "y"], "representation": representation}}, ) - error = InvalidParamError if local_off else IncompatibleParamsError - expected = "single-column composition route" if local_off else "requires y at fit time" + error = RuntimeError if local_off else IncompatibleParamsError + expected = "group preflight complete" if local_off else "requires y at fit time" with pytest.raises(error, match=expected): processor.fit(group_frame) @pytest.mark.parametrize("available", [False, True]) -def test_group_dependency_check_is_contextual_without_import_or_construction(group_frame, monkeypatch, available): +def test_group_dependency_check_is_contextual_without_import_or_construction( + group_frame, monkeypatch, available, stop_after_group_preflight +): discovered = [] def discover(module_name): @@ -245,7 +258,7 @@ def unexpected(*args, **kwargs): monkeypatch.setattr("pretab.core.dependencies.importlib.import_module", unexpected) processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) if available: - with pytest.raises(InvalidParamError, match="single-column composition route"): + with pytest.raises(RuntimeError, match="group preflight complete"): processor.fit(group_frame) else: with pytest.raises(OptionalDependencyError) as failure: @@ -278,11 +291,13 @@ def test_group_placement_dependency_keeps_context_and_install_hint(group_frame, assert "pip install pretab[lightgbm]" in str(failure.value) -def test_builtin_group_preflight_does_not_discover_unselected_extras(group_frame, monkeypatch): +def test_builtin_group_preflight_does_not_discover_unselected_extras( + group_frame, monkeypatch, stop_after_group_preflight +): def unexpected(*args, **kwargs): pytest.fail("No optional dependency is selected") monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", unexpected) processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) - with pytest.raises(InvalidParamError, match="single-column composition route"): + with pytest.raises(RuntimeError, match="group preflight complete"): processor.fit(group_frame) diff --git a/tests/compose/test_inspection.py b/tests/compose/test_inspection.py index cf7dc9b..cb0ff5f 100644 --- a/tests/compose/test_inspection.py +++ b/tests/compose/test_inspection.py @@ -18,8 +18,10 @@ _locate_block_representation, block_uses_target, build_feature_info, + build_feature_lineage, build_transformer_summary, clean_feature_names, + feature_names_out, get_output_slices, ) from pretab.core.representation import RepresentationSpec @@ -32,6 +34,86 @@ def fitted_ct(make_config, sample_frame): return ct, sample_frame +@pytest.fixture(params=["tensorspline", "tprs"]) +def grouped_ct(request, make_config): + values = np.random.default_rng(42).normal(size=(24, 3)) + frame = pd.DataFrame(values, columns=pd.Index(["age", "x% west", "y+east"])) + frame["city"] = ["a", "b"] * 12 + options = ( + {"output_dim": 3, "degree": 2} + if request.param == "tensorspline" + else {"n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + config = make_config( + feature_groups={ + "location": {"columns": ["y+east", "x% west"], "representation": {"method": request.param, **options}} + } + ) + transformer = build_column_transformer(config, ["age", "x% west", "y+east"], ["city"]) + transformer.fit(frame) + return transformer, frame + + +def test_group_feature_info_counts_joint_width_once(grouped_ct): + transformer, _ = grouped_ct + info = build_feature_info(transformer, embeddings=False, embedding_dimensions={}) + assert len(info) == 3 + numerical, categorical, embeddings = info + assert list(numerical) == ["age", "group_location"] + assert list(categorical) == ["city"] + assert embeddings == {} + group = numerical["group_location"] + span = transformer.output_indices_["group_location"] + assert group["dimension"] == span.stop - span.start + assert group["group"] == "location" + assert group["source_features"] == ("y+east", "x% west") + assert group["categories"] is None + assert set(numerical["age"]) == {"preprocessing", "dimension", "categories"} + + +def test_group_names_encode_ordered_sources_and_preserve_leaf_names(grouped_ct): + transformer, _ = grouped_ct + raw = transformer.get_feature_names_out() + names = feature_names_out(transformer) + span = transformer.output_indices_["group_location"] + expected = [f"group_location__y%2Beast+x%25%20west__{name.partition('__')[2]}" for name in raw[span]] + assert names[span] == expected + assert len(set(names)) == len(names) + assert names[0] == "num_age" + + +def test_explicit_group_display_names_preserve_identity_without_mutating_fit(grouped_ct): + transformer, _ = grouped_ct + original = feature_names_out(transformer) + fitted = transformer.feature_names_in_.copy() + renamed = feature_names_out(transformer, ["years", "west%", "east+", "town"]) + span = transformer.output_indices_["group_location"] + assert all(name.startswith("group_location__east%2B+west%25__") for name in renamed[span]) + assert renamed[0] == "num_years" + assert len(renamed) == len(original) + assert feature_names_out(transformer) == original + np.testing.assert_array_equal(transformer.feature_names_in_, fitted) + with pytest.raises(ValueError): + feature_names_out(transformer, ["too", "short"]) + + +def test_group_lineage_covers_actual_span_with_one_identity(grouped_ct): + transformer, _ = grouped_ct + names = feature_names_out(transformer) + lineage = build_feature_lineage(transformer) + span = transformer.output_indices_["group_location"] + assert [record.output_feature for record in lineage] == names + assert [record.output_index for record in lineage] == list(range(len(names))) + for record in lineage[span]: + assert record.group_id == "group_location" + assert record.source_features == ("y+east", "x% west") + assert record.to_dict()["group_id"] == "group_location" + assert [record.component_index for record in lineage[span]] == list(range(span.stop - span.start)) + for record in [*lineage[: span.start], *lineage[span.stop :]]: + assert record.group_id is None + assert "group_id" not in record.to_dict() + + @pytest.fixture def declared_representation(): spec = RepresentationSpec( diff --git a/tests/integration/test_feature_lineage.py b/tests/integration/test_feature_lineage.py index 307d24b..5607819 100644 --- a/tests/integration/test_feature_lineage.py +++ b/tests/integration/test_feature_lineage.py @@ -8,6 +8,29 @@ from pretab.core.representation import FeatureLineage +def test_legacy_positional_lineage_keeps_default_group_and_dict_shape(): + record = FeatureLineage("num_age", 0, ("age",), "passthrough", "raw", 0, False, False) + assert record.group_id is None + assert record.to_dict() == { + "output_feature": "num_age", + "output_index": 0, + "source_features": ["age"], + "family": "passthrough", + "component": "raw", + "component_index": 0, + "uses_target": False, + "is_interaction": False, + } + + +def test_group_lineage_round_trips_through_dict(): + record = FeatureLineage("joint", 2, ("east", "west"), "tensor_product", "basis", 0, False, True, "group_location") + data = record.to_dict() + assert data["group_id"] == "group_location" + data["source_features"] = tuple(data["source_features"]) + assert FeatureLineage(**data) == record + + @pytest.fixture def mixed_frame(): rng = np.random.default_rng(0) diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index f910577..64a51ba 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -1121,7 +1121,7 @@ "pretab.BaseRepresentation": "()", "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None)", "pretab.FeatureGroup": "(name: 'str', columns: 'Sequence[Any]', representation: 'str | Mapping[str, Any] | RepresentationConfig') -> None", - "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool) -> None", + "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool, group_id: str | None = None) -> None", "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None, *, feature_groups=None)", "pretab.RepresentationConfig": "(method: 'str', output_dim: 'int | _Unset' = UNSET, target_aware: 'bool | _Unset' = UNSET, placement_strategy: 'str | _Unset' = UNSET, adaptive: 'bool | _Unset' = UNSET, min_output_dim: 'int | _Unset | None' = UNSET, max_output_dim: 'int | _Unset | None' = UNSET, params: 'Mapping[str, Any]' = , name: 'str | None' = None) -> None", "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", From ee44324898af21a165a261a2005ddde3f7c4584b Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 11:12:30 +0100 Subject: [PATCH 40/86] feat(compose): audit grouped widths in budgets and reports --- pretab/compose/serialize.py | 9 +- pretab/preprocessor.py | 45 ++++++++-- tests/compose/test_block_layout_contract.py | 92 ++++++++++++++++++++- tests/integration/test_fingerprint.py | 80 +++++++++++++++++- 4 files changed, 215 insertions(+), 11 deletions(-) diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index a2a1ae6..077ee5c 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -304,7 +304,9 @@ def _representation_summary(preprocessor) -> list: :func:`~pretab.compose.inspection.representation_leaf`), not the union itself. Blocks whose representation ends in a step without ``get_representation_spec`` (scikit-learn scalers and encoders, embeddings) - have no entry. The steps are fitted, so a spec that fails to build is a bug: + have no entry. Explicit groups also carry their public identity, actual full + block dimension and half-open fitted output slice, including raw indicators. + The steps are fitted, so a spec that fails to build is a bug: its error propagates instead of silently dropping the entry. """ summary: list = [] @@ -325,6 +327,11 @@ def _representation_summary(preprocessor) -> list: fits_block = getattr(leaf, "n_features_in_", len(block_columns)) == len(block_columns) entry = spec_fn(input_features=block_columns if fits_block else None).to_dict() entry["columns"] = block_columns + if block.group_id is not None: + span = block.span + entry["group_id"] = block.group_id + entry["dimension"] = span.stop - span.start + entry["output_slice"] = [span.start, span.stop] summary.append(entry) return summary diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index face0f6..ca98378 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -288,9 +288,10 @@ class Preprocessor(TransformerMixin, BaseEstimator): features. ``None`` disables the check. A violation is handled per ``overflow_policy``. max_features_per_input : int or None, default=None - Upper bound on the number of output columns any single input feature may - expand to. ``None`` disables the check. A violation is handled per - ``overflow_policy``. + Upper bound on the actual output width of each single feature or joint + feature group, including raw missing indicators. A group counts as one + unit; its width is not divided among sources. ``None`` disables the check. + A violation is handled per ``overflow_policy``. max_dense_memory : int or None, default=None Upper bound, in bytes, on the estimated dense output footprint (``n_rows * total_output_dim_ * itemsize``) evaluated against the training @@ -1314,10 +1315,21 @@ def _enforce_output_budget(self, n_rows: int) -> None: violations.append(f"total output columns ({total}) exceed max_output_features ({self.max_output_features})") if self.max_features_per_input is not None: + input_labels = self._input_labels() + group_sources = { + block.group_id: tuple(input_labels.get(column, column) for column in block.columns) + for block in _iter_fitted_blocks(self.column_transformer_) + if block.group_id is not None + } for feature, width in self.output_dims_.items(): if width > self.max_features_per_input: + unit = ( + f"group {feature!r} with sources {group_sources[feature]!r}" + if feature in group_sources + else f"feature {feature!r}" + ) violations.append( - f"feature {feature!r} expands to {width} columns, " + f"{unit} expands to {width} columns, " f"exceeding max_features_per_input ({self.max_features_per_input})" ) @@ -1530,15 +1542,29 @@ def reproducibility_report(self) -> dict: ------- dict Fingerprint, schema / library versions, random seed, output dtype and - format, input/output widths, and the per-feature representation - families -- everything needed to audit or reproduce the fit. + format, input/output widths, and representation families keyed by + source or public group key. Active groups also have a ``feature_groups`` + mapping with canonical string ``source_features``, actual full-block + ``dimension`` (including raw indicators), and half-open ``output_slice``. + Group metadata comes from the fitted graph, not current requests. """ check_is_fitted(self) spec = preprocessor_to_spec(self) representations = { - entry["columns"][0]: entry.get("family") for entry in spec["representations"] if entry.get("columns") + entry.get("group_id", entry["columns"][0]): entry.get("family") + for entry in spec["representations"] + if entry.get("columns") } - return { + groups = { + entry["group_id"]: { + "source_features": entry["columns"], + "dimension": entry["dimension"], + "output_slice": entry["output_slice"], + } + for entry in spec["representations"] + if "group_id" in entry + } + report = { "fingerprint": self.fingerprint_, "schema_version": SCHEMA_VERSION, "pretab_version": spec["pretab_version"], @@ -1550,6 +1576,9 @@ def reproducibility_report(self) -> dict: "n_output_features": len(spec["feature_names_out"]), "representations": representations, } + if groups: + report["feature_groups"] = groups + return report # --- Immutable lifecycle --- @property diff --git a/tests/compose/test_block_layout_contract.py b/tests/compose/test_block_layout_contract.py index b7cbe18..dd2ddb9 100644 --- a/tests/compose/test_block_layout_contract.py +++ b/tests/compose/test_block_layout_contract.py @@ -1,6 +1,7 @@ """Agreement between fitted block spans and the public output-layout APIs.""" import json +import warnings from contextlib import nullcontext from unittest.mock import Mock @@ -196,7 +197,8 @@ def test_fitted_block_layout_agrees_across_views(layout_data, output_format, par @pytest.mark.parametrize("method", ["tensorspline", "tprs"]) @pytest.mark.parametrize("missing", ["none", "observed", "all"]) @pytest.mark.parametrize("output_format", ["dense", "sparse"]) -def test_grouped_block_layout_agrees_across_views(layout_data, method, missing, output_format): +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_grouped_block_layout_agrees_across_views(layout_data, method, missing, output_format, dtype): frame, target = layout_data frame = frame.assign(spare=np.linspace(2.0, 7.0, len(frame))) representation = ( @@ -213,6 +215,7 @@ def test_grouped_block_layout_agrees_across_views(layout_data, method, missing, missing_policy="separate_state" if missing == "all" else None, output_format=output_format, output_structure="blocks", + dtype=dtype, feature_groups={"location": {"columns": ["other", "value"], "representation": representation}}, ).fit(frame, target) matrix = preprocessor.transform(frame, return_array=True) @@ -255,6 +258,85 @@ def test_grouped_block_layout_agrees_across_views(layout_data, method, missing, source = record.source_features[0] np.testing.assert_array_equal(_dense(blocks["group_location"])[:, basis_width + index], frame[source].isna()) assert dimensions["group_location"] == basis_width + len(expected_sources) + report = preprocessor.reproducibility_report() + assert report["fingerprint"] == preprocessor.fingerprint_ + assert report["n_output_features"] == offset + assert list(report["representations"]) == ["group_location"] + assert report["feature_groups"] == { + "group_location": { + "source_features": ["other", "value"], + "dimension": dimensions["group_location"], + "output_slice": [span.start, span.stop], + } + } + (entry,) = preprocessor.to_spec()["representations"] + assert entry["group_id"] == "group_location" + assert entry["columns"] == ["other", "value"] + assert entry["dimension"] == dimensions["group_location"] + assert entry["output_dim"] == basis_width + assert entry["output_slice"] == [span.start, span.stop] + assert json.loads(json.dumps(report, allow_nan=False)) == report + assert preprocessor.estimate_output_shape(frame) == np.shape(matrix) + assert preprocessor.estimate_memory(frame) == _dense(matrix).nbytes + limits = { + "max_output_features": offset, + "max_features_per_input": dimensions["group_location"], + "max_dense_memory": _dense(matrix).nbytes, + } + bounded = clone(preprocessor) + assert isinstance(bounded, Preprocessor) + bounded.set_params(**limits).fit(frame, target) + assert bounded.output_dims_ == dimensions + np.testing.assert_array_equal(_dense(bounded.transform(frame, return_array=True)), _dense(matrix)) + for budget, limit in limits.items(): + rejected = clone(preprocessor) + assert isinstance(rejected, Preprocessor) + rejected.set_params(**{budget: limit - 1}) + with pytest.raises(OutputBudgetError, match=budget) as failure: + rejected.fit(frame, target) + if budget == "max_features_per_input": + assert str(failure.value).count("group 'group_location'") == 1 + assert "('other', 'value')" in str(failure.value) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("overflow_policy", ["error", "warn", "ignore"]) +def test_group_budget_error_identifies_full_joint_width_and_sources(layout_data, method, overflow_policy): + frame, _ = layout_data + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + width = 9 if method == "tensorspline" else 3 + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + max_features_per_input=width - 1, + overflow_policy=overflow_policy, + feature_groups={"location": {"columns": ["other", "value"], "representation": representation}}, + ) + if overflow_policy == "error": + with pytest.raises(OutputBudgetError) as failure: + preprocessor.fit(frame) + message = str(failure.value) + elif overflow_policy == "warn": + with pytest.warns(ConfigWarning) as caught: + preprocessor.fit(frame) + assert len(caught) == 1 + message = str(caught[0].message) + else: + with warnings.catch_warnings(record=True) as caught: + preprocessor.fit(frame) + assert not caught + assert preprocessor.output_dims_["group_location"] == width + return + assert "group 'group_location'" in message + assert "('other', 'value')" in message + assert f"expands to {width} columns" in message + assert f"max_features_per_input ({width - 1})" in message + assert preprocessor.output_dims_["group_location"] == width def test_group_metadata_preserves_original_integer_labels_and_renamed_display_names(): @@ -281,6 +363,14 @@ def test_group_metadata_preserves_original_integer_labels_and_renamed_display_na assert len(renamed) == len(original) == preprocessor.total_output_dim_ np.testing.assert_array_equal(preprocessor.get_feature_names_out(), original) assert all(record.source_features == ("11", "7") for record in preprocessor.get_feature_lineage()[1:]) + report = preprocessor.reproducibility_report() + assert report["feature_groups"]["group_location"]["source_features"] == ["11", "7"] + bounded = clone(preprocessor) + assert isinstance(bounded, Preprocessor) + bounded.set_params(max_features_per_input=8) + with pytest.raises(OutputBudgetError) as failure: + bounded.fit(frame) + assert "sources (11, 7)" in str(failure.value) @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) diff --git a/tests/integration/test_fingerprint.py b/tests/integration/test_fingerprint.py index b0598dd..4c7b451 100644 --- a/tests/integration/test_fingerprint.py +++ b/tests/integration/test_fingerprint.py @@ -16,7 +16,8 @@ import pytest from sklearn.base import clone -from pretab import Preprocessor +from pretab import FeatureGroup, Preprocessor +from pretab.compose.inspection import representation_leaf from pretab.compose.registry import ( CATEGORICAL_ALIASES, CATEGORICAL_METHODS, @@ -55,6 +56,82 @@ def test_fingerprint_deterministic_same_fit(frame, target): assert _fit(frame, target).fingerprint_ == _fit(frame, target).fingerprint_ +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("change", ["group_order", "source_order", "family", "width", "params", "seed", "state"]) +def test_group_fingerprint_tracks_order_settings_and_fitted_state(frame, typed, change): + frame = frame.assign(d=frame["a"] ** 2, e=np.sin(frame["b"])) + + def make_groups(): + return { + "location": { + "columns": ["b", "a"], + "representation": { + "method": "tprs", + "n_components": 4, + "landmark_strategy": "subsample", + "random_state": 17, + }, + }, + "shape": { + "columns": ["d", "e"], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + }, + } + + def fit(groups): + declarations = ( + [FeatureGroup(name, entry["columns"], entry["representation"]) for name, entry in groups.items()] + if typed + else groups + ) + return Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + feature_groups=declarations, + ).fit(frame) + + reference = fit(make_groups()) + original = reference.fingerprint_ + repeated = fit(make_groups()) + assert repeated.fingerprint_ == original + report = reference.reproducibility_report() + assert list(report["representations"]) == ["group_location", "group_shape", "c"] + assert list(report["feature_groups"]) == ["group_location", "group_shape"] + assert [entry["dimension"] for entry in report["feature_groups"].values()] == [4, 9] + reference.transform(frame) + reference.mark_stale("metadata only").freeze() + assert reference.fingerprint_ == original + + groups = make_groups() + if change == "group_order": + groups = dict(reversed(list(groups.items()))) + elif change == "source_order": + groups["location"]["columns"] = ["a", "b"] + elif change == "family": + groups["location"]["representation"] = { + "method": "tensorspline", + "output_dim": 2, + "degree": 1, + "diff_order": 1, + } + elif change == "width": + groups["location"]["representation"]["n_components"] = 5 + elif change == "params": + groups["shape"]["representation"]["degree"] = 1 + elif change == "seed": + groups["location"]["representation"]["random_state"] = 18 + candidate = fit(groups) + if change == "state": + leaf = representation_leaf(candidate.column_transformer_.named_transformers_["group_location"]) + leaf.landmarks_[0, 0] += 0.125 + assert candidate.fingerprint_ != original + if change == "width": + assert candidate.output_dims_["group_location"] == 5 + else: + assert candidate.total_output_dim_ == reference.total_output_dim_ + + @pytest.mark.parametrize("per_feature", [False, True], ids=["global", "override"]) @pytest.mark.parametrize( ("feature", "method", "canonical"), @@ -200,3 +277,4 @@ def test_reproducibility_report_contents(frame, target): assert report["n_output_features"] == len(p.get_feature_names_out()) assert report["output_format"] == "dense" assert "a" in report["representations"] + assert "feature_groups" not in report From a0b66df7bee44fe2e0552a6abd4a0af92179d774 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 11:59:09 +0100 Subject: [PATCH 41/86] test(compose): verify grouped cross-fitting safeguards --- pretab/compose/inspection.py | 4 +- pretab/core/supervised.py | 3 +- pretab/preprocessor.py | 3 + tests/core/test_cross_fitted.py | 356 +++++++++++++++++++++++++++++++- 4 files changed, 360 insertions(+), 6 deletions(-) diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index b8cdab8..7a4ca43 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -402,7 +402,7 @@ def _resolve_block_representation(pipeline, columns): def block_uses_target(transformer) -> bool: - """Whether a fitted per-column block's representation consumed the target ``y``. + """Whether a fitted single-feature or joint block's representation consumed ``y``. For a separate-state / missing-indicator union the representation branch decides; helper steps such as imputers and scalers never use the target. The spec is read without @@ -414,7 +414,7 @@ def block_uses_target(transformer) -> bool: def refit_block_representation(transformer, X, y) -> TransformerLike: - """Return a copy of a fitted per-column block whose representation is refit on ``(X, y)``. + """Copy a fitted block and refit its representation on its ordered inputs and ``y``. Only the representation step and the steps after it are refit. The steps before it (the imputer with its missing indicator, scalers) never use the diff --git a/pretab/core/supervised.py b/pretab/core/supervised.py index 2adb49b..6c54fae 100644 --- a/pretab/core/supervised.py +++ b/pretab/core/supervised.py @@ -165,7 +165,8 @@ class CrossFittedTransformer(RepresentationSpecMixin, TransformerMixin, BaseEsti A supervised (target-aware) PreTab transformer to cross-fit, or an estimator such as a :class:`~pretab.Preprocessor` or ``Pipeline`` built from them. For a :class:`~pretab.Preprocessor`, only its target-aware - representations and subsequent steps are refit per fold. Column types, + representations and subsequent steps are refit per fold, including joint + representations selected by feature groups. Column types, target-free blocks and their vocabularies, imputers, scalers before the representation and missing-indicator branches come from the all-data fit. Target-free feature values match :meth:`transform`; target-aware values diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index ca98378..5d85179 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -1201,6 +1201,9 @@ def _cross_fit_fold(self, X, y): the fold. Column types, target-free blocks and their vocabularies, and preprocessing before the representation (imputers and scalers) are shared with this all-data fit. Missing-indicator branches are shared too. + A feature group is one block: its ordered source columns use the same + fitted prefix, and only its target-consuming joint representation is + refit for the fold. An out-of-fold row is encoded exactly like ``transform`` encodes it, except that no target-aware placement has seen that row's target. Refitting the whole preprocessor per fold would diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index c483c24..e7b6b81 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -6,12 +6,13 @@ """ import warnings +from dataclasses import replace from typing import cast import numpy as np import pytest from sklearn.base import BaseEstimator, TransformerMixin -from sklearn.model_selection import KFold +from sklearn.model_selection import KFold, StratifiedKFold from pretab import CrossFittedTransformer, LeakageWarning from pretab.core._typing import TransformerLike @@ -554,14 +555,16 @@ def test_wrapped_preprocessor_out_of_fold_codes_match_transform(array_with_rare_ np.testing.assert_array_equal(np.unique(out[:, unsupervised[1]]), [1.0, 2.0, 3.0, 4.0]) -def _refit_representation_per_fold(pipeline, column, y): +def _refit_representation_per_fold(pipeline, column, y, splitter=None): """Expected out-of-fold rows of a fitted block pipeline whose last step is its target-aware representation: the helper steps before it keep their all-data fit.""" from sklearn.base import clone helpers, representation = pipeline[:-1], pipeline[-1] blocks = {} - for train_idx, test_idx in KFold(n_splits=5, shuffle=True, random_state=0).split(column): + if splitter is None: + splitter = KFold(n_splits=5, shuffle=True, random_state=0) + for train_idx, test_idx in splitter.split(column, y): fold = cast(TransformerLike, clone(representation)) fold.fit(helpers.transform(column.iloc[train_idx]), y[train_idx]) blocks[tuple(test_idx)] = fold.transform(helpers.transform(column.iloc[test_idx])) @@ -577,6 +580,353 @@ def _fitted_block(cross_fitted, name): return cast(Preprocessor, cross_fitted.estimator_).column_transformer_.named_transformers_[name] +class _JointTargetProjection(TransformerMixin, BaseEstimator): + def __init__(self, target_aware=True): + self.target_aware = target_aware + + def fit(self, X, y=None): + values = np.asarray(X, dtype=float) + target = np.asarray(y) + self.n_features_in_ = values.shape[1] + self.fit_values_ = values.copy() + self.fit_target_ = target.copy() + self.weights_ = values.T @ target / len(values) if self.target_aware else np.arange(1, values.shape[1] + 1) + self.target_mean_ = target.mean() if self.target_aware else 0.0 + return self + + def transform(self, X): + values = np.asarray(X, dtype=float) + return np.column_stack((values @ self.weights_, np.full(len(values), self.target_mean_))) + + def get_feature_names_out(self, input_features=None): + return np.array(["joint_projection", "target_mean"], dtype=object) + + +@pytest.fixture +def grouped_cross_fit_data(): + import pandas as pd + + rng = np.random.default_rng(42) + frame = pd.DataFrame( + { + "north": rng.normal(size=100), + "east": rng.normal(size=100), + "spare": rng.normal(size=100), + "city": ["rare", *(["usual"] * 99)], + } + ) + frame.loc[7, "north"] = np.nan + return frame, rng.normal(size=len(frame)) + + +@pytest.mark.parametrize( + ("target_usage", "target_aware"), [("optional", False), ("optional", True), ("required", True)] +) +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("task", ["regression", "classification"]) +def test_grouped_target_aware_cross_fitting_preserves_frozen_prefix_and_missing_state( + grouped_cross_fit_data, monkeypatch, target_usage, target_aware, missing, output_format, dtype, task +): + import pandas as pd + from scipy import sparse as sp + + from pretab import Preprocessor + from pretab.compose.registry import TRANSFORMER_REGISTRY + + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace( + TRANSFORMER_REGISTRY["tprs"], + transformer_cls=_JointTargetProjection, + target_usage=target_usage, + allowed_args=(), + placement_strategies=frozenset(), + ), + ) + fold_models = [] + original_fold = Preprocessor._cross_fit_fold + + def record_fold(self, X, y): + fold = original_fold(self, X, y) + fold_models.append(fold) + return fold + + monkeypatch.setattr(Preprocessor, "_cross_fit_fold", record_fold) + frame, target = grouped_cross_fit_data + original_frame = frame.copy(deep=True) + if task == "classification": + target = (target > 0).astype(int) + wrapped = CrossFittedTransformer( + Preprocessor( + numerical_method="minmax", + categorical_method="one-hot", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + output_format=output_format, + dtype=dtype, + task=task, + feature_groups={ + "location": { + "columns": ["east", "north"], + "representation": {"method": "tprs", "target_aware": target_aware}, + } + }, + ), + n_folds=5, + random_state=0, + task=task, + ) + out = wrapped.fit_transform(frame, target) + full = wrapped.transform(frame) + assert sp.issparse(out) is (output_format == "sparse") + assert out.dtype == full.dtype == dtype + if output_format == "sparse": + assert out.format == full.format == "csr" + out = out.toarray() if sp.issparse(out) else out + full = full.toarray() if sp.issparse(full) else full + fitted = cast(Preprocessor, wrapped.estimator_) + span = fitted.column_transformer_.output_indices_["group_location"] + block = _fitted_block(wrapped, "group_location") + representation = block if missing == "none" else dict(block.transformer_list)["representation"] + splitter_cls = StratifiedKFold if task == "classification" else KFold + splitter = splitter_cls(n_splits=5, shuffle=True, random_state=0) + expected = _refit_representation_per_fold(representation, frame[["east", "north"]], target, splitter).astype(dtype) + np.testing.assert_array_equal(out[:, span.start : span.start + 2], expected) + np.testing.assert_array_equal(out[:, : span.start], full[:, : span.start]) + np.testing.assert_array_equal(out[:, span.stop :], full[:, span.stop :]) + sources = {"none": [], "observed": ["north"], "all": ["east", "north"]}[missing] + assert span.stop - span.start == 2 + len(sources) + np.testing.assert_array_equal(out[:, span.start + 2 : span.stop], frame[sources].isna().astype(float)) + assert out.shape == full.shape == (len(frame), len(wrapped.get_feature_names_out())) + if target_aware: + assert not np.allclose(out[:, span.start : span.start + 2], full[:, span.start : span.start + 2]) + else: + np.testing.assert_array_equal(out, full) + assert len(fold_models) == 5 + for fold, (train_idx, _) in zip(fold_models, splitter.split(frame, target), strict=True): + fold_block = fold.column_transformer_.named_transformers_["group_location"] + fold_representation = fold_block if missing == "none" else dict(fold_block.transformer_list)["representation"] + assert (fold_block is block) is not target_aware + if target_aware: + assert fold_representation[-1] is not representation[-1] + for (_, helper), (_, fold_helper) in zip( + representation.steps[:-1], fold_representation.steps[:-1], strict=True + ): + assert fold_helper is helper + np.testing.assert_array_equal( + fold_representation[-1].fit_values_, + representation[:-1].transform(frame.iloc[train_idx][["east", "north"]]), + ) + np.testing.assert_array_equal(fold_representation[-1].fit_target_, target[train_idx]) + if missing != "none": + assert dict(fold_block.transformer_list)["missing"] is dict(block.transformer_list)["missing"] + for name in ("num_spare", "cat_city"): + assert ( + fold.column_transformer_.named_transformers_[name] + is fitted.column_transformer_.named_transformers_[name] + ) + assert fold.output_dims_ == fitted.output_dims_ + np.testing.assert_array_equal(fold.get_feature_names_out(), fitted.get_feature_names_out()) + records = fitted.get_feature_lineage()[span] + assert all(record.uses_target is target_aware for record in records[:2]) + assert all(not record.uses_target for record in records[2:]) + pd.testing.assert_frame_equal(frame, original_frame) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +def test_builtin_groups_keep_all_data_state_while_supervised_single_is_refit(grouped_cross_fit_data, method, missing): + from pretab import Preprocessor + + frame, target = grouped_cross_fit_data + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + wrapped = CrossFittedTransformer( + Preprocessor( + numerical_method="ple", + output_dim=4, + categorical_method="one-hot", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + feature_groups={"location": {"columns": ["east", "north"], "representation": representation}}, + ), + n_folds=5, + random_state=0, + ) + out = wrapped.fit_transform(frame, target) + fitted = cast(Preprocessor, wrapped.estimator_) + full = wrapped.transform(frame) + span = fitted.column_transformer_.output_indices_["group_location"] + np.testing.assert_array_equal(out[:, span], full[:, span]) + assert not np.allclose(out[:, :4], full[:, :4]) + fingerprint = fitted.fingerprint_ + for train_idx, _ in KFold(n_splits=5, shuffle=True, random_state=0).split(frame): + fold = fitted._cross_fit_fold(frame.iloc[train_idx], target[train_idx]) + assert fold.column_transformer_.named_transformers_["group_location"] is _fitted_block( + wrapped, "group_location" + ) + assert fold.column_transformer_.named_transformers_["num_spare"] is not _fitted_block(wrapped, "num_spare") + assert fitted.fingerprint_ == fingerprint + + +def test_grouped_cross_fitting_retains_dictionary_error_and_matrix_remedy(grouped_cross_fit_data): + from pretab import Preprocessor + + frame, target = grouped_cross_fit_data + wrapped = CrossFittedTransformer( + Preprocessor( + numerical_method="minmax", + output_structure="blocks", + output_format="dense", + feature_groups={ + "location": { + "columns": ["east", "north"], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + } + }, + ), + n_folds=5, + random_state=0, + ) + with pytest.raises(IncompatibleParamsError, match=r"dict of blocks.*output_structure='matrix'"): + wrapped.fit_transform(frame, target) + assert isinstance(wrapped.transform(frame), dict) + + +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +def test_grouped_refit_preserves_prefix_and_refits_representation_suffix(grouped_cross_fit_data, monkeypatch, missing): + from copy import copy + + from sklearn.base import clone + from sklearn.pipeline import Pipeline + from sklearn.preprocessing import StandardScaler + + from pretab import Preprocessor + from pretab.compose.inspection import _separate_state_branches, refit_block_representation + from pretab.compose.registry import TRANSFORMER_REGISTRY + + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace( + TRANSFORMER_REGISTRY["tprs"], + transformer_cls=_JointTargetProjection, + target_usage="optional", + allowed_args=(), + placement_strategies=frozenset(), + ), + ) + frame, target = grouped_cross_fit_data + sources = ["east", "north"] + fitted = Preprocessor( + numerical_method="minmax", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + feature_groups={"location": {"columns": sources, "representation": "tprs"}}, + ).fit(frame, target) + original_block = fitted.column_transformer_.named_transformers_["group_location"] + representation = original_block if missing == "none" else dict(original_block.transformer_list)["representation"] + pipeline = copy(representation) + pipeline.steps = [ + *representation.steps, + ("suffix", StandardScaler().fit(representation.transform(frame[sources]))), + ] + block = pipeline + if missing != "none": + block = copy(original_block) + block.transformer_list = [ + (name, pipeline if name == "representation" else branch) for name, branch in original_block.transformer_list + ] + original_values = block.transform(frame[sources]).copy() + train, held_out = frame.iloc[20:][sources], frame.iloc[:20][sources] + refitted = refit_block_representation(block, train, target[20:]) + branches = _separate_state_branches(refitted) + if missing == "none": + assert branches is None + refitted_pipeline = refitted + else: + assert branches is not None + refitted_pipeline, indicator = branches + assert indicator is dict(block.transformer_list)["missing"] + assert isinstance(refitted_pipeline, Pipeline) + expected = clone(pipeline[-2:]) + assert isinstance(expected, Pipeline) + expected.fit(pipeline[:-2].transform(train), target[20:]) + np.testing.assert_allclose( + refitted_pipeline.transform(held_out), expected.transform(pipeline[:-2].transform(held_out)) + ) + for (_, helper), (_, fold_helper) in zip(pipeline.steps[:-2], refitted_pipeline.steps[:-2], strict=True): + assert fold_helper is helper + assert refitted_pipeline[-2] is not pipeline[-2] + assert refitted_pipeline[-1] is not pipeline[-1] + np.testing.assert_array_equal(block.transform(frame[sources]), original_values) + np.testing.assert_array_equal(representation[-1].fit_target_, target) + + +class _ChangingJointWidth(_JointTargetProjection): + def fit(self, X, y=None): + super().fit(X, y) + self.width_ = 2 if len(X) == 100 else (3 if np.asarray(X).mean() > 0 else 1) + return self + + def transform(self, X): + values = np.asarray(X, dtype=float) + return np.repeat((values @ self.weights_ + self.target_mean_)[:, None], self.width_, axis=1) + + def get_feature_names_out(self, input_features=None): + return np.array([f"joint_{index}" for index in range(self.width_)], dtype=object) + + +@pytest.mark.parametrize("first_group", ["positive", "negative"]) +def test_grouped_cross_fitting_rejects_opposite_width_changes_with_constant_total(monkeypatch, first_group): + import pandas as pd + + from pretab import Preprocessor + from pretab.compose.inspection import refit_block_representation + from pretab.compose.registry import TRANSFORMER_REGISTRY + + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace( + TRANSFORMER_REGISTRY["tprs"], + transformer_cls=_ChangingJointWidth, + target_usage="required", + allowed_args=(), + placement_strategies=frozenset(), + ), + ) + values = np.linspace(1.0, 10.0, 100) + frame = pd.DataFrame( + {"positive": values, "positive_other": values + 1, "negative": -values, "negative_other": -values - 1} + ) + target = np.random.default_rng(42).normal(size=len(frame)) + other_group = "negative" if first_group == "positive" else "positive" + groups = { + name: {"columns": [name, f"{name}_other"], "representation": "tprs"} for name in (first_group, other_group) + } + preprocessor = Preprocessor(scaling="none", feature_groups=groups).fit(frame, target) + assert preprocessor.output_dims_ == {f"group_{first_group}": 2, f"group_{other_group}": 2} + fold_widths = [] + for name in groups: + columns = [name, f"{name}_other"] + block = preprocessor.column_transformer_.named_transformers_[f"group_{name}"] + refitted = refit_block_representation(block, frame.iloc[20:][columns], target[20:]) + fold_widths.append(len(refitted.get_feature_names_out(columns))) + assert sorted(fold_widths) == [1, 3] + assert sum(fold_widths) == preprocessor.total_output_dim_ == 4 + with pytest.raises(IncompatibleParamsError, match="fixed output width") as failure: + CrossFittedTransformer(preprocessor, n_folds=5, shuffle=False).fit_transform(frame, target) + assert f"block 'group_{first_group}'" in str(failure.value) + assert f"expected 2, got {fold_widths[0]}" in str(failure.value) + + def test_wrapped_preprocessor_target_aware_blocks_stay_out_of_fold(array_with_rare_category): """Only the target-aware representation is refit, on each fold's training rows; the helper steps before it (imputer, scaler) keep their all-data fit.""" From de8ba9e98cc04189b7c808a357875e230f113b0a Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 16:10:33 +0100 Subject: [PATCH 42/86] fix(compose): report missing fitted group sources --- pretab/preprocessor.py | 17 ++- tests/integration/test_column_labels.py | 156 ++++++++++++++++++++++++ tests/integration/test_output_format.py | 111 ++++++++++++++++- tests/integration/test_polars_input.py | 62 +++++++++- 4 files changed, 342 insertions(+), 4 deletions(-) diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 5d85179..e8dec0d 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -812,7 +812,7 @@ def transform(self, X, embeddings=None, return_array=None): ------ PretabDataError If input matched by position has a different number of columns than - ``n_features_in_``: it could never be routed correctly. + ``n_features_in_``, or named input is missing a fitted group source. """ check_is_fitted(self) @@ -1087,7 +1087,8 @@ def _align_input(self, X): ------ PretabDataError If array-like input matched by position has a different number of - columns than seen during ``fit``: it could never be routed correctly. + columns than seen during ``fit``, or named input omits a fitted group + source. Group errors identify the group and original missing labels. """ # Synthetic labels mark an array fit only when no input feature names were recorded. fitted_labels = getattr(self.column_transformer_, "feature_names_in_", None) @@ -1100,6 +1101,18 @@ def _align_input(self, X): is_array = not has_column_labels(X) X = to_dataframe(X, copy=True) if not (is_array or (fitted_on_array and list(X.columns) != positional_labels)): + available = {str(column) for column in X.columns} + for block in _iter_fitted_blocks(self.column_transformer_): + if block.group_id is None: + continue + missing = tuple(column for column in block.columns if str(column) not in available) + if missing: + labels = self._input_labels() + sources = tuple(labels.get(column, column) for column in missing) + raise PretabDataError( + f"Feature group {block.group_id!r} is missing sources {sources!r} " + "required by the fitted representation." + ) return X if X.shape[1] != self.n_features_in_: raise PretabDataError( diff --git a/tests/integration/test_column_labels.py b/tests/integration/test_column_labels.py index 504d6e9..eec306d 100644 --- a/tests/integration/test_column_labels.py +++ b/tests/integration/test_column_labels.py @@ -123,6 +123,162 @@ def test_mixed_structured_inputs_keep_feature_order(input_kind, typed, reverse_s np.testing.assert_array_equal(result.toarray() if sparse.issparse(result) else np.asarray(result), expected) +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("labels", ["string", "integer"]) +@pytest.mark.parametrize("missing_indices", [(0,), (1,), (0, 1)]) +@pytest.mark.parametrize("input_kind", ["pandas", "dict"]) +def test_missing_group_sources_name_fitted_group_and_original_labels( + int_labelled, method, labels, missing_indices, input_kind +): + frame = int_labelled if labels == "integer" else int_labelled.set_axis(["north", "east"], axis=1) + sources = list(frame.columns[::-1]) + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + feature_groups={"location": {"columns": sources, "representation": representation}}, + ).fit(frame) + preprocessor.set_params(feature_groups=None) + missing = tuple(sources[index] for index in missing_indices) + incoming = frame.drop(columns=list(missing)) + original = incoming.copy(deep=True) + values = incoming.to_dict(orient="list") if input_kind == "dict" else incoming + with pytest.raises(PretabDataError) as failure: + preprocessor.transform(values) + assert "group 'group_location'" in str(failure.value) + assert f"missing sources {missing!r}" in str(failure.value) + pd.testing.assert_frame_equal(incoming, original) + + +def _grouped_input_processor(method, columns, **kwargs): + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + return Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + missing_policy="separate_state", + feature_groups={"location": {"columns": columns, "representation": representation}}, + **kwargs, + ) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("input_kind", ["pandas", "numpy", "polars"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse", "auto"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_grouped_inputs_preserve_order_missing_state_and_values(method, input_kind, output_format, dtype): + from scipy import sparse + + frame = pd.DataFrame( + np.random.default_rng(42).normal(size=(40, 3)), columns=pd.Index(["feature_0", "feature_1", "feature_2"]) + ) + frame.iloc[7, 0] = np.nan + sources = ["feature_1", "feature_0"] + expected_preprocessor = _grouped_input_processor(method, sources, dtype=dtype).fit(frame) + expected = expected_preprocessor.transform(frame) + if input_kind == "polars": + polars = pytest.importorskip("polars") + incoming = polars.DataFrame(frame.to_dict(orient="list")).fill_nan(None) + else: + incoming = frame.to_numpy() if input_kind == "numpy" else frame + original = deepcopy(incoming) + preprocessor = _grouped_input_processor(method, sources, output_format=output_format, dtype=dtype) + transformed = preprocessor.fit_transform(incoming) + assert not isinstance(transformed, dict) + assert sparse.issparse(transformed) == (preprocessor.output_format_ == "sparse") + assert transformed.dtype == dtype + values = transformed.toarray() if sparse.issparse(transformed) else np.asarray(transformed) + np.testing.assert_array_equal(values, expected) + np.testing.assert_array_equal(preprocessor.get_feature_names_out(), expected_preprocessor.get_feature_names_out()) + assert preprocessor.get_feature_info(verbose=False) == expected_preprocessor.get_feature_info(verbose=False) + assert preprocessor.get_feature_lineage() == expected_preprocessor.get_feature_lineage() + assert list(preprocessor.output_dims_) == ["feature_2", "group_location"] + fingerprint = preprocessor.fingerprint_ + blocks = preprocessor.transform(incoming, return_array=False) + assert isinstance(blocks, dict) + assert list(blocks) == ["num_feature_2", "group_location"] + assert all(sparse.issparse(block) == (preprocessor.output_format_ == "sparse") for block in blocks.values()) + stacked = np.hstack([block.toarray() if sparse.issparse(block) else np.asarray(block) for block in blocks.values()]) + np.testing.assert_array_equal(stacked, expected) + np.testing.assert_array_equal(values[:, -2:], frame[sources].isna().astype(dtype)) + if input_kind == "numpy": + assert isinstance(incoming, np.ndarray) + for wrong in (incoming[:, :-1], np.column_stack((incoming, np.ones(len(incoming))))): + with pytest.raises(PretabDataError, match=r"X has [24] features, but Preprocessor is expecting 3"): + preprocessor.transform(wrong) + np.testing.assert_array_equal(incoming, original) + else: + assert not isinstance(incoming, np.ndarray) + reordered = ( + incoming.iloc[:, ::-1] if isinstance(incoming, pd.DataFrame) else incoming.select(incoming.columns[::-1]) + ) + result = preprocessor.transform(reordered) + assert not isinstance(result, dict) + np.testing.assert_array_equal(result.toarray() if sparse.issparse(result) else np.asarray(result), expected) + if isinstance(incoming, pd.DataFrame): + assert isinstance(original, pd.DataFrame) + pd.testing.assert_frame_equal(incoming, original) + else: + assert incoming.equals(original) + assert preprocessor.fingerprint_ == fingerprint + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("input_kind", ["pandas", "dict", "numpy", "list"]) +def test_grouped_integer_labels_keep_named_and_positional_routes(int_labelled, method, input_kind): + preprocessor = _grouped_input_processor(method, [0, 1]).fit(int_labelled) + expected = preprocessor.transform(int_labelled) + reordered = int_labelled.iloc[:, ::-1] + incoming = { + "pandas": reordered, + "dict": reordered.to_dict(orient="list"), + "numpy": int_labelled.to_numpy(), + "list": int_labelled.to_numpy().tolist(), + }[input_kind] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + actual = preprocessor.transform(incoming) + assert not caught + np.testing.assert_array_equal(actual, expected) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_array_fitted_groups_accept_differently_named_frames_positionally(method): + frame = pd.DataFrame(np.random.default_rng(42).normal(size=(40, 3)), columns=pd.Index(["north", "east", "spare"])) + preprocessor = _grouped_input_processor(method, ["feature_1", "feature_0"]).fit(frame.to_numpy()) + expected = preprocessor.transform(frame.to_numpy()) + with pytest.warns(UserWarning, match="was fitted without feature names"): + actual = preprocessor.transform(frame) + np.testing.assert_array_equal(actual, expected) + with pytest.raises(PretabDataError, match="X has 2 features, but Preprocessor is expecting 3"): + preprocessor.transform(frame.iloc[:, :-1]) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("input_kind", ["numpy", "list"]) +def test_named_fitted_groups_accept_positional_inputs_with_existing_warning(method, input_kind): + frame = pd.DataFrame(np.random.default_rng(42).normal(size=(40, 3)), columns=pd.Index(["north", "east", "spare"])) + preprocessor = _grouped_input_processor(method, ["east", "north"]).fit(frame) + expected = preprocessor.transform(frame) + incoming = frame.to_numpy() if input_kind == "numpy" else frame.to_numpy().tolist() + with pytest.warns(UserWarning, match="does not have valid feature names") as caught: + actual = preprocessor.transform(incoming) + assert len(caught) == 1 + np.testing.assert_array_equal(actual, expected) + wrong = frame.iloc[:, :-1].to_numpy() + with pytest.raises(PretabDataError, match="X has 2 features, but Preprocessor is expecting 3"): + preprocessor.transform(wrong if input_kind == "numpy" else wrong.tolist()) + + @pytest.fixture(params=["string", "integer"]) def input_route_frame(request): frame = pd.DataFrame( diff --git a/tests/integration/test_output_format.py b/tests/integration/test_output_format.py index 9503e21..bda7af6 100644 --- a/tests/integration/test_output_format.py +++ b/tests/integration/test_output_format.py @@ -5,7 +5,7 @@ wrapping. """ -from typing import cast +from typing import Any, cast import numpy as np import pandas as pd @@ -50,6 +50,115 @@ def _bspline(**kwargs): # --- default (dense) behaviour ------------------------------------------------- +def _grouped_format_processor(method, **kwargs): + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + return Preprocessor( + numerical_method="none", + categorical_method="one-hot", + target_aware=False, + placement_strategy="uniform", + feature_groups={"location": {"columns": ["b", "a"], "representation": representation}}, + **kwargs, + ) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse", "auto"]) +@pytest.mark.parametrize("many_categories", [False, True]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_grouped_output_negotiates_format_once_without_changing_values( + frame, method, output_format, many_categories, dtype +): + frame = frame.assign(city=[f"city_{index}" for index in range(len(frame))] if many_categories else "same") + expected_preprocessor = _grouped_format_processor(method, dtype=dtype).fit(frame) + expected = expected_preprocessor.transform(frame) + preprocessor = _grouped_format_processor(method, output_format=output_format, dtype=dtype).fit(frame) + resolved = ("sparse" if many_categories else "dense") if output_format == "auto" else output_format + assert preprocessor.output_format_ == resolved + fingerprint = preprocessor.fingerprint_ + native_group = preprocessor.column_transformer_.named_transformers_["group_location"].transform(frame[["b", "a"]]) + assert isinstance(native_group, np.ndarray) + for batch in (frame, frame.iloc[:1]): + matrix = preprocessor.transform(batch) + assert not isinstance(matrix, dict) + assert sp.issparse(matrix) == (resolved == "sparse") + assert matrix.dtype == dtype + if sp.issparse(matrix): + assert matrix.format == "csr" + values = matrix.toarray() if sp.issparse(matrix) else np.asarray(matrix) + np.testing.assert_array_equal(values, expected[: len(batch)]) + report = preprocessor.output_report_ + assert report["format"] == resolved + assert report["shape"] == values.shape + assert report["dense_bytes"] == values.nbytes + blocks = preprocessor.transform(batch, return_array=False) + assert isinstance(blocks, dict) + assert list(blocks) == ["group_location", "cat_city"] + assert all(sp.issparse(block) == (resolved == "sparse") for block in blocks.values()) + stacked = np.hstack([block.toarray() if sp.issparse(block) else np.asarray(block) for block in blocks.values()]) + np.testing.assert_array_equal(stacked, values) + assert preprocessor.fingerprint_ == fingerprint + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse", "auto"]) +@pytest.mark.parametrize("container", ["pandas", "polars"]) +@pytest.mark.parametrize("configuration", ["local", "global"]) +def test_grouped_dataframe_output_keeps_names_dtype_and_index(frame, method, output_format, container, configuration): + from sklearn import config_context + + polars = pytest.importorskip("polars") if container == "polars" else None + frame = frame.assign(city=[f"city_{index}" for index in range(len(frame))]) + frame.index = pd.Index(np.arange(len(frame)) % 7, name="row") + expected_preprocessor = _grouped_format_processor(method, dtype=np.float32).fit(frame) + expected = expected_preprocessor.transform(frame) + assert isinstance(expected, np.ndarray) + preprocessor = _grouped_format_processor(method, output_format=output_format, dtype=np.float32) + if configuration == "local": + actual = preprocessor.set_output(transform=container).fit_transform(frame) + else: + with config_context(transform_output=container): + actual = preprocessor.fit_transform(frame) + if container == "pandas": + assert isinstance(actual, pd.DataFrame) + pd.testing.assert_index_equal(actual.index, frame.index) + assert all(column_dtype == np.float32 for column_dtype in actual.dtypes) + else: + assert polars is not None + assert isinstance(actual, polars.DataFrame) + actual = cast(Any, actual) + assert actual.dtypes == [polars.Float32] * expected.shape[1] + assert list(actual.columns) == list(preprocessor.get_feature_names_out()) + np.testing.assert_array_equal(actual.to_numpy(), expected) + assert preprocessor.output_format_ == ("dense" if output_format == "dense" else "sparse") + assert preprocessor.output_report_["format"] == preprocessor.output_format_ + assert preprocessor.output_dims_ == expected_preprocessor.output_dims_ + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_grouped_sparse_intermediate_is_not_densified(frame, monkeypatch, method): + frame = frame.assign(city=[f"city_{index}" for index in range(len(frame))]) + preprocessor = _grouped_format_processor(method, output_format="sparse").fit(frame) + raw = preprocessor.column_transformer_.transform(frame) + assert sp.issparse(raw) + + class NoDensifyCSR(sp.csr_matrix): + def toarray(self, *args, **kwargs): + pytest.fail("Grouped sparse intermediate must not be densified") + + monkeypatch.setattr(preprocessor.column_transformer_, "transform", lambda X: NoDensifyCSR(raw)) + actual = preprocessor.transform(frame) + assert isinstance(actual, sp.csr_matrix) + blocks = preprocessor.transform(frame, return_array=False) + assert isinstance(blocks, dict) + assert all(sp.issparse(block) for block in blocks.values()) + assert actual.shape == (len(frame), preprocessor.total_output_dim_) + + def test_default_output_format_is_dense(frame, y): p = _bspline().fit(frame, y) arr = p.transform(frame, return_array=True) diff --git a/tests/integration/test_polars_input.py b/tests/integration/test_polars_input.py index b7e932c..f1bf01d 100644 --- a/tests/integration/test_polars_input.py +++ b/tests/integration/test_polars_input.py @@ -13,7 +13,7 @@ import pytest from pretab import Preprocessor, RepresentationConfig -from pretab.exceptions import DataWarning +from pretab.exceptions import DataWarning, PretabDataError pl = pytest.importorskip("polars") @@ -137,6 +137,66 @@ def test_mixed_structured_inputs_preserve_polars_column_types(frames, typed, out assert polars_frame.equals(original) +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse", "auto"]) +def test_grouped_polars_nullable_sources_match_pandas_with_categorical_neighbors(frames, method, output_format): + from scipy import sparse + + pandas_frame, polars_frame, _ = frames + pandas_frame = pandas_frame.astype({"visits": float}) + pandas_frame.loc[7, "visits"] = np.nan + visits = polars_frame["visits"].to_list() + visits[7] = None + polars_frame = polars_frame.with_columns(pl.Series("visits", visits, dtype=pl.Int64)) + original = polars_frame.clone() + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + options = { + "numerical_method": "none", + "categorical_method": "one-hot", + "target_aware": False, + "placement_strategy": "uniform", + "missing_policy": "separate_state", + "output_format": output_format, + "dtype": np.float32, + "feature_groups": {"location": {"columns": ["visits", "income"], "representation": representation}}, + } + from_pandas = Preprocessor(**options).fit(pandas_frame) + from_polars = Preprocessor(**options).fit(polars_frame) + reference = from_pandas.transform(pandas_frame) + assert not isinstance(reference, dict) + expected = reference.toarray() if sparse.issparse(reference) else np.asarray(reference) + assert from_polars.numerical_features_ == ["income", "visits"] + assert from_polars.categorical_features_ == ["rooms", "plan", "city", "flag"] + assert from_polars.output_dims_ == from_pandas.output_dims_ + assert from_polars.get_feature_lineage() == from_pandas.get_feature_lineage() + np.testing.assert_array_equal(from_polars.get_feature_names_out(), from_pandas.get_feature_names_out()) + for preprocessor, incoming in ( + (from_polars, polars_frame.select(polars_frame.columns[::-1])), + (from_polars, pandas_frame.iloc[:, ::-1]), + (from_pandas, polars_frame.select(polars_frame.columns[::-1])), + ): + actual = preprocessor.transform(incoming) + assert not isinstance(actual, dict) + assert sparse.issparse(actual) == (preprocessor.output_format_ == "sparse") + np.testing.assert_array_equal(actual.toarray() if sparse.issparse(actual) else np.asarray(actual), expected) + blocks = preprocessor.transform(incoming, return_array=False) + assert isinstance(blocks, dict) + assert list(blocks) == ["group_location", "cat_rooms", "cat_plan", "cat_city", "cat_flag"] + group = blocks["group_location"] + values = group.toarray() if sparse.issparse(group) else np.asarray(group) + np.testing.assert_array_equal(values[:, -2:], pandas_frame[["visits", "income"]].isna().astype(np.float32)) + assert polars_frame.equals(original) + assert polars_frame.null_count()["visits"][0] == 1 + with pytest.raises(PretabDataError) as failure: + from_polars.transform(polars_frame.drop("visits")) + assert "group 'group_location'" in str(failure.value) + assert "missing sources ('visits',)" in str(failure.value) + + def test_polars_input_with_polars_output(frames): _, polars_frame, y = frames pre = Preprocessor(numerical_method="minmax").set_output(transform="polars").fit(polars_frame, y) From e0f6726aba5f016c827ca9230f01a65adabe5742 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 21:54:43 +0100 Subject: [PATCH 43/86] fix(compose): restore grouped specs and name empty sources --- pretab/compose/serialize.py | 12 +- pretab/preprocessor.py | 42 ++- tests/integration/test_feature_groups.py | 339 +++++++++++++++++++++++ 3 files changed, 378 insertions(+), 15 deletions(-) create mode 100644 tests/integration/test_feature_groups.py diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 077ee5c..6498ff5 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -39,7 +39,7 @@ from ..exceptions import PretabSerializationError from ..placement.base import PlacementResult from ..preprocessing.floats import NoTransformer, ToFloatTransformer -from .config import RepresentationConfig +from .config import FeatureGroup, RepresentationConfig from .inspection import _iter_fitted_blocks, representation_leaf from .registry import TransformerSpec @@ -60,7 +60,15 @@ # let a spec construct an arbitrary sklearn/numpy/scipy dataclass with # attacker-controlled fields. _ALLOWED_DATACLASSES = frozenset( - {RepresentationPolicy, RepresentationSpec, FeatureLineage, PlacementResult, TransformerSpec, RepresentationConfig} + { + RepresentationPolicy, + RepresentationSpec, + FeatureLineage, + PlacementResult, + TransformerSpec, + RepresentationConfig, + FeatureGroup, + } ) diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index e8dec0d..a9caca3 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -1261,40 +1261,56 @@ def _reject_missing(self, X) -> None: ) def _raise_for_empty_features(self, X, y, empty_features, config) -> None: - """Name the empty feature behind a failed ``fit``, if one is to blame. + """Name the empty sources behind a failed ``fit``, if they are to blame. - Called when fitting the ColumnTransformer failed. The block of each feature - without an observed value is refitted on its own, and the first that fails - raises a :class:`~pretab.exceptions.PretabDataError` naming that feature, + Called when fitting the ColumnTransformer failed. Each block containing + a source without an observed value is refitted on its own, and the first + that fails raises a :class:`~pretab.exceptions.PretabDataError` naming its + empty sources and, for a group, the declared group and representation, chained to the block's own error: methods that cannot be fitted on a constant column (e.g. the B/M/I and cubic splines, Box-Cox) otherwise only report "the feature at index 0". A block is only blamed when it fits a - stand-in column of distinct observed values with the same ``y``, so a + stand-in frame with distinct observed values for all empty sources and the same ``y``, so a failure with another cause (e.g. a ``y`` of the wrong length) is not attributed to the empty column. Returns without raising when no empty column is to blame, so the caller re-raises the original error. """ empty = {str(feature): feature for feature in empty_features} + groups = {tuple(str(column) for column in group.columns): group for group in config.feature_groups} for _name, transformer, columns in self.column_transformer_.transformers: - if columns[0] not in empty: + empty_columns = tuple(column for column in columns if column in empty) + if not empty_columns: continue - feature = empty[columns[0]] - is_numerical = feature in self.numerical_features_ try: cast(TransformerLike, clone(transformer)).fit(X[columns], y) except PretabConfigError: continue # a configuration problem, not one of the empty column except ValueError as exc: stand_in = X[columns].copy() - stand_in[columns[0]] = ( - np.linspace(1.0, 2.0, len(X)) - if is_numerical - else np.resize(np.array(["a", "b"], dtype=object), len(X)) - ) + for column in empty_columns: + stand_in[column] = ( + np.linspace(1.0, 2.0, len(X)) + if empty[column] in self.numerical_features_ + else np.resize(np.array(["a", "b"], dtype=object), len(X)) + ) try: cast(TransformerLike, clone(transformer)).fit(stand_in, y) except ValueError: continue # the block fails with observed values too: not the emptiness + group = groups.get(tuple(columns)) + if group is not None: + labels = self._input_labels() + sources = tuple(labels.get(column, column) for column in columns) + missing = tuple(empty[column] for column in empty_columns) + raise PretabDataError( + f"Feature group {'group_' + group.name!r} with sources {sources!r} has no observed " + f"(non-missing) value at fit for sources {missing!r}, and its {group.representation.method!r} " + f"representation cannot be fitted on such data: {exc}\n" + "Fix: fit on data where these sources are observed, or change the group's columns or " + "representation via feature_groups." + ) from exc + feature = empty[empty_columns[0]] + is_numerical = feature in self.numerical_features_ method = config.method_for(feature, is_numerical=is_numerical) raise PretabDataError( f"Column {feature!r} has no observed (non-missing) value at fit, and its {method!r} " diff --git a/tests/integration/test_feature_groups.py b/tests/integration/test_feature_groups.py new file mode 100644 index 0000000..7ae096b --- /dev/null +++ b/tests/integration/test_feature_groups.py @@ -0,0 +1,339 @@ +"""End-to-end grouped configuration, fitted layout, and replay contracts.""" + +import json +import pickle +from copy import deepcopy + +import numpy as np +import pandas as pd +import pytest +from scipy import sparse +from sklearn.base import clone +from sklearn.pipeline import Pipeline + +from pretab import FeatureGroup, FrozenRepresentationError, OutputBudgetError, Preprocessor, RepresentationConfig +from pretab.exceptions import DataWarning, PretabDataError + + +@pytest.fixture +def frame(): + rng = np.random.default_rng(17) + return pd.DataFrame(rng.normal(size=(48, 5)), columns=pd.Index(["east", "north", "depth", "time", "single"])) + + +def _representation(method, width=3): + if method == "tensorspline": + return {"method": method, "output_dim": width, "degree": 2} + return {"method": method, "n_components": width, "landmark_strategy": "subsample", "random_state": 11} + + +def _processor(groups, **kwargs): + return Preprocessor( + feature_groups=groups, + numerical_method="none", + categorical_method="one-hot", + target_aware=False, + placement_strategy="uniform", + missing_policy="separate_state", + **kwargs, + ) + + +def _groups(typed, reverse=False): + entries = [ + ("location", ["north", "east"], _representation("tensorspline")), + ("trajectory", ["time", "depth"], _representation("tprs", width=4)), + ] + if reverse: + entries.reverse() + if typed: + return [ + FeatureGroup(name, columns, RepresentationConfig.from_dict(options)) for name, columns, options in entries + ] + return {name: {"columns": columns, "representation": options} for name, columns, options in entries} + + +def _dense(output): + assert not isinstance(output, dict) + return output.toarray() if sparse.issparse(output) else np.asarray(output) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("mixed", [False, True], ids=["grouped-only", "mixed"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["forward", "reversed"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_grouped_layout_matches_independent_blocks(frame, typed, mixed, reverse, output_format, dtype): + data = frame.copy() if mixed else frame.drop(columns="single") + if mixed: + data["city"] = np.resize(["Rome", "Lima", "Oslo"], len(data)) + data.loc[0, "east"] = np.nan + data.loc[1, "time"] = np.nan + before = data.copy(deep=True) + groups = _groups(typed, reverse) + declarations = deepcopy(groups) + processor = _processor(groups, output_format=output_format, dtype=dtype).fit(data) + fingerprint = processor.fingerprint_ + actual = processor.transform(data) + assert not isinstance(actual, dict) + assert sparse.issparse(actual) == (output_format == "sparse") + + references = [] + if mixed: + references.append(_processor(None, dtype=dtype).fit(data[["single"]])) + ordered = ["trajectory", "location"] if reverse else ["location", "trajectory"] + for name in ordered: + columns = ["north", "east"] if name == "location" else ["time", "depth"] + method, width = ("tensorspline", 3) if name == "location" else ("tprs", 4) + reference = _processor( + {name: {"columns": columns, "representation": _representation(method, width)}}, dtype=dtype + ) + references.append(reference.fit(data[columns])) + if mixed: + references.append(_processor(None, dtype=dtype).fit(data[["city"]])) + + expected = np.concatenate([_dense(reference.transform(data)) for reference in references], axis=1) + expected_names = np.concatenate([reference.get_feature_names_out() for reference in references]) + np.testing.assert_array_equal(_dense(actual), expected) + np.testing.assert_array_equal(processor.get_feature_names_out(), expected_names) + assert actual.dtype == dtype + expected_keys = (["num_single"] if mixed else []) + [f"group_{name}" for name in ordered] + expected_keys += ["cat_city"] if mixed else [] + blocks = processor.transform(data, return_array=False) + assert isinstance(blocks, dict) + assert list(blocks) == expected_keys + offset = 0 + for block in blocks.values(): + width = block.shape[1] + np.testing.assert_array_equal(_dense(block), expected[:, offset : offset + width]) + offset += width + assert offset == processor.total_output_dim_ == len(expected_names) + assert sum(processor.output_dims_.values()) == offset + lineage = processor.get_feature_lineage() + assert [record.output_index for record in lineage] == list(range(offset)) + assert [record.output_feature for record in lineage] == list(expected_names) + for name in ordered: + records = [record for record in lineage if record.group_id == f"group_{name}"] + assert records + sources = ("north", "east") if name == "location" else ("time", "depth") + assert all(record.source_features == sources for record in records if record.component != "indicator") + np.testing.assert_array_equal(_dense(processor.transform(data.iloc[:, ::-1])), expected) + assert processor.fingerprint_ == fingerprint + assert groups == declarations + pd.testing.assert_frame_equal(data, before) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_typed_group_spec_round_trip_preserves_fitted_contract(frame, method): + data = frame[["east", "north"]] + group = FeatureGroup("location", ["north", "east"], RepresentationConfig.from_dict(_representation(method))) + processor = _processor([group]).fit(data) + expected = processor.transform(data) + fingerprint = processor.fingerprint_ + + restored = Preprocessor.from_spec(json.loads(json.dumps(processor.to_spec(), allow_nan=False))) + + np.testing.assert_array_equal(restored.transform(data), expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), processor.get_feature_names_out()) + assert restored.get_params(deep=False) == processor.get_params(deep=False) + assert restored.get_feature_info(verbose=False) == processor.get_feature_info(verbose=False) + assert restored.output_dims_ == processor.output_dims_ + assert restored.fingerprint_ == fingerprint + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_structure", ["matrix", "blocks"]) +@pytest.mark.parametrize("restore_format", ["spec", "file", "pickle"]) +def test_grouped_mixed_replay_preserves_frozen_fitted_state( + frame, tmp_path, method, typed, output_structure, restore_format +): + data = frame.assign(city=np.resize(["Rome", "Lima", "Oslo"], len(frame))) + data.loc[0, "north"] = np.nan + options = _representation(method) + groups = ( + [FeatureGroup("location", ["north", "east"], RepresentationConfig.from_dict(options))] + if typed + else {"location": {"columns": ["north", "east"], "representation": options}} + ) + processor = _processor(groups, output_structure=output_structure, output_format="sparse", dtype=np.float32) + processor.fit(data).freeze() + expected = processor.transform(data) + fingerprint = processor.fingerprint_ + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(processor)) # noqa: S301 + elif restore_format == "file": + path = tmp_path / "groups.json" + processor.to_spec(path) + restored = Preprocessor.from_spec(path) + else: + restored = Preprocessor.from_spec(json.loads(json.dumps(processor.to_spec(), allow_nan=False))) + + actual = restored.transform(data.iloc[:, ::-1]) + if output_structure == "blocks": + assert isinstance(expected, dict) and isinstance(actual, dict) + assert list(actual) == list(expected) + for key in expected: + assert sparse.issparse(actual[key]) + np.testing.assert_array_equal(_dense(actual[key]), _dense(expected[key])) + assert actual[key].dtype == np.float32 + else: + assert sparse.issparse(actual) + np.testing.assert_array_equal(_dense(actual), _dense(expected)) + assert restored.get_params(deep=False) == processor.get_params(deep=False) + assert restored.get_resolved_config() == processor.get_resolved_config() + assert restored.get_feature_info(verbose=False) == processor.get_feature_info(verbose=False) + assert restored.get_feature_lineage() == processor.get_feature_lineage() + np.testing.assert_array_equal(restored.get_feature_names_out(), processor.get_feature_names_out()) + assert restored.output_dims_ == processor.output_dims_ + assert restored.output_format_ == "sparse" + assert restored.output_report_ == processor.output_report_ + assert restored.reproducibility_report() == processor.reproducibility_report() + assert restored.fingerprint_ == processor.fingerprint_ == fingerprint + assert restored.is_frozen() + with pytest.raises(FrozenRepresentationError, match="frozen"): + restored.set_params(feature_groups=None) + assert Preprocessor.from_spec(restored.to_spec()).fingerprint_ == fingerprint + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("via_pipeline", [False, True], ids=["direct", "pipeline"]) +def test_grouped_clone_and_set_params_refit_without_changing_original(frame, method, typed, via_pipeline): + options = _representation(method) + groups = ( + [FeatureGroup("location", ["north", "east"], RepresentationConfig.from_dict(options))] + if typed + else {"location": {"columns": ["north", "east"], "representation": options}} + ) + processor = _processor(groups).fit(frame) + expected = processor.transform(frame) + names = processor.get_feature_names_out() + dimensions = processor.output_dims_.copy() + lineage = processor.get_feature_lineage() + original_graph = processor.column_transformer_ + caller = Pipeline([("pre", processor)]) if via_pipeline else processor + copied = clone(caller) + assert isinstance(copied, (Pipeline, Preprocessor)) + fresh = copied.named_steps["pre"] if isinstance(copied, Pipeline) else copied + assert isinstance(fresh, Preprocessor) + assert fresh.lifecycle_state_ == "UNFITTED" + assert not hasattr(fresh, "column_transformer_") + assert fresh.get_params(deep=False) == processor.get_params(deep=False) + copied.fit(frame) + np.testing.assert_array_equal(copied.transform(frame), expected) + assert fresh.column_transformer_ is not original_graph + + replacement = [ + FeatureGroup("location", ["east", "north"], RepresentationConfig.from_dict(_representation(method, 4))) + ] + params = {"pre__feature_groups" if via_pipeline else "feature_groups": replacement} + assert caller.set_params(**params) is caller + assert processor.feature_groups is replacement + assert processor.column_transformer_ is original_graph + np.testing.assert_array_equal(processor.transform(frame), expected) + np.testing.assert_array_equal(processor.get_feature_names_out(), names) + assert processor.output_dims_ == dimensions + assert processor.get_feature_lineage() == lineage + old_fingerprint = fresh.fingerprint_ + caller.fit(frame) + reference = _processor(replacement).fit(frame) + np.testing.assert_array_equal(caller.transform(frame), reference.transform(frame)) + np.testing.assert_array_equal(processor.get_feature_names_out(), reference.get_feature_names_out()) + assert processor.output_dims_ == reference.output_dims_ + assert processor.output_dims_["group_location"] != dimensions["group_location"] + assert processor.column_transformer_ is not original_graph + assert processor.fingerprint_ != old_fingerprint + assert fresh.fingerprint_ == old_fingerprint + np.testing.assert_array_equal(copied.transform(frame), expected) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_structure", ["matrix", "blocks"]) +def test_grouped_budget_uses_full_actual_width_and_remains_reusable(frame, method, typed, output_structure): + options = _representation(method) + groups = ( + [FeatureGroup("location", ["north", "east"], RepresentationConfig.from_dict(options))] + if typed + else {"location": {"columns": ["north", "east"], "representation": options}} + ) + processor = _processor(groups, output_structure=output_structure).fit(frame) + width = processor.output_dims_["group_location"] + expected = processor.transform(frame, return_array=True) + processor.set_params(max_features_per_input=width - 1) + with pytest.raises(OutputBudgetError, match="group_location") as failure: + processor.fit(frame) + assert "('north', 'east')" in str(failure.value) + assert f"expands to {width} columns" in str(failure.value) + processor.set_params(max_features_per_input=width).fit(frame) + np.testing.assert_array_equal(processor.transform(frame, return_array=True), expected) + assert processor.output_dims_["group_location"] == width + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["forward", "reversed"]) +@pytest.mark.parametrize("replace_requested", [False, True], ids=["active-groups", "replaced-groups"]) +def test_grouped_spec_replays_fitted_order_after_requested_groups_change(frame, typed, reverse, replace_requested): + processor = _processor(_groups(typed, reverse), output_structure="blocks").fit(frame) + expected = processor.transform(frame) + assert isinstance(expected, dict) + names = processor.get_feature_names_out() + lineage = processor.get_feature_lineage() + if replace_requested: + processor.set_params(feature_groups=None) + processor.freeze() + fingerprint = processor.fingerprint_ + restored = Preprocessor.from_spec(json.loads(json.dumps(processor.to_spec(), allow_nan=False))) + actual = restored.transform(frame) + assert isinstance(actual, dict) + assert list(actual) == list(expected) + for key in expected: + np.testing.assert_array_equal(actual[key], expected[key]) + np.testing.assert_array_equal(restored.get_feature_names_out(), names) + assert restored.get_feature_lineage() == lineage + assert restored.output_dims_ == processor.output_dims_ + assert restored.feature_groups == processor.feature_groups + assert restored.get_resolved_config() == processor.get_resolved_config() + assert restored.fingerprint_ == fingerprint + + +@pytest.mark.parametrize("integer_labels", [False, True], ids=["strings", "integers"]) +@pytest.mark.parametrize("empty_positions", [(0,), (1,), (0, 1)], ids=["first", "second", "both"]) +def test_grouped_empty_source_failure_names_group_and_ordered_original_sources(frame, integer_labels, empty_positions): + data = frame[["east", "north"]].copy() + if integer_labels: + data.columns = pd.Index([7, 3]) + columns = tuple(data.columns[::-1]) + empty = tuple(columns[position] for position in empty_positions) + for column in empty: + data[column] = np.nan + before = data.copy(deep=True) + processor = _processor({"location": {"columns": columns, "representation": _representation("tensorspline")}}) + with pytest.warns(DataWarning), pytest.raises(PretabDataError, match="group_location") as failure: + processor.fit(data) + message = str(failure.value) + assert f"with sources {columns!r}" in message + assert f"for sources {empty!r}" in message + assert "'tensorspline'" in message + assert "feature_groups" in message + assert failure.value.__cause__ is not None + pd.testing.assert_frame_equal(data, before) + + +@pytest.mark.parametrize("integer_labels", [False, True], ids=["strings", "integers"]) +@pytest.mark.parametrize("empty_position", [0, 1], ids=["first", "second"]) +def test_grouped_empty_source_is_not_blamed_when_observed_stand_in_also_fails(frame, integer_labels, empty_position): + data = frame[["east", "north"]].copy() + if integer_labels: + data.columns = pd.Index([7, 3]) + columns = tuple(data.columns[::-1]) + data[columns[empty_position]] = np.nan + data[columns[1 - empty_position]] = 5.0 + before = data.copy(deep=True) + processor = _processor({"location": {"columns": columns, "representation": _representation("tensorspline")}}) + with pytest.warns(DataWarning), pytest.raises(ValueError, match="constant") as failure: + processor.fit(data) + assert "has no observed" not in str(failure.value) + assert "group_location" not in str(failure.value) + pd.testing.assert_frame_equal(data, before) From 1990408f1a55d8e5eeb1a8f266a2252c2190e923 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 23:09:44 +0100 Subject: [PATCH 44/86] docs(compose): document grouped preprocessing and widths --- docs/api/preprocessor.rst | 34 ++- docs/core_concepts/configuration.md | 31 ++- docs/getting_started/overview.md | 5 +- docs/representations/comparison_table.md | 5 +- docs/representations/overview.md | 12 +- docs/representations/spline_expansions.md | 14 +- docs/tutorials/multivariate_features.md | 206 ++++++++++++++++++- tests/doc_snippets/test_tutorial_snippets.py | 7 +- 8 files changed, 288 insertions(+), 26 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index c704148..33ad9e1 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -2,7 +2,7 @@ Preprocessor ============ The high-level entry point. :class:`~pretab.Preprocessor` reads a ``DataFrame``, -detects feature types, resolves a per-column representation from a single +detects feature types, resolves per-column and grouped representations from a single configuration, and produces model-ready output with full lineage. .. currentmodule:: pretab @@ -26,7 +26,6 @@ and mappings with a ``method`` key are accepted there as well. :toctree: _autosummary :nosignatures: - FeatureGroup RepresentationConfig Fields and conversion @@ -90,6 +89,37 @@ even when the values agree. The replacement is used by the next fit; it does not refit automatically. Frozen preprocessors reject configuration replacement. +Feature groups +-------------- + +:class:`~pretab.FeatureGroup` is an immutable request with three fields: +``name``, ordered ``columns``, and ``representation``. The representation accepts +a method string, mapping, or :class:`~pretab.RepresentationConfig`. Pass an ordered +sequence of these values to ``Preprocessor(feature_groups=...)``, or use a mapping +from group names to dictionaries containing ``columns`` and ``representation``. + +.. autosummary:: + :toctree: _autosummary + :nosignatures: + + FeatureGroup + +The supported group methods are ``tensorspline`` and ``tprs``, each with at least +two detected numerical inputs. Sources are exclusive: they cannot overlap another +group or an explicit per-feature override. Local representation settings take +precedence over applicable constructor-wide controls. The value itself neither +fits an estimator nor resolves method aliases. + +Fitted groups appear once as ``group_`` in block output and ``output_dims_``. +Output names and lineage retain group identity and source order. Joint basis width +and raw missing-state columns count together for output budgets. Ungrouped numerical +blocks precede groups in declaration order; categorical blocks follow them. + +See the :doc:`multivariate tutorial <../tutorials/multivariate_features>` for +executable declarations, block widths and trusted-spec replay. Frozen preprocessors +reject group replacement; otherwise ``set_params(feature_groups=...)`` changes +the request without refitting the existing representation. + Requested and resolved settings ------------------------------- diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index af99109..7c0e18a 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -1,15 +1,15 @@ # Configuration The `Preprocessor` is configured through a small, predictable set of parameters. This page -covers the four ways to express intent: global defaults, per-feature overrides, presets, and +covers global defaults, per-feature overrides, feature groups, presets, and reading back the resolved configuration. The mechanics of width and placement live in [Resolution and placement](resolution_and_placement.md), and target usage in [Target awareness](target_awareness.md). ## Global defaults -The simplest configuration sets one strategy for every numerical column and one for every -categorical column. +The simplest configuration sets one strategy for every ungrouped numerical column and one +for every categorical column. ```python from pretab import Preprocessor @@ -115,8 +115,8 @@ feature-type detection. ### Columns not listed in `feature_preprocessing` -`feature_preprocessing` only overrides the columns it names. Any numerical column left out -falls back to `numerical_method`, and any categorical column left out falls back to +`feature_preprocessing` only overrides the columns it names. Any ungrouped numerical column +left out falls back to `numerical_method`, and any categorical column left out falls back to `categorical_method`. This is real method resolution, not just a logging detail: the fallback column is fit with the global default's transformer, exactly as if you had listed it yourself. @@ -144,6 +144,27 @@ Don't infer the resolved method per column from the constructor arguments alone. [Fit-time logging](outputs_and_inspection.md#fit-time-logging). ``` +## Feature groups + +Use `feature_groups` when several numerical columns need one joint representation. +It accepts an ordered sequence of {class}`~pretab.FeatureGroup` values or an ordered +mapping from group names to `columns` and `representation`. The supported group +methods are `tensorspline` and `tprs`; they are not per-column `numerical_method` +choices. Group settings use the same {class}`~pretab.RepresentationConfig` values +and representation mappings as per-feature settings. + +A group exclusively owns at least two detected numerical columns. Groups cannot +overlap or claim columns with explicit `feature_preprocessing` entries. Boolean +and categorical columns are not eligible. Use `treat_all_integers_as_numerical=True` +when integer sources should bypass cardinality-based categorical detection. +Group declaration order controls block order; ordered source labels control +the group's input axes. Read joint widths from `output_dims_["group_"]` +after fit, including any raw missing-state columns. + +The [multivariate tutorial](../tutorials/multivariate_features.md#grouped-preprocessing-with-preprocessor) +covers typed and mapping declarations, tensor versus thin-plate sizing, output +budgets, block-based model inputs, and fitted-state replay. + ## Structured per-feature configuration The first three examples use the same training data and a scikit-learn regression pipeline. diff --git a/docs/getting_started/overview.md b/docs/getting_started/overview.md index ef35a8b..7473d05 100644 --- a/docs/getting_started/overview.md +++ b/docs/getting_started/overview.md @@ -104,8 +104,9 @@ surface that keeps the intent of your code clearest. ```{note} The tensor-product spline, thin-plate spline, random Fourier features, and Nyström map model -several columns jointly. They are standalone-only and are not selectable per column through -`Preprocessor(numerical_method=...)`. See +several columns jointly. Use `Preprocessor(feature_groups=...)` for tensor-product or +thin-plate splines, or fit their standalone transformers directly. Random Fourier features +and Nyström remain standalone-only. None is a per-column `numerical_method`. See [Multivariate features](../tutorials/multivariate_features.md). ``` diff --git a/docs/representations/comparison_table.md b/docs/representations/comparison_table.md index 8d81a3c..e8396b6 100644 --- a/docs/representations/comparison_table.md +++ b/docs/representations/comparison_table.md @@ -43,7 +43,10 @@ source of truth, and these tables mirror it. ```{note} The multivariate splines (`tensorspline`, `tprs`) model several inputs jointly and are used -standalone, not selected per column through `Preprocessor`. The alias `thinplate` resolves to +through `Preprocessor(feature_groups=...)` or their standalone transformers, not +per-column `numerical_method`. See the +[grouped preprocessing tutorial](../tutorials/multivariate_features.md). +The alias `thinplate` resolves to `tprs`. `ThinPlateSplineTransformer.get_penalty_matrix()` is experimental: it is not guaranteed positive semi-definite (the retained eigenvalues of the projected landmark kernel can be negative) and emits a `ConfigWarning` on every call. `transform()` is unaffected; only the diff --git a/docs/representations/overview.md b/docs/representations/overview.md index 13474b2..9f49282 100644 --- a/docs/representations/overview.md +++ b/docs/representations/overview.md @@ -57,12 +57,12 @@ Pretrained language embeddings for high-cardinality text categories. Every family is described with the same terms, introduced in [Preprocessing and representation](../core_concepts/feature_representation.md). -| Term | Meaning | -| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `scope` | `univariate` methods transform one column at a time. `multivariate` methods such as tensor-product spline, thin-plate spline, random Fourier features, and Nyström model several columns jointly and are used standalone, not per column through `Preprocessor`. | -| `supervision` | Whether the method uses the target: `forbidden`, `optional`, or `required`. See [Target awareness](../core_concepts/target_awareness.md). | -| `output_dim` | The width of the expansion. See [Resolution and placement](../core_concepts/resolution_and_placement.md). | -| `placement` | Where the knots, centers, or edges are placed, chosen via `target_aware` and `placement_strategy`. | +| Term | Meaning | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scope` | `univariate` methods transform one column at a time. `multivariate` methods model several columns jointly. Tensor-product and thin-plate splines support `Preprocessor(feature_groups=...)`; random Fourier features and Nyström are standalone-only. | +| `supervision` | Whether the method uses the target: `forbidden`, `optional`, or `required`. See [Target awareness](../core_concepts/target_awareness.md). | +| `output_dim` | The width of the expansion. See [Resolution and placement](../core_concepts/resolution_and_placement.md). | +| `placement` | Where the knots, centers, or edges are placed, chosen via `target_aware` and `placement_strategy`. | ## How to select a method diff --git a/docs/representations/spline_expansions.md b/docs/representations/spline_expansions.md index ced5a12..a487a78 100644 --- a/docs/representations/spline_expansions.md +++ b/docs/representations/spline_expansions.md @@ -216,8 +216,9 @@ penalty do the regularizing. Its penalty matrix plugs directly into penalized li ## Multivariate splines -Two families model several inputs jointly. They are used standalone, not selected per column -through `Preprocessor`. +Two families model several inputs jointly. Use them through +`Preprocessor(feature_groups=...)` for exclusive numerical groups, or fit their +standalone transformers directly. Neither is a per-column `numerical_method`. ### Tensor-product spline @@ -286,10 +287,11 @@ non-negative, so the returned penalty is not guaranteed positive semi-definite, actual smoothing regularization until it is fully fixed. ``` -```{warning} -The tensor-product and thin-plate splines are multivariate. They are standalone transformers -and are not available as a per-column `numerical_method`. Fit them directly on the columns you -want to model jointly. +```{note} +Use `feature_groups` to select the joint sources inside `Preprocessor`. A group +has one fitted width and one output block, including its raw missing states. +The [multivariate tutorial](../tutorials/multivariate_features.md) shows how to +configure groups and inspect the actual width rather than assigning it to each source. ``` ## Where to go next diff --git a/docs/tutorials/multivariate_features.md b/docs/tutorials/multivariate_features.md index 4fba8ad..e8002d6 100644 --- a/docs/tutorials/multivariate_features.md +++ b/docs/tutorials/multivariate_features.md @@ -24,12 +24,212 @@ is usually a more natural fit there. `nystroem` : Nyström kernel map. A landmark-based kernel approximation. +```{note} +Use `feature_groups` on `Preprocessor` to apply `tensorspline` or `tprs` to named +numerical columns jointly. Neither is a per-column `numerical_method`. Random +Fourier features and Nyström remain standalone transformers; use a scikit-learn +`ColumnTransformer` to combine them with other representations. +``` + +## Grouped preprocessing with Preprocessor + +A feature group owns its source columns and produces one joint block. Other +columns keep their per-column representations. Here latitude and longitude share +a tensor-product basis, size receives an RBF expansion, and city is one-hot encoded. + +```python +import numpy as np +import pandas as pd + +from pretab import FeatureGroup, Preprocessor, RepresentationConfig + +group_rng = np.random.default_rng(17) +data = pd.DataFrame({ + "longitude": group_rng.uniform(-3, 3, 96), + "latitude": group_rng.uniform(-2, 2, 96), + "size": group_rng.uniform(20, 200, 96), + "city": np.resize(["Lima", "Oslo", "Rome"], 96), +}) +data.loc[0, "latitude"] = np.nan + +location = FeatureGroup( + name="location", + columns=("latitude", "longitude"), + representation=RepresentationConfig( + method="tensorspline", output_dim=3, params={"degree": 2}, + ), +) +pre = Preprocessor( + numerical_method="none", + categorical_method="one-hot", + feature_preprocessing={"size": {"method": "rbf", "output_dim": 3}}, + feature_groups=[location], + target_aware=False, + placement_strategy="uniform", + missing_policy="separate_state", + output_structure="blocks", + output_format="dense", +) +blocks = pre.fit_transform(data) +assert list(blocks) == ["num_size", "group_location", "cat_city"] +``` + +Each group must contain at least two detected numerical columns. A source may +belong to only one group, and cannot also have an explicit `feature_preprocessing` +entry. Categorical and Boolean columns cannot be group sources. Set +`treat_all_integers_as_numerical=True` when low-cardinality integer sources +would otherwise be detected as categorical. +See [Configuration](../core_concepts/configuration.md) for feature detection settings. + +Group order and source order have different meanings. Output blocks appear as +ungrouped numerical columns, groups in declaration order, then categorical columns. +The ordered `columns` tuple determines a group's input axes; it does not need to +match the DataFrame's column order. Named inference columns are matched by label. +Arrays and lists instead use fitted input positions and must have the same width. + +### Read the fitted width + +Tensor-product `output_dim` is the width **per input axis**, not the total group +width. Three basis functions on each of two axes produce $3^2 = 9$ joint basis +columns. With `missing_policy="separate_state"`, two additional raw missing-state +columns follow that basis, in declared source order. The group therefore has +eleven output columns, even when one source has no missing values during fitting. + +```python +assert pre.output_dims_["group_location"] == 11 +assert blocks["group_location"].shape == (len(data), 11) +np.testing.assert_array_equal(blocks["group_location"][0, -2:], [1.0, 0.0]) +assert sum(pre.output_dims_.values()) == pre.total_output_dim_ + +names = pre.get_feature_names_out() +lineage = pre.get_feature_lineage() +assert len(names) == len(lineage) == pre.total_output_dim_ +location_lineage = [item for item in lineage if item.group_id == "group_location"] +assert len(location_lineage) == 11 +assert all( + item.source_features == ("latitude", "longitude") + for item in location_lineage if item.component != "indicator" +) +assert not any(item.uses_target for item in location_lineage) +``` + +Names encode the group and its ordered sources. Joint basis columns trace back to +both inputs; each missing indicator traces back to its own raw source. The two +sources do not receive duplicate copies of the joint width in `output_dims_` or +`get_feature_info()`. + ```{warning} -These four are standalone transformers. They are not available as a per-column -`numerical_method` on `Preprocessor`, because they need the whole input block. Fit them -directly on the columns you want to model jointly. +Tensor-product width grows multiplicatively with the number of sources. Inspect +the fitted width and use output budgets before passing a large joint basis to a +model. `max_features_per_input` applies to the whole group, including raw missing +states, not to an average width per source. +``` + +```python +bounded = pre.clone_unfitted().set_params( + max_features_per_input=16, + max_output_features=64, +) +bounded.fit(data) +assert bounded.output_dims_["group_location"] == 11 +``` + +The built-in tensor and thin-plate groups do not use the target. Tensor-product +splines use local `output_dim`; thin-plate splines use `n_components` to size the +joint basis. To replace the tensor basis with a six-column thin-plate basis: + +```python +thin_plate = FeatureGroup( + name="location", + columns=("latitude", "longitude"), + representation=RepresentationConfig( + method="tprs", + params={ + "n_components": 6, + "landmark_strategy": "subsample", + "random_state": 17, + }, + ), +) +thin_pre = pre.clone_unfitted().set_params(feature_groups=[thin_plate]) +thin_blocks = thin_pre.fit_transform(data) +assert thin_blocks["group_location"].shape[1] == 8 +``` + +The thin-plate group has six joint basis columns plus the same two raw indicators. +Fitted widths are authoritative; they also include categorical encodings and +missing-state columns outside the group. + +### Mapping syntax + +An ordered mapping is equivalent to the typed group declaration. Representation +options belong inside `representation`, not beside `columns`. + +```python +mapped = pre.clone_unfitted().set_params(feature_groups={ + "location": { + "columns": ["latitude", "longitude"], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + }, +}) +mapped_blocks = mapped.fit_transform(data) +for key in blocks: + np.testing.assert_array_equal(mapped_blocks[key], blocks[key]) +``` + +Typed values detach their settings when constructed. Raw constructor mappings +remain live until normalization or fitting. After fitting, `set_params` changes +the requested configuration, not the existing fitted representation. Refit an +unfrozen instance, or use `clone_unfitted()` to learn a different representation. + +### Block widths for DeepTab + +A block-based model needs one input width per output block, not one joint width +for each raw source. Read those widths from fitted output: + +```python +block_widths = {name: values.shape[1] for name, values in blocks.items()} +assert list(block_widths) == ["num_size", "group_location", "cat_city"] +assert block_widths["group_location"] == 11 +assert "latitude" not in block_widths and "longitude" not in block_widths +assert sum(block_widths.values()) == pre.total_output_dim_ +print(block_widths) +``` + +`group_location` is one model input with eleven coordinates. Do not divide eleven +by the two sources or create two identical joint inputs. This example stops at +PreTab's dense block-output boundary. It does not construct or fit a DeepTab +model, and `block_widths` is not a DeepTab configuration object. + +```{note} +Dictionary output is not supported for out-of-fold assembly by +`CrossFittedTransformer`. Use matrix output for that training workflow. An +ordinary all-data `fit` followed by a dictionary `transform` is not a substitute +for out-of-fold features when another representation uses the target. ``` +### Preserve a fitted group + +Specs retain fitted group order, learned parameters, output metadata and frozen +state. The example uses strict JSON and reloads the preprocessor without fitting: + +```python +import json + +pre.freeze() +restored = Preprocessor.from_spec(json.loads(json.dumps(pre.to_spec(), allow_nan=False))) +restored_blocks = restored.transform(data[data.columns[::-1]]) +assert restored.is_frozen() +assert restored.fingerprint_ == pre.fingerprint_ +np.testing.assert_array_equal(restored.get_feature_names_out(), names) +for key in blocks: + np.testing.assert_array_equal(restored_blocks[key], blocks[key]) +``` + +Use specs only from trusted sources; loading can import supported library code. +A spec does not guarantee compatibility across dependency versions. See +[Reproducibility](../core_concepts/reproducibility.md) for the persistence contract. + ## A smooth surface with thin-plate splines Suppose the target is a smooth function of two coordinates. A per-column expansion cannot see diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index 146f6e7..87480ff 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -73,7 +73,12 @@ def isolate_document_state(tmp_path, monkeypatch): ROOT / "docs" / "core_concepts" / "configuration.md", "Structured per-feature configuration", id="configuration", - ) + ), + pytest.param( + TUTORIALS_DIR / "multivariate_features.md", + "Grouped preprocessing with Preprocessor", + id="feature-groups", + ), ], ) @pytest.mark.filterwarnings("ignore::pretab.exceptions.LeakageWarning") From 3fbd23db0ee1a28b87c8088b0aed13fd999eb1c2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Thu, 19 Nov 2026 23:33:48 +0100 Subject: [PATCH 45/86] feat(spline): add immutable penalty specifications --- pretab/__init__.py | 2 + pretab/expansion/spline/__init__.py | 2 + pretab/expansion/spline/penalty.py | 210 ++++++++++++++++++++ tests/expansion/spline/test_penalty_spec.py | 177 +++++++++++++++++ tests/regression/_snapshots/public_api.json | 2 + 5 files changed, 393 insertions(+) create mode 100644 pretab/expansion/spline/penalty.py create mode 100644 tests/expansion/spline/test_penalty_spec.py diff --git a/pretab/__init__.py b/pretab/__init__.py index 96563c4..61f5681 100644 --- a/pretab/__init__.py +++ b/pretab/__init__.py @@ -13,6 +13,7 @@ PretabWarning, RepresentationConformanceError, ) +from .expansion.spline import PenaltySpec from .extension import ( BaseRepresentation, check_representation, @@ -30,6 +31,7 @@ "FrozenRepresentationError", "LeakageWarning", "OutputBudgetError", + "PenaltySpec", "Preprocessor", "PretabSerializationError", "PretabWarning", diff --git a/pretab/expansion/spline/__init__.py b/pretab/expansion/spline/__init__.py index 72976f6..984a058 100644 --- a/pretab/expansion/spline/__init__.py +++ b/pretab/expansion/spline/__init__.py @@ -7,6 +7,7 @@ from .multivariate.thin_plate import ThinPlateSplineTransformer from .natural_cubic import NaturalCubicSplineTransformer from .p_spline import PSplineTransformer +from .penalty import PenaltySpec __all__ = [ "BSplineTransformer", @@ -16,6 +17,7 @@ "MSplineTransformer", "NaturalCubicSplineTransformer", "PSplineTransformer", + "PenaltySpec", "TensorProductSplineTransformer", "ThinPlateSplineTransformer", ] diff --git a/pretab/expansion/spline/penalty.py b/pretab/expansion/spline/penalty.py new file mode 100644 index 0000000..a7a656f --- /dev/null +++ b/pretab/expansion/spline/penalty.py @@ -0,0 +1,210 @@ +"""Validated penalty matrices in explicit coefficient coordinates.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from math import isfinite +from numbers import Integral, Real +from types import MappingProxyType +from typing import Any + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from ...exceptions import InvalidParamError, invalid_param_error + + +def _invalid(name: str, value: object, constraint: str) -> InvalidParamError: + return invalid_param_error("PenaltySpec", name, value, constraint) + + +def _text(name: str, value: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise _invalid(name, value, "must be a nonempty string") + return value + + +def _items(name: str, values: object) -> tuple[Any, ...]: + if isinstance(values, (str, bytes, bytearray)) or not isinstance(values, (Sequence, np.ndarray)): + raise _invalid(name, values, "must be a nonempty ordered sequence") + if (isinstance(values, np.ndarray) and values.ndim != 1) or len(values) == 0: + raise _invalid(name, values, "must be a nonempty one-dimensional sequence") + return tuple(values) + + +def _integer(name: str, value: int, minimum: int) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value < minimum: + raise _invalid(name, value, f"must be an integer >= {minimum}") + return int(value) + + +def _tolerance(name: str, value: float) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real) or value < 0: + raise _invalid(name, value, "must be a finite nonnegative real number") + try: + result = float(value) + except OverflowError as exc: + raise _invalid(name, value, "must be a finite nonnegative real number") from exc + if not isfinite(result): + raise _invalid(name, value, "must be a finite nonnegative real number") + return result + + +def _freeze_provenance(value: Any, active: set[int]) -> Any: + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float) and isfinite(value): + return float(value) + if isinstance(value, (Mapping, list, tuple)): + identity = id(value) + if identity in active: + raise _invalid("provenance", value, "must not contain circular references") + active.add(identity) + try: + if isinstance(value, Mapping): + if not all(isinstance(key, str) for key in value): + raise _invalid("provenance", value, "mapping keys must be strings") + return MappingProxyType({key: _freeze_provenance(item, active) for key, item in value.items()}) + return tuple(_freeze_provenance(item, active) for item in value) + finally: + active.remove(identity) + raise _invalid("provenance", value, "must contain only finite JSON-compatible values") + + +def _copy_provenance(value: Any) -> Any: + if isinstance(value, Mapping): + return {key: _copy_provenance(item) for key, item in value.items()} + if isinstance(value, tuple): + return [_copy_provenance(item) for item in value] + return value + + +def _validated_matrix(matrix: ArrayLike, atol: float, rtol: float) -> tuple[NDArray[np.float64], int]: + try: + raw = np.asarray(matrix) + except (TypeError, ValueError, OverflowError) as exc: + raise _invalid("matrix", matrix, "must be a nonempty real square matrix") from exc + if raw.ndim != 2 or raw.shape[0] == 0 or raw.shape[0] != raw.shape[1] or raw.dtype.kind not in "iuf": + raise _invalid("matrix", matrix, "must be a nonempty real square matrix") + with np.errstate(over="ignore", invalid="ignore"): + values = np.array(raw, dtype=np.float64, order="C", copy=True) + if not np.isfinite(values).all(): + raise _invalid("matrix", matrix, "must contain only finite float64 values") + + scale = float(np.max(np.abs(values))) or 1.0 + scaled = values / scale + symmetric = (scaled + scaled.T) * 0.5 + try: + eigenvalues = np.linalg.eigvalsh(symmetric) + except np.linalg.LinAlgError as exc: + raise _invalid("matrix", matrix, "could not validate its symmetric eigenvalues") from exc + threshold = atol / scale + rtol * float(np.max(np.abs(eigenvalues))) + if (threshold == 0 and not np.array_equal(values, values.T)) or np.max(np.abs(scaled - scaled.T)) > threshold: + raise _invalid("matrix", matrix, "must be symmetric within the recorded tolerance") + if eigenvalues[0] < -threshold: + raise _invalid("matrix", matrix, "must be positive semidefinite within the recorded tolerance") + return values, int(np.count_nonzero(eigenvalues > threshold)) + + +@dataclass(frozen=True, init=False, eq=False, slots=True) +class PenaltySpec: + """Immutable quadratic penalty and its ordered output coefficient coordinates. + + ``matrix`` is a detached, read-only float64 array. The unscaled penalty is + ``beta.T @ matrix @ beta`` in the order of ``coefficient_names`` and + ``coefficient_indices``. ``axis`` names the source directions. ``order`` is + a positive integer or ``None`` for a convention without a difference order. + + Symmetry, positive semidefiniteness and numerical rank are checked using + ``atol + rtol * spectral_norm`` of the symmetric part. Validation never + repairs the stored matrix. ``rank`` and ``nullity`` are derived, and nested + JSON-compatible ``provenance`` is detached and read-only. + """ + + _matrix_bytes: bytes = field(repr=False) + kind: str + order: int | None + axis: tuple[str, ...] + coordinate_system: str + coefficient_names: tuple[str, ...] + coefficient_indices: tuple[int, ...] + rank: int + nullity: int + atol: float + rtol: float + provenance: Mapping[str, Any] + + def __init__( + self, + matrix: ArrayLike, + kind: str, + order: int | None, + axis: Sequence[str], + coordinate_system: str, + coefficient_names: Sequence[str], + coefficient_indices: Sequence[int], + atol: float = 1e-10, + rtol: float = 1e-10, + provenance: Mapping[str, Any] | None = None, + ) -> None: + kind = _text("kind", kind) + if kind == "coefficient_difference" and order is None: + raise _invalid("order", order, "coefficient_difference requires a positive integer order") + order = None if order is None else _integer("order", order, 1) + axes = tuple(_text("axis", label) for label in _items("axis", axis)) + coordinate_system = _text("coordinate_system", coordinate_system) + names = tuple(_text("coefficient_names", name) for name in _items("coefficient_names", coefficient_names)) + indices = tuple( + _integer("coefficient_indices", index, 0) for index in _items("coefficient_indices", coefficient_indices) + ) + atol, rtol = _tolerance("atol", atol), _tolerance("rtol", rtol) + values, rank = _validated_matrix(matrix, atol, rtol) + width = values.shape[0] + for field_name, coordinates in (("coefficient_names", names), ("coefficient_indices", indices)): + if len(coordinates) != width or len(set(coordinates)) != width: + raise _invalid(field_name, coordinates, "must contain one distinct entry per matrix row") + if len(set(axes)) != len(axes): + raise _invalid("axis", axis, "must contain distinct source labels") + if provenance is not None and not isinstance(provenance, Mapping): + raise _invalid("provenance", provenance, "must be a mapping") + + object.__setattr__(self, "_matrix_bytes", values.tobytes()) + object.__setattr__(self, "kind", kind) + object.__setattr__(self, "order", order) + object.__setattr__(self, "axis", axes) + object.__setattr__(self, "coordinate_system", coordinate_system) + object.__setattr__(self, "coefficient_names", names) + object.__setattr__(self, "coefficient_indices", indices) + object.__setattr__(self, "rank", rank) + object.__setattr__(self, "nullity", width - rank) + object.__setattr__(self, "atol", atol) + object.__setattr__(self, "rtol", rtol) + object.__setattr__(self, "provenance", _freeze_provenance({} if provenance is None else provenance, set())) + + @property + def matrix(self) -> NDArray[np.float64]: + """Read-only matrix with independent array metadata on each access.""" + width = len(self.coefficient_indices) + return np.frombuffer(self._matrix_bytes, dtype=np.float64).reshape(width, width) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PenaltySpec): + return NotImplemented + return self._metadata() == other._metadata() and np.array_equal(self.matrix, other.matrix) + + def _metadata(self) -> tuple: + return ( + self.kind, + self.order, + self.axis, + self.coordinate_system, + self.coefficient_names, + self.coefficient_indices, + self.atol, + self.rtol, + self.provenance, + ) + + def __reduce__(self): + return type(self), (self.matrix, *self._metadata()[:-1], _copy_provenance(self.provenance)) diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py new file mode 100644 index 0000000..c15b02a --- /dev/null +++ b/tests/expansion/spline/test_penalty_spec.py @@ -0,0 +1,177 @@ +"""Value and validation contracts for coefficient-coordinate penalties.""" + +import pickle +from copy import copy, deepcopy +from dataclasses import FrozenInstanceError + +import numpy as np +import pytest + +from pretab import PenaltySpec +from pretab.exceptions import InvalidParamError +from pretab.expansion.spline import PenaltySpec as SplinePenaltySpec + + +def _spec(matrix, **overrides): + settings = { + "kind": "coefficient_difference", + "order": 1, + "axis": ["age"], + "coordinate_system": "output_coefficients", + "coefficient_names": ["age_0", "age_1"], + "coefficient_indices": [2, 3], + } + return PenaltySpec(matrix, **(settings | overrides)) + + +def test_penalty_is_detached_immutable_and_has_derived_rank(): + original = np.array([[1, -1], [-1, 1]], dtype=np.int16) + provenance = {"options": [{"bias": False}]} + spec = _spec(original, provenance=provenance) + original[:] = 0 + provenance["options"][0]["bias"] = True + + np.testing.assert_array_equal(spec.matrix, [[1.0, -1.0], [-1.0, 1.0]]) + assert spec.matrix.dtype == np.float64 + assert (spec.rank, spec.nullity) == (1, 1) + assert spec.coefficient_indices == (2, 3) + assert spec.provenance["options"][0]["bias"] is False + with pytest.raises(FrozenInstanceError): + setattr(spec, "rank", 2) # noqa: B010 + with pytest.raises(ValueError): + spec.matrix.setflags(write=True) + with pytest.raises(TypeError): + spec.provenance["options"][0]["bias"] = True + assert deepcopy(spec) == spec + + +def test_material_negative_direction_is_rejected(): + with pytest.raises(InvalidParamError, match="positive semidefinite"): + _spec([[1.0, 0.0], [0.0, -0.5]]) + + +@pytest.mark.parametrize("restore", [copy, deepcopy, lambda spec: pickle.loads(pickle.dumps(spec))]) # noqa: S301 +def test_restored_values_retain_immutable_storage(restore): + spec = _spec(np.eye(2), provenance={"axes": ["age"], "options": {"bias": False}}) + restored = restore(spec) + assert restored == spec + assert restored != _spec(np.eye(2)) + with pytest.raises(ValueError): + restored.matrix.setflags(write=True) + with pytest.raises(ValueError): + restored.matrix.base.setflags(write=True) + with pytest.raises(TypeError): + restored.provenance["options"]["bias"] = True + + +def test_public_export_and_ordered_metadata(): + names = ["joint_1", "joint_0"] + indices = [np.int64(7), np.int64(3)] + axes = ["north", "east"] + spec = _spec( + np.eye(2), + coefficient_names=names, + coefficient_indices=indices, + axis=axes, + kind="quadratic_form", + order=None, + ) + names.reverse() + indices.reverse() + axes.reverse() + assert type(spec) is SplinePenaltySpec is PenaltySpec + assert spec.coefficient_names == ("joint_1", "joint_0") + assert spec.coefficient_indices == (7, 3) + assert spec.axis == ("north", "east") + assert spec.order is None + assert spec != _spec(np.eye(2)) + with pytest.raises(TypeError): + hash(spec) + assert spec.matrix is not spec.matrix + assert spec.matrix.base is not spec.matrix.base + assert spec.matrix.shape == (2, 2) + + +@pytest.mark.parametrize("scale", [1e-300, 1.0, 1e308]) +def test_relative_tolerance_preserves_values_and_scales_rank(scale): + matrix = scale * np.array([[1.0, 1e-12], [0.0, -1e-12]]) + spec = _spec(matrix, atol=0.0, rtol=1e-10) + np.testing.assert_array_equal(spec.matrix, matrix) + assert (spec.rank, spec.nullity) == (1, 1) + with pytest.raises(InvalidParamError, match="symmetric"): + _spec(matrix, atol=0.0, rtol=0.0) + with pytest.raises(InvalidParamError, match="positive semidefinite"): + _spec(np.diag([scale, -scale * 1e-12]), atol=0.0, rtol=0.0) + + +def test_absolute_tolerance_includes_boundary_and_rank_is_strict(): + spec = _spec(np.diag([0.25, -0.25]), atol=0.25, rtol=0.0) + assert (spec.rank, spec.nullity) == (0, 2) + assert (spec.atol, spec.rtol) == (0.25, 0.0) + np.testing.assert_array_equal(spec.matrix, np.diag([0.25, -0.25])) + zero = _spec(np.zeros((2, 2)), atol=0.0, rtol=0.0) + assert (zero.rank, zero.nullity) == (0, 2) + + +@pytest.mark.parametrize( + "matrix", + [ + [], + [1, 2], + [[1], [1]], + [[1, 2], [3]], + np.eye(2, dtype=complex), + np.eye(2, dtype=bool), + [["1", "0"], ["0", "1"]], + [[1.0, np.nan], [0.0, 1.0]], + [[np.inf, 0], [0, 1]], + ], +) +def test_invalid_matrices_raise_typed_errors(matrix): + with pytest.raises(InvalidParamError, match="matrix"): + _spec(matrix) + + +@pytest.mark.parametrize( + ("name", "value"), + [ + ("kind", " "), + ("order", True), + ("order", np.bool_(True)), + ("order", 0), + ("order", 1.5), + ("order", None), + ("axis", "east"), + ("axis", []), + ("axis", ["east", "east"]), + ("axis", [3]), + ("coordinate_system", ""), + ("coefficient_names", ["a"]), + ("coefficient_names", ["a", "a"]), + ("coefficient_names", ["a", ""]), + ("coefficient_indices", [0]), + ("coefficient_indices", [1, 1]), + ("coefficient_indices", [0, -1]), + ("coefficient_indices", [False, 1]), + ("coefficient_indices", [0, 1.0]), + ("atol", -1), + ("atol", np.inf), + ("rtol", np.nan), + ("rtol", True), + ("provenance", []), + ("provenance", {1: "x"}), + ("provenance", {"x": {1}}), + ("provenance", {"x": [np.inf]}), + ], +) +def test_invalid_metadata_raises_typed_errors(name, value): + with pytest.raises(InvalidParamError, match=name): + _spec(np.eye(2), **{name: value}) + + +def test_provenance_rejects_cycles_but_accepts_shared_nested_values(): + nested: list[object] = ["age"] + assert _spec(np.eye(2), provenance={"a": nested, "b": nested}).provenance == {"a": ("age",), "b": ("age",)} + nested.append(nested) + with pytest.raises(InvalidParamError, match="circular"): + _spec(np.eye(2), provenance={"axes": nested}) diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index 64a51ba..6f56d88 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -147,6 +147,7 @@ "FrozenRepresentationError", "LeakageWarning", "OutputBudgetError", + "PenaltySpec", "Preprocessor", "PretabSerializationError", "PretabWarning", @@ -1122,6 +1123,7 @@ "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None)", "pretab.FeatureGroup": "(name: 'str', columns: 'Sequence[Any]', representation: 'str | Mapping[str, Any] | RepresentationConfig') -> None", "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool, group_id: str | None = None) -> None", + "pretab.PenaltySpec": "(matrix: 'ArrayLike', kind: 'str', order: 'int | None', axis: 'Sequence[str]', coordinate_system: 'str', coefficient_names: 'Sequence[str]', coefficient_indices: 'Sequence[int]', atol: 'float' = 1e-10, rtol: 'float' = 1e-10, provenance: 'Mapping[str, Any] | None' = None) -> 'None'", "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None, *, feature_groups=None)", "pretab.RepresentationConfig": "(method: 'str', output_dim: 'int | _Unset' = UNSET, target_aware: 'bool | _Unset' = UNSET, placement_strategy: 'str | _Unset' = UNSET, adaptive: 'bool | _Unset' = UNSET, min_output_dim: 'int | _Unset | None' = UNSET, max_output_dim: 'int | _Unset | None' = UNSET, params: 'Mapping[str, Any]' = , name: 'str | None' = None) -> None", "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", From 7050fa1cc922a44c61d3f97d8b0bef257a35ea0e Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 20 Nov 2026 00:07:34 +0100 Subject: [PATCH 46/86] feat(spline): expose typed difference penalties --- pretab/expansion/spline/base.py | 65 ++++++++++++++++++ tests/expansion/spline/test_penalty_spec.py | 75 ++++++++++++++++++++- 2 files changed, 139 insertions(+), 1 deletion(-) diff --git a/pretab/expansion/spline/base.py b/pretab/expansion/spline/base.py index d5540bf..8350025 100644 --- a/pretab/expansion/spline/base.py +++ b/pretab/expansion/spline/base.py @@ -30,13 +30,16 @@ from ...core.parameters import UNSET, validate_placement, validate_task from ...core.policy import RepresentationPolicy, resolve_out_of_range from ...core.supervised import warn_target_leakage +from ...core.validation import resolve_input_features from ...exceptions import ( DataWarning, InvalidParamError, PretabDataError, + PretabNotFittedError, invalid_param_error, ) from ...placement.adapters import SplinePlacementAdapter +from .penalty import PenaltySpec class BaseSplineTransformer(BasePreTabTransformer): @@ -444,3 +447,65 @@ def get_penalty_matrix(self, feature_index: int = 0, diff_order: int = 2): full[1:, 1:] = penalty return full return penalty + + def get_penalty_spec(self, feature_index: int = 0, *, diff_order: int | None = None) -> PenaltySpec: + """Return the base difference penalty in the selected feature's output coordinates. + + ``diff_order=None`` selects the legacy default of two. An explicit order + must be positive and smaller than the selected basis width without bias. + Output indices refer to this transformer's full output, including any + unpenalized bias column. Subclasses with a different matrix convention + must provide their own typed accessor. + + Raises + ------ + PretabNotFittedError + If the transformer has not been fitted. + InvalidParamError + If a feature index or difference order is invalid, or the subclass + overrides the legacy matrix without a typed convention. + """ + estimator = type(self).__name__ + if not hasattr(self, "n_basis_"): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_spec().") + legacy_accessor = self.get_penalty_matrix + if getattr(legacy_accessor, "__func__", None) is not BaseSplineTransformer.get_penalty_matrix: + raise invalid_param_error( + estimator, + "get_penalty_spec", + None, + "this penalty convention is not supported; use get_penalty_matrix() for the legacy matrix", + ) + if ( + isinstance(feature_index, (bool, np.bool_)) + or not isinstance(feature_index, (int, np.integer)) + or not 0 <= feature_index < len(self.n_basis_) + ): + raise invalid_param_error( + estimator, "feature_index", feature_index, f"must be in [0, {len(self.n_basis_)})" + ) + index = int(feature_index) + order = 2 if diff_order is None else diff_order + if ( + isinstance(order, (bool, np.bool_)) + or not isinstance(order, (int, np.integer)) + or order < 1 + or (diff_order is not None and order >= self.n_basis_[index]) + ): + raise invalid_param_error( + estimator, "diff_order", diff_order, f"must be an integer in [1, {self.n_basis_[index]})" + ) + sizes = self._output_sizes() + start = sum(sizes[:index]) + stop = start + sizes[index] + axis = str(resolve_input_features(self, None)[index]) + return PenaltySpec( + matrix=legacy_accessor(feature_index=index, diff_order=int(order)), + kind="coefficient_difference", + order=int(order), + axis=(axis,), + coordinate_system="output_coefficients", + coefficient_names=tuple(self.get_feature_names_out()[start:stop]), + coefficient_indices=range(start, stop), + provenance={"transformer": estimator, "include_bias": bool(self.include_bias)}, + ) diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py index c15b02a..871e3d5 100644 --- a/tests/expansion/spline/test_penalty_spec.py +++ b/tests/expansion/spline/test_penalty_spec.py @@ -5,11 +5,13 @@ from dataclasses import FrozenInstanceError import numpy as np +import pandas as pd import pytest from pretab import PenaltySpec -from pretab.exceptions import InvalidParamError +from pretab.exceptions import InvalidParamError, PretabNotFittedError from pretab.expansion.spline import PenaltySpec as SplinePenaltySpec +from pretab.transformers import BSplineTransformer, ISplineTransformer, MSplineTransformer def _spec(matrix, **overrides): @@ -175,3 +177,74 @@ def test_provenance_rejects_cycles_but_accepts_shared_nested_values(): nested.append(nested) with pytest.raises(InvalidParamError, match="circular"): _spec(np.eye(2), provenance={"axes": nested}) + + +@pytest.mark.parametrize("transformer_cls", [BSplineTransformer, MSplineTransformer, ISplineTransformer]) +@pytest.mark.parametrize("include_bias", [False, True]) +@pytest.mark.parametrize("diff_order", [None, np.int64(1), 2]) +def test_base_typed_accessor_matches_legacy_and_named_output_span(transformer_cls, include_bias, diff_order): + source = np.linspace(0, 1, 21) + frame = pd.DataFrame({"left": source, "right": source**2}) + spline = transformer_cls(output_dim=6, include_bias=include_bias).fit(frame) + spec = spline.get_penalty_spec(np.int64(1), diff_order=diff_order) + width = len(spline.get_feature_names_out()) // 2 + order = 2 if diff_order is None else int(diff_order) + legacy = spline.get_penalty_matrix(feature_index=1, diff_order=order) + + np.testing.assert_array_equal(spec.matrix, legacy) + assert not spec.matrix.flags.writeable + assert (spec.kind, spec.order, spec.axis) == ("coefficient_difference", order, ("right",)) + assert spec.coordinate_system == "output_coefficients" + assert spec.coefficient_indices == tuple(range(width, 2 * width)) + assert spec.coefficient_names == tuple(spline.get_feature_names_out()[width:]) + assert spec.matrix.shape == (width, width) + assert (spec.rank, spec.nullity) == (width - order - int(include_bias), order + int(include_bias)) + if include_bias: + np.testing.assert_array_equal(spec.matrix[0], np.zeros(width)) + + +def test_base_typed_accessor_requires_fit_and_uses_synthetic_names_for_arrays(): + spline = BSplineTransformer(output_dim=6) + with pytest.raises(PretabNotFittedError, match="must be fitted"): + spline.get_penalty_spec() + spline.fit(np.linspace(0, 1, 21).reshape(-1, 1)) + spec = spline.get_penalty_spec() + assert spec.axis == ("x0",) + np.testing.assert_array_equal(spec.matrix, spline.get_penalty_matrix()) + + +@pytest.mark.parametrize("feature_index", [-1, 1, True, np.bool_(False), 0.0, "0"]) +def test_base_typed_accessor_rejects_invalid_indices(feature_index): + spline = BSplineTransformer(output_dim=6).fit(np.linspace(0, 1, 21).reshape(-1, 1)) + with pytest.raises(InvalidParamError, match="feature_index"): + spline.get_penalty_spec(feature_index) + + +@pytest.mark.parametrize("diff_order", [0, -1, 6, 7, True, np.bool_(False), 1.0, "1"]) +def test_base_typed_accessor_rejects_invalid_explicit_orders(diff_order): + spline = BSplineTransformer(output_dim=6, include_bias=True).fit(np.linspace(0, 1, 21).reshape(-1, 1)) + with pytest.raises(InvalidParamError, match="diff_order"): + spline.get_penalty_spec(diff_order=diff_order) + + +def test_typed_validation_does_not_change_legacy_validation(): + spline = BSplineTransformer(output_dim=6).fit(np.linspace(0, 1, 21).reshape(-1, 1)) + np.testing.assert_array_equal(spline.get_penalty_matrix(-1, 0), np.eye(6)) + with pytest.raises(InvalidParamError, match="feature_index"): + spline.get_penalty_spec(-1, diff_order=0) + with pytest.raises(InvalidParamError, match="diff_order"): + spline.get_penalty_spec(diff_order=0) + + +def test_base_typed_accessor_does_not_infer_an_overridden_convention(): + class OtherPenaltySpline(BSplineTransformer): + def get_penalty_matrix(self, feature_index: int = 0, diff_order: int = 2): + return np.eye(self.n_basis_[feature_index]) + + spline = OtherPenaltySpline(output_dim=6) + with pytest.raises(PretabNotFittedError, match="OtherPenaltySpline"): + spline.get_penalty_spec() + spline.fit(np.linspace(0, 1, 21).reshape(-1, 1)) + with pytest.raises(InvalidParamError, match=r"not supported; use get_penalty_matrix\(\)"): + spline.get_penalty_spec() + np.testing.assert_array_equal(spline.get_penalty_matrix(), np.eye(6)) From ebb1886e61daa6918c9d87fdb0169ef9e89578b5 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 20 Nov 2026 00:27:38 +0100 Subject: [PATCH 47/86] feat(spline): expose typed P-spline penalties --- pretab/expansion/spline/p_spline.py | 69 +++++++++++++++- tests/expansion/spline/test_penalty_spec.py | 89 ++++++++++++++++++++- 2 files changed, 156 insertions(+), 2 deletions(-) diff --git a/pretab/expansion/spline/p_spline.py b/pretab/expansion/spline/p_spline.py index 6ba7b2c..006e7f7 100644 --- a/pretab/expansion/spline/p_spline.py +++ b/pretab/expansion/spline/p_spline.py @@ -1,3 +1,5 @@ +from typing import Any + import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted @@ -5,8 +7,10 @@ from ...core.knots import bspline_basis, extrapolate_bspline_rows from ...core.parameters import UNSET from ...core.policy import RepresentationPolicy, resolve_out_of_range -from ...exceptions import InvalidParamError +from ...core.validation import resolve_input_features +from ...exceptions import InvalidParamError, PretabNotFittedError, invalid_param_error from .mixins import SplineBasisMixin +from .penalty import PenaltySpec class PSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -155,6 +159,7 @@ def __init__( self.policy = policy def fit(self, X, y=None): + self.__dict__.pop("_penalty_fit_", None) X = self._validate_allow_nan(X, reset=True) output_dim = self._resolve_param("output_dim", default=6) if self.placement_strategy != "uniform": @@ -204,6 +209,7 @@ def fit(self, X, y=None): self.n_knots_.append(max(0, len(knots) - 2 * (self.degree + 1))) self.penalty_.append(penalty) + self._penalty_fit_ = (int(self.diff_order), bool(self.include_bias)) return self def transform(self, X): @@ -241,3 +247,64 @@ def get_penalty_matrix(self, feature_index=0): """ check_is_fitted(self, "penalty_") return self.penalty_[feature_index] + + def get_penalty_spec( + self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | np.integer[Any] | None = None + ) -> PenaltySpec: + """Return the fitted difference penalty for the selected feature. + + Typed penalties support fitted orders one and two. Omit ``diff_order`` + to use the fitted order, or specify that same order explicitly. The + coefficient positions refer to the full transformer output, including + the leading unpenalized bias column for each feature if fitted with bias. + + Raises + ------ + PretabNotFittedError + If no fitted penalty matrices are available. + InvalidParamError + If the fitted convention is unavailable or unsupported, or the + feature index or explicit order is invalid. + """ + estimator = type(self).__name__ + if not hasattr(self, "penalty_"): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_spec().") + fitted = getattr(self, "_penalty_fit_", None) + if fitted is None: + raise invalid_param_error(estimator, "get_penalty_spec", None, "refit to record the fitted penalty order") + order, include_bias = fitted + if order not in (1, 2): + raise invalid_param_error( + estimator, + "diff_order", + order, + "typed P-spline penalties support fitted orders 1 and 2; " + "use get_penalty_matrix() for the legacy matrix", + ) + if diff_order is not None and ( + isinstance(diff_order, (bool, np.bool_)) + or not isinstance(diff_order, (int, np.integer)) + or diff_order != order + ): + raise invalid_param_error(estimator, "diff_order", diff_order, f"must match the fitted order ({order})") + sizes = self._output_sizes() + if ( + isinstance(feature_index, (bool, np.bool_)) + or not isinstance(feature_index, (int, np.integer)) + or not 0 <= feature_index < len(sizes) + ): + raise invalid_param_error(estimator, "feature_index", feature_index, f"must be in [0, {len(sizes)})") + index = int(feature_index) + start = sum(sizes[:index]) + stop = start + sizes[index] + axis = str(resolve_input_features(self, None)[index]) + return PenaltySpec( + matrix=self.get_penalty_matrix(index), + kind="coefficient_difference", + order=order, + axis=(axis,), + coordinate_system="output_coefficients", + coefficient_names=tuple(self.get_feature_names_out()[start:stop]), + coefficient_indices=range(start, stop), + provenance={"transformer": estimator, "include_bias": include_bias}, + ) diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py index 871e3d5..e70c566 100644 --- a/tests/expansion/spline/test_penalty_spec.py +++ b/tests/expansion/spline/test_penalty_spec.py @@ -11,7 +11,7 @@ from pretab import PenaltySpec from pretab.exceptions import InvalidParamError, PretabNotFittedError from pretab.expansion.spline import PenaltySpec as SplinePenaltySpec -from pretab.transformers import BSplineTransformer, ISplineTransformer, MSplineTransformer +from pretab.transformers import BSplineTransformer, ISplineTransformer, MSplineTransformer, PSplineTransformer def _spec(matrix, **overrides): @@ -248,3 +248,90 @@ def get_penalty_matrix(self, feature_index: int = 0, diff_order: int = 2): with pytest.raises(InvalidParamError, match=r"not supported; use get_penalty_matrix\(\)"): spline.get_penalty_spec() np.testing.assert_array_equal(spline.get_penalty_matrix(), np.eye(6)) + + +@pytest.mark.parametrize("order", [1, 2]) +@pytest.mark.parametrize("include_bias", [False, True]) +@pytest.mark.parametrize("index", [0, 1]) +def test_pspline_typed_penalty_matches_fitted_matrix_and_output(order, include_bias, index): + source = np.linspace(0, 1, 21) + frame = pd.DataFrame({"left": source, "right": source**2}) + spline = PSplineTransformer(output_dim=6, diff_order=order, include_bias=include_bias).fit(frame) + spec = spline.get_penalty_spec(index) + assert spec == spline.get_penalty_spec(np.int64(index), diff_order=np.int64(order)) + width = 6 + int(include_bias) + span = slice(index * width, (index + 1) * width) + difference = np.diff(np.eye(6), n=order, axis=0) + if include_bias: + difference = np.pad(difference, ((0, 0), (1, 0))) + legacy = spline.get_penalty_matrix(index) + np.testing.assert_array_equal(spec.matrix, legacy) + np.testing.assert_array_equal(spec.matrix, difference.T @ difference) + assert not np.shares_memory(spec.matrix, legacy) + assert (spec.kind, spec.order, spec.axis) == ("coefficient_difference", order, (frame.columns[index],)) + assert spec.coordinate_system == "output_coefficients" + assert spec.coefficient_indices == tuple(range(span.start, span.stop)) + assert spec.coefficient_names == tuple(spline.get_feature_names_out()[span]) + assert spline.transform(frame)[:, span].shape[1] == spec.matrix.shape[0] + assert (spec.rank, spec.nullity) == (6 - order, order + int(include_bias)) + assert spec.provenance["include_bias"] is include_bias + coefficients = np.arange(width, dtype=float) ** 2 + assert coefficients @ spec.matrix @ coefficients == pytest.approx(np.linalg.norm(difference @ coefficients) ** 2) + + +def test_pspline_typed_penalty_uses_fit_order_until_refit(): + source = np.linspace(0, 1, 21).reshape(-1, 1) + spline = PSplineTransformer(diff_order=1) + with pytest.raises(PretabNotFittedError): + spline.get_penalty_spec() + spline.fit(source) + original = spline.get_penalty_spec() + spline.set_params(diff_order=2) + assert original.axis == ("x0",) + assert spline.get_penalty_spec() == original + with pytest.raises(InvalidParamError, match=r"match the fitted order \(1\)"): + spline.get_penalty_spec(diff_order=2) + spline.fit(source) + assert spline.get_penalty_spec().order == 2 + + +@pytest.mark.parametrize("diff_order", [0, 2, True, np.bool_(True), 1.0, "1"]) +def test_pspline_typed_penalty_rejects_an_invalid_explicit_order(diff_order): + spline = PSplineTransformer(diff_order=1).fit(np.linspace(0, 1, 21).reshape(-1, 1)) + with pytest.raises(InvalidParamError, match="must match the fitted order"): + spline.get_penalty_spec(diff_order=diff_order) + + +@pytest.mark.parametrize("feature_index", [-1, 1, False, 0.0]) +def test_pspline_typed_penalty_rejects_invalid_indices(feature_index): + spline = PSplineTransformer().fit(np.linspace(0, 1, 21).reshape(-1, 1)) + with pytest.raises(InvalidParamError, match="feature_index"): + spline.get_penalty_spec(feature_index) + + +def test_pspline_typed_penalty_refuses_unqualified_higher_orders(): + spline = PSplineTransformer(diff_order=3).fit(np.linspace(0, 1, 21).reshape(-1, 1)) + with pytest.raises(InvalidParamError, match="support fitted orders 1 and 2"): + spline.get_penalty_spec() + assert np.linalg.matrix_rank(spline.get_penalty_matrix()) == 3 + + +def test_pspline_typed_penalty_replay_requires_fitted_metadata(): + spline = PSplineTransformer(diff_order=1, include_bias=True).fit(np.linspace(0, 1, 21).reshape(-1, 1)) + expected = spline.get_penalty_spec() + restored = pickle.loads(pickle.dumps(spline)) # noqa: S301 + assert restored.get_penalty_spec() == expected + del restored._penalty_fit_ + with pytest.raises(InvalidParamError, match="refit to record the fitted penalty order"): + restored.get_penalty_spec() + np.testing.assert_array_equal(restored.get_penalty_matrix(), expected.matrix) + + +def test_pspline_typed_penalty_refuses_state_after_failed_refit(): + source = np.linspace(0, 1, 21).reshape(-1, 1) + spline = PSplineTransformer(diff_order=1).fit(source) + spline.set_params(diff_order=20) + with pytest.raises(InvalidParamError, match="too large"): + spline.fit(source) + with pytest.raises(InvalidParamError, match="refit to record the fitted penalty order"): + spline.get_penalty_spec() From 62758834670bf7bc0ccd3675f8b295677e02f4d7 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 20 Nov 2026 13:38:37 +0100 Subject: [PATCH 48/86] feat(spline): expose typed curvature penalties --- pretab/expansion/spline/cubic_regression.py | 21 ++++ pretab/expansion/spline/mixins.py | 63 +++++++++++- pretab/expansion/spline/natural_cubic.py | 22 ++++ tests/expansion/spline/test_penalty_spec.py | 107 +++++++++++++++++++- 4 files changed, 211 insertions(+), 2 deletions(-) diff --git a/pretab/expansion/spline/cubic_regression.py b/pretab/expansion/spline/cubic_regression.py index 1ce7fde..add9796 100644 --- a/pretab/expansion/spline/cubic_regression.py +++ b/pretab/expansion/spline/cubic_regression.py @@ -1,4 +1,5 @@ import itertools +from typing import Any import numpy as np from sklearn.base import BaseEstimator, TransformerMixin @@ -10,6 +11,7 @@ from ...exceptions import InvalidParamError from ...placement.adapters import SplinePlacementAdapter from .mixins import SplineBasisMixin +from .penalty import PenaltySpec class CubicRegressionSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -276,6 +278,25 @@ def get_penalty_matrix(self, feature_index=0): P += (D * weights[:, None]).T @ D return P + def get_penalty_spec( + self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | None = None + ) -> PenaltySpec: + """Return the integrated squared curvature penalty in fitted output coordinates. + + The integral is over the fitted feature range, in fitted input units. + Its derivative order is two; ``diff_order`` must be omitted or ``None``. + The linear column and optional leading bias are unpenalized; the quadratic, + cubic, and truncated cubic columns contribute to the penalty. + """ + return self._curvature_penalty_spec( + feature_index, + diff_order, + legacy_method=CubicRegressionSplineTransformer.get_penalty_matrix, + kind="integrated_squared_second_derivative", + base_width=3, + integration="piecewise_simpson", + ) + def _second_derivative(self, x, basis_index, knots): """Second derivative of one basis column, evaluated at ``x``.""" poly_offset = 1 if self.include_bias else 0 diff --git a/pretab/expansion/spline/mixins.py b/pretab/expansion/spline/mixins.py index ddb7971..874a404 100644 --- a/pretab/expansion/spline/mixins.py +++ b/pretab/expansion/spline/mixins.py @@ -10,11 +10,16 @@ transformer only has to implement its own basis math. """ +from collections.abc import Callable +from typing import Any + import numpy as np from ...core.base import BasePreTabTransformer from ...core.knots import generate_internal_knots, select_knots, spanning_knots, supplement_interior_knots -from ...exceptions import IncompatibleParamsError, PretabDataError +from ...core.validation import resolve_input_features +from ...exceptions import IncompatibleParamsError, PretabDataError, PretabNotFittedError, invalid_param_error +from .penalty import PenaltySpec class SplineBasisMixin(BasePreTabTransformer): @@ -49,6 +54,62 @@ def _output_sizes(self) -> list[int]: """Number of output columns contributed by each input feature.""" return [int(n) for n in self.n_basis_] + def _curvature_penalty_spec( + self, + feature_index: int | np.integer[Any], + diff_order: int | None, + *, + legacy_method: Callable[..., object], + kind: str, + base_width: int, + integration: str, + ) -> PenaltySpec: + estimator = type(self).__name__ + knot_counts: list[int] | None = getattr(self, "n_knots_", None) + if knot_counts is None or len(self.n_basis_) != self.n_features_in_ or len(knot_counts) != len(self.n_basis_): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_spec().") + legacy_accessor = getattr(self, "get_penalty_matrix", None) + if not callable(legacy_accessor) or getattr(legacy_accessor, "__func__", None) is not legacy_method: + raise invalid_param_error( + estimator, "get_penalty_spec", None, "the matrix convention is overridden; use get_penalty_matrix()" + ) + if diff_order is not None: + raise invalid_param_error( + estimator, + "diff_order", + diff_order, + "omit for a fixed second-derivative penalty, not a difference penalty", + ) + sizes = self._output_sizes() + if ( + isinstance(feature_index, (bool, np.bool_)) + or not isinstance(feature_index, (int, np.integer)) + or not 0 <= feature_index < len(sizes) + ): + raise invalid_param_error(estimator, "feature_index", feature_index, f"must be in [0, {len(sizes)})") + include_bias = bool(getattr(self, "include_bias", False)) + if any( + width != knot_count + base_width + include_bias + for width, knot_count in zip(sizes, knot_counts, strict=True) + ): + raise invalid_param_error( + estimator, "include_bias", include_bias, "refit after changing the fitted basis width" + ) + + index = int(feature_index) + start = sum(sizes[:index]) + stop = start + sizes[index] + return PenaltySpec( + matrix=legacy_accessor(index), + kind=kind, + order=2, + axis=(str(resolve_input_features(self, None)[index]),), + coordinate_system="output_coefficients", + coefficient_names=tuple(self.get_feature_names_out()[start:stop]), + coefficient_indices=range(start, stop), + provenance={"transformer": estimator, "include_bias": include_bias, "integration": integration}, + ) + def _finite_column(self, x, y): """Drop NaN samples from one feature (aligning ``y``) before knot placement. diff --git a/pretab/expansion/spline/natural_cubic.py b/pretab/expansion/spline/natural_cubic.py index 4462b00..6f63460 100644 --- a/pretab/expansion/spline/natural_cubic.py +++ b/pretab/expansion/spline/natural_cubic.py @@ -1,3 +1,5 @@ +from typing import Any + import numpy as np from scipy.integrate import trapezoid from sklearn.base import BaseEstimator, TransformerMixin @@ -9,6 +11,7 @@ from ...exceptions import InvalidParamError from ...placement.adapters import SplinePlacementAdapter from .mixins import SplineBasisMixin +from .penalty import PenaltySpec class NaturalCubicSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -273,3 +276,22 @@ def get_penalty_matrix(self, feature_index=0): P[i, j] = trapezoid(integrand, x_grid) return P + + def get_penalty_spec( + self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | None = None + ) -> PenaltySpec: + """Return the legacy approximate curvature penalty in fitted output coordinates. + + The penalty uses numerical second derivatives and trapezoidal integration + on a 200-point grid over the fitted feature range, in fitted input units. + Its derivative order is two; ``diff_order`` must be omitted or ``None``. + The linear column and optional leading bias are unpenalized. + """ + return self._curvature_penalty_spec( + feature_index, + diff_order, + legacy_method=NaturalCubicSplineTransformer.get_penalty_matrix, + kind="approximate_integrated_squared_second_derivative", + base_width=1, + integration="finite_difference_trapezoid_200", + ) diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py index e70c566..08692db 100644 --- a/tests/expansion/spline/test_penalty_spec.py +++ b/tests/expansion/spline/test_penalty_spec.py @@ -11,7 +11,14 @@ from pretab import PenaltySpec from pretab.exceptions import InvalidParamError, PretabNotFittedError from pretab.expansion.spline import PenaltySpec as SplinePenaltySpec -from pretab.transformers import BSplineTransformer, ISplineTransformer, MSplineTransformer, PSplineTransformer +from pretab.transformers import ( + BSplineTransformer, + CubicRegressionSplineTransformer, + ISplineTransformer, + MSplineTransformer, + NaturalCubicSplineTransformer, + PSplineTransformer, +) def _spec(matrix, **overrides): @@ -335,3 +342,101 @@ def test_pspline_typed_penalty_refuses_state_after_failed_refit(): spline.fit(source) with pytest.raises(InvalidParamError, match="refit to record the fitted penalty order"): spline.get_penalty_spec() + + +@pytest.mark.parametrize("include_bias", [False, True]) +def test_natural_cubic_typed_penalty_matches_approximate_curvature_in_output_coordinates(include_bias): + source = np.linspace(-1, 2, 101) + frame = pd.DataFrame({"left": source, "right": source * 2 + 3}) + spline = NaturalCubicSplineTransformer(output_dim=5, include_bias=include_bias).fit(frame) + spec = spline.get_penalty_spec(1) + width = 5 + int(include_bias) + assert spec.kind == "approximate_integrated_squared_second_derivative" + assert spec.order == 2 + assert spec.axis == ("right",) + assert spec.coordinate_system == "output_coefficients" + assert spec.coefficient_indices == tuple(range(width, 2 * width)) + assert spec.coefficient_names == tuple(spline.get_feature_names_out()[width:]) + assert spline.transform(frame).shape[1] == 2 * width + np.testing.assert_array_equal(spec.matrix, spline.get_penalty_matrix(1)) + offset = 1 + int(include_bias) + np.testing.assert_array_equal(spec.matrix[:offset], 0) + assert (spec.rank, spec.nullity) == (4, offset) + + knots = spline.knots_[1] + grid = np.linspace(knots[0], knots[-1], 4001) + tails = np.maximum(grid[:, None] - knots, 0) + left_weights = (knots[-1] - knots[1:-1]) / (knots[-1] - knots[0]) + curvature = 6 * (tails[:, 1:-1] - left_weights * tails[:, :1]) + exact_gram = (curvature[:-1].T @ curvature[:-1] + curvature[1:].T @ curvature[1:]) * (grid[1] - grid[0]) / 2 + np.testing.assert_allclose(spec.matrix[offset:, offset:], exact_gram, rtol=0.02) + np.testing.assert_allclose(spec.matrix, 8 * spline.get_penalty_spec(0).matrix, atol=1e-8, rtol=1e-8) + + +@pytest.mark.parametrize("include_bias", [False, True]) +def test_cubic_regression_typed_penalty_matches_integrated_curvature_in_output_coordinates(include_bias): + source = np.linspace(-1, 2, 101) + frame = pd.DataFrame({"left": source, "right": source * 2 + 3}) + spline = CubicRegressionSplineTransformer(output_dim=5, include_bias=include_bias).fit(frame) + spec = spline.get_penalty_spec(np.int64(1)) + width = 5 + int(include_bias) + offset = 1 + int(include_bias) + assert spec.kind == "integrated_squared_second_derivative" + assert spec.order == 2 + assert spec.axis == ("right",) + assert spec.coordinate_system == "output_coefficients" + assert spec.coefficient_indices == tuple(range(width, 2 * width)) + assert spec.coefficient_names == tuple(spline.get_feature_names_out()[width:]) + assert spline.transform(frame).shape[1] == 2 * width + np.testing.assert_array_equal(spec.matrix, spline.get_penalty_matrix(1)) + np.testing.assert_array_equal(spec.matrix[:offset], 0) + assert (spec.rank, spec.nullity) == (4, offset) + + knots = spline.knots_[1] + bounds = np.r_[frame["right"].min(), knots, frame["right"].max()] + half_widths = np.diff(bounds) / 2 + midpoints = (bounds[1:] + bounds[:-1]) / 2 + nodes, weights = np.polynomial.legendre.leggauss(2) + grid = (midpoints[:, None] + half_widths[:, None] * nodes).ravel() + weights = (half_widths[:, None] * weights).ravel() + curvature = np.column_stack((np.full_like(grid, 2), 6 * grid, 6 * np.maximum(grid[:, None] - knots, 0))) + np.testing.assert_allclose(spec.matrix[offset:, offset:], curvature.T @ (weights[:, None] * curvature), rtol=1e-12) + assert spec.matrix[offset, offset] == pytest.approx(2 * spline.get_penalty_spec(0).matrix[offset, offset]) + + +@pytest.mark.parametrize("transformer_cls", [NaturalCubicSplineTransformer, CubicRegressionSplineTransformer]) +def test_curvature_typed_penalty_validation_and_legacy_access(transformer_cls): + spline = transformer_cls(output_dim=5) + with pytest.raises(PretabNotFittedError, match="must be fitted"): + spline.get_penalty_spec() + spline.fit(np.linspace(0, 1, 21).reshape(-1, 1)) + spec = spline.get_penalty_spec() + assert spec.axis == ("x0",) + with pytest.raises(ValueError): + spec.matrix.setflags(write=True) + legacy = spline.get_penalty_matrix(-1) + np.testing.assert_array_equal(spec.matrix, legacy) + with pytest.raises(InvalidParamError, match="feature_index"): + spline.get_penalty_spec(-1) + with pytest.raises(InvalidParamError, match="feature_index"): + spline.get_penalty_spec(True) + with pytest.raises(InvalidParamError, match="not a difference penalty"): + spline.get_penalty_spec(diff_order=2) + spline.set_params(include_bias=True) + with pytest.raises(InvalidParamError, match="refit"): + spline.get_penalty_spec() + + +@pytest.mark.parametrize("order", [1, 2]) +@pytest.mark.parametrize("include_bias", [False, True]) +def test_bspline_typed_difference_penalty_invariant_to_input_rescaling(order, include_bias): + source = np.linspace(-1, 2, 101).reshape(-1, 1) + spline = BSplineTransformer(output_dim=6, include_bias=include_bias).fit(source) + penalty = spline.get_penalty_spec(diff_order=order) + spline.fit(2 * source + 3) + assert spline.get_penalty_spec(diff_order=order) == penalty + assert penalty.kind == "coefficient_difference" + assert (penalty.rank, penalty.nullity) == (6 - order, order + int(include_bias)) + coefficients = np.arange(6 + int(include_bias), dtype=float) ** 2 + energy = np.sum(np.diff(coefficients[int(include_bias) :], n=order) ** 2) + assert coefficients @ penalty.matrix @ coefficients == energy From 74ba0a9e833ad423e57b74a0eae349fc02cad4ec Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 20 Nov 2026 15:47:27 +0100 Subject: [PATCH 49/86] feat(spline): expose typed tensor penaltie --- .../spline/multivariate/tensor_product.py | 64 ++++++++++++++++++- pretab/preprocessor.py | 8 +++ .../spline/test_penalty_matrix_invariants.py | 2 + tests/expansion/spline/test_penalty_spec.py | 64 +++++++++++++++++++ tests/integration/test_feature_groups.py | 29 +++++++++ 5 files changed, 166 insertions(+), 1 deletion(-) diff --git a/pretab/expansion/spline/multivariate/tensor_product.py b/pretab/expansion/spline/multivariate/tensor_product.py index 6e83586..5137dc8 100644 --- a/pretab/expansion/spline/multivariate/tensor_product.py +++ b/pretab/expansion/spline/multivariate/tensor_product.py @@ -6,8 +6,9 @@ from ....core.parameters import UNSET from ....core.policy import RepresentationPolicy, resolve_out_of_range from ....core.validation import resolve_input_features -from ....exceptions import InvalidParamError +from ....exceptions import InvalidParamError, PretabNotFittedError, invalid_param_error from ..mixins import SplineBasisMixin +from ..penalty import PenaltySpec class TensorProductSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -186,7 +187,11 @@ def _difference_penalty(self, n_basis): D = np.diff(D, n=1, axis=0) return D.T @ D + _penalty_source_axes_: tuple[str, ...] + def fit(self, X, y=None): + self.__dict__.pop("_penalty_fit_", None) + self.__dict__.pop("_penalty_source_axes_", None) X = self._validate_allow_nan(X, reset=True) output_dim = self._resolve_param("output_dim", default=4) if self.placement_strategy not in ("uniform", "quantile"): @@ -234,6 +239,7 @@ def fit(self, X, y=None): self.penalties_.append(penalty) self.n_knots_.append(max(0, len(knots) - 2 * (self.degree + 1))) + self._penalty_fit_ = (int(self.diff_order), bool(self.include_bias), int(self.degree)) return self def transform(self, X): @@ -326,3 +332,59 @@ def get_penalty_matrix(self, feature_index=0): """ check_is_fitted(self, "penalties_") return self.penalties_[feature_index] + + def get_penalty_specs(self) -> tuple[PenaltySpec, ...]: + """Return one full joint penalty per fitted source direction, in source order. + + Every matrix matches the corresponding entry in :meth:`get_penalty_matrices`. + Names and indices address this transformer's joint output in C order, + with the last input axis varying fastest. Bias, when enabled at fit, + belongs to each marginal basis, not to an extra joint intercept. + + Raises + ------ + PretabNotFittedError + If no fitted marginal penalties are available. + InvalidParamError + If the fitted convention is unavailable, the basis settings require + a refit, or a subclass overrides the joint matrix convention. + """ + estimator = type(self).__name__ + if not hasattr(self, "penalties_"): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_specs().") + fitted = getattr(self, "_penalty_fit_", None) + if fitted is None: + raise invalid_param_error(estimator, "get_penalty_specs", None, "refit to record the fitted penalty order") + order, include_bias, degree = fitted + if (bool(self.include_bias), self.degree) != (include_bias, degree): + raise invalid_param_error( + estimator, "get_penalty_specs", None, "refit after changing degree or include_bias" + ) + legacy_accessor = self.get_penalty_matrices + if getattr(legacy_accessor, "__func__", None) is not TensorProductSplineTransformer.get_penalty_matrices: + raise invalid_param_error( + estimator, "get_penalty_specs", None, "the matrix convention is overridden; use get_penalty_matrices()" + ) + + axes = getattr(self, "_penalty_source_axes_", None) + if axes is None: + axes = resolve_input_features(self, None) + names = tuple(self.get_feature_names_out()) + return tuple( + PenaltySpec( + matrix=matrix, + kind="coefficient_difference", + order=order, + axis=(str(axis),), + coordinate_system="output_coefficients", + coefficient_names=names, + coefficient_indices=range(len(names)), + provenance={ + "transformer": estimator, + "include_bias": include_bias, + "marginal_sizes": self.marginal_sizes_, + "flatten_order": "C", + }, + ) + for axis, matrix in zip(axes, legacy_accessor(), strict=True) + ) diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index a9caca3..cc94907 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -63,6 +63,7 @@ PretabSerializationError, invalid_param_error, ) +from .expansion.spline.multivariate.tensor_product import TensorProductSplineTransformer logger = get_logger(__name__) @@ -748,6 +749,13 @@ def fit(self, X, y=None, embeddings=None): self._enforce_output_budget(X.shape[0]) + if config.feature_groups: + for block in _iter_fitted_blocks(self.column_transformer_): + if block.group_id is not None: + leaf = representation_leaf(block.transformer) + if isinstance(leaf, TensorProductSplineTransformer): + leaf._penalty_source_axes_ = tuple(block.columns) + if verbose >= 1: numerical_summary = _method_summary(numerical_features, is_numerical=True, config=config) categorical_summary = _method_summary(categorical_features, is_numerical=False, config=config) diff --git a/tests/expansion/spline/test_penalty_matrix_invariants.py b/tests/expansion/spline/test_penalty_matrix_invariants.py index 38c9236..36647e2 100644 --- a/tests/expansion/spline/test_penalty_matrix_invariants.py +++ b/tests/expansion/spline/test_penalty_matrix_invariants.py @@ -82,6 +82,8 @@ def test_tensor_product_penalty_is_symmetric_psd(X_multi): def test_thinplate_penalty_is_symmetric_but_not_guaranteed_psd(): X = np.linspace(0, 1, 40).reshape(-1, 1) transformer = ThinPlateSplineTransformer(n_components=6, random_state=0).fit(X) + assert not hasattr(transformer, "get_penalty_spec") + assert not hasattr(transformer, "get_penalty_specs") with pytest.warns(ConfigWarning, match="experimental"): P = transformer.get_penalty_matrix() # PSD is explicitly not guaranteed here (see the class docstring); only symmetry is. diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py index 08692db..052a141 100644 --- a/tests/expansion/spline/test_penalty_spec.py +++ b/tests/expansion/spline/test_penalty_spec.py @@ -18,6 +18,7 @@ MSplineTransformer, NaturalCubicSplineTransformer, PSplineTransformer, + TensorProductSplineTransformer, ) @@ -440,3 +441,66 @@ def test_bspline_typed_difference_penalty_invariant_to_input_rescaling(order, in coefficients = np.arange(6 + int(include_bias), dtype=float) ** 2 energy = np.sum(np.diff(coefficients[int(include_bias) :], n=order) ** 2) assert coefficients @ penalty.matrix @ coefficients == energy + + +@pytest.mark.parametrize("axes", [("north", "east"), ("depth", "north", "east")]) +@pytest.mark.parametrize("include_bias", [False, True]) +@pytest.mark.parametrize("order", [1, 2]) +def test_tensor_typed_penalties_match_joint_directions(axes, include_bias, order): + source = np.linspace(0, 1, 31) + frame = pd.DataFrame({axis: source**power for power, axis in enumerate(axes, 1)}) + spline = TensorProductSplineTransformer(output_dim=3, degree=2, include_bias=include_bias, diff_order=order).fit( + frame + ) + specs = spline.get_penalty_specs() + legacy = spline.get_penalty_matrices() + bias = int(include_bias) + width = 3 + bias + sizes = (width,) * len(axes) + coefficients = np.random.default_rng(42).normal(size=sizes) + vector = coefficients.ravel() + names = tuple( + "tp_" + "_".join(f"{axis}{index}" for axis, index in zip(axes, indices, strict=True)) + for indices in np.ndindex(*sizes) + ) + assert tuple(spline.get_feature_names_out()) == names + assert spline.transform(frame).shape[1] == len(names) + assert isinstance(specs, tuple) + assert [spec.axis for spec in specs] == [(axis,) for axis in axes] + for direction, (spec, matrix) in enumerate(zip(specs, legacy, strict=True)): + np.testing.assert_array_equal(spec.matrix, matrix) + assert not spec.matrix.flags.writeable + assert (spec.kind, spec.order, spec.coordinate_system) == ( + "coefficient_difference", + order, + "output_coefficients", + ) + assert spec.coefficient_indices == tuple(range(len(names))) + assert spec.coefficient_names == names + assert spec.provenance["marginal_sizes"] == sizes + assert spec.provenance["include_bias"] is include_bias + assert spline.get_penalty_matrix(direction).shape == (width, width) + direction_coefficients = np.moveaxis(coefficients, direction, 0)[bias:] + energy = np.sum(np.diff(direction_coefficients, n=order, axis=0) ** 2) + assert vector @ spec.matrix @ vector == pytest.approx(energy) + repeats = width ** (len(axes) - 1) + assert (spec.rank, spec.nullity) == ((3 - order) * repeats, (order + bias) * repeats) + + +def test_tensor_typed_penalties_use_fit_settings_and_refuse_missing_metadata(): + spline = TensorProductSplineTransformer(diff_order=1) + with pytest.raises(PretabNotFittedError, match="must be fitted"): + spline.get_penalty_specs() + spline.fit(np.arange(32).reshape(-1, 2)) + expected = spline.get_penalty_specs() + assert [spec.axis for spec in expected] == [("x0",), ("x1",)] + spline.set_params(diff_order=2) + assert spline.get_penalty_specs() == expected + spline.set_params(include_bias=True) + with pytest.raises(InvalidParamError, match="refit after changing"): + spline.get_penalty_specs() + spline.set_params(include_bias=False) + del spline._penalty_fit_ + with pytest.raises(InvalidParamError, match="refit to record"): + spline.get_penalty_specs() + np.testing.assert_array_equal(spline.get_penalty_matrices()[0], expected[0].matrix) diff --git a/tests/integration/test_feature_groups.py b/tests/integration/test_feature_groups.py index 7ae096b..f495220 100644 --- a/tests/integration/test_feature_groups.py +++ b/tests/integration/test_feature_groups.py @@ -12,7 +12,9 @@ from sklearn.pipeline import Pipeline from pretab import FeatureGroup, FrozenRepresentationError, OutputBudgetError, Preprocessor, RepresentationConfig +from pretab.compose.inspection import representation_leaf from pretab.exceptions import DataWarning, PretabDataError +from pretab.transformers import TensorProductSplineTransformer @pytest.fixture @@ -58,6 +60,33 @@ def _dense(output): return output.toarray() if sparse.issparse(output) else np.asarray(output) +@pytest.mark.parametrize("columns", [("north", "east"), ("east", "north"), (20, 10)]) +def test_grouped_tensor_typed_penalties_follow_fitted_sources_and_exclude_indicators(frame, columns): + data = frame[["east", "north", "single"]].copy() + data.loc[0, "east"] = np.nan + data.loc[1, "north"] = np.nan + if isinstance(columns[0], int): + data = data.rename(columns={"north": 20, "east": 10}) + groups = {"location": {"columns": list(columns), "representation": _representation("tensorspline")}} + processor = _processor(groups).fit(data) + restored = Preprocessor.from_spec(json.loads(json.dumps(processor.to_spec(), allow_nan=False))) + expected = None + for fitted in (processor, restored): + leaf = representation_leaf(fitted.column_transformer_.named_transformers_["group_location"]) + assert isinstance(leaf, TensorProductSplineTransformer) + specs = leaf.get_penalty_specs() + assert [spec.axis for spec in specs] == [(str(column),) for column in columns] + assert all(spec.coefficient_names == tuple(leaf.get_feature_names_out()) for spec in specs) + assert all(spec.coefficient_indices == tuple(range(9)) and spec.matrix.shape == (9, 9) for spec in specs) + blocks = fitted.transform(data, return_array=False) + assert isinstance(blocks, dict) + assert blocks["group_location"].shape[1] == 11 + assert blocks["num_single"].shape[1] == 2 + if expected is not None: + assert specs == expected + expected = specs + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("mixed", [False, True], ids=["grouped-only", "mixed"]) @pytest.mark.parametrize("reverse", [False, True], ids=["forward", "reversed"]) From 0bf59726685e2df01d1840e761931654f1173e27 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 20 Nov 2026 18:36:58 +0100 Subject: [PATCH 50/86] feat(extension): check typed penalty capabilitie --- pretab/compose/registry.py | 10 +++ pretab/extension.py | 93 ++++++++++++++++++++- tests/extension/test_conformance.py | 81 +++++++++++++++++- tests/regression/_snapshots/public_api.json | 89 +++++++++++++------- 4 files changed, 239 insertions(+), 34 deletions(-) diff --git a/pretab/compose/registry.py b/pretab/compose/registry.py index 1433c97..812fa5c 100644 --- a/pretab/compose/registry.py +++ b/pretab/compose/registry.py @@ -135,6 +135,8 @@ class TransformerSpec: max_arity : int or None Maximum declared group size, or ``None`` for no declared upper bound. Relevant only when ``group_compatible`` is true. + typed_penalty : bool + Whether the method exposes validated penalty metadata aligned to its output. """ name: str @@ -152,6 +154,7 @@ class TransformerSpec: group_compatible: bool = False min_arity: int = 1 max_arity: int | None = 1 + typed_penalty: bool = False @property def is_numerical(self) -> bool: @@ -276,12 +279,14 @@ def _spec(name, cls, allowed_args=(), **kwargs): "max_output_dim", "random_state", ), + typed_penalty=True, **_BOTH_MODE, ), _spec( "naturalspline", NaturalCubicSplineTransformer, ("output_dim", "include_bias", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), # --- numerical: penalized splines (equally-spaced knots, unsupervised only) --- @@ -290,6 +295,7 @@ def _spec(name, cls, allowed_args=(), **kwargs): PSplineTransformer, ("output_dim", "degree", "diff_order"), placement_strategies=_UNIFORM_ONLY, + typed_penalty=True, ), _spec( "tensorspline", @@ -301,6 +307,7 @@ def _spec(name, cls, allowed_args=(), **kwargs): group_compatible=True, min_arity=2, max_arity=None, + typed_penalty=True, ), # --- numerical: kernel-based thin-plate spline (knot-free, multivariate) --- _spec( @@ -333,18 +340,21 @@ def _spec(name, cls, allowed_args=(), **kwargs): "bspline", BSplineTransformer, ("degree", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), _spec( "mspline", MSplineTransformer, ("degree", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), _spec( "ispline", ISplineTransformer, ("degree", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), # --- numerical / categorical: passthrough --- diff --git a/pretab/extension.py b/pretab/extension.py index 4e60bcd..cad72cb 100644 --- a/pretab/extension.py +++ b/pretab/extension.py @@ -21,6 +21,7 @@ import inspect import warnings +from collections.abc import Iterable import numpy as np from sklearn.base import clone @@ -35,7 +36,9 @@ ) from .core.base import BasePreTabTransformer from .core.representation import RepresentationSpec -from .exceptions import ConfigWarning, RepresentationConformanceError +from .core.validation import resolve_input_features +from .exceptions import ConfigWarning, PretabNotFittedError, RepresentationConformanceError +from .expansion.spline.penalty import PenaltySpec __all__ = [ "BaseRepresentation", @@ -136,6 +139,7 @@ def register_representation( periodic=False, sparse_output=False, override=False, + typed_penalty=False, ): """Register a representation class under ``name`` so it is selectable by name. @@ -186,6 +190,8 @@ class without one raises ``TypeError``. For a class without a Whether the method can emit a sparse matrix. override : bool, default=False Whether replacing an already-registered ``name`` is allowed. + typed_penalty : bool, default=False + Opt in to the typed penalty contract checked by :func:`check_representation`. Returns ------- @@ -228,6 +234,7 @@ class without one raises ``TypeError``. For a class without a optional_dependency=optional_dependency, periodic=bool(periodic), sparse_output=bool(sparse_output), + typed_penalty=bool(typed_penalty), ) return register_spec(spec, override=override) @@ -333,6 +340,71 @@ def _densify(array): return np.asarray(array) +def _check_typed_penalty(fitted, unfitted, *, joint, names): + typed_name, legacy_name = ( + ("get_penalty_specs", "get_penalty_matrices") if joint else ("get_penalty_spec", "get_penalty_matrix") + ) + label = f"{type(fitted).__name__}.{typed_name}" + typed_accessor = getattr(fitted, typed_name, None) + legacy_accessor = getattr(fitted, legacy_name, None) + if not callable(typed_accessor) or not callable(legacy_accessor): + raise RepresentationConformanceError(f"{label} and {legacy_name} are required by typed_penalty") + try: + getattr(unfitted, typed_name)() + except PretabNotFittedError: + pass + except Exception as exc: + raise RepresentationConformanceError(f"{label} before fit must raise PretabNotFittedError") from exc + else: + raise RepresentationConformanceError(f"{label} before fit must raise PretabNotFittedError") + + axes = tuple(str(axis) for axis in resolve_input_features(fitted, None)) + try: + if joint: + penalties = typed_accessor() + matrices = legacy_accessor() + if not isinstance(matrices, Iterable): + raise TypeError(f"{legacy_name} must return an iterable of matrices") + legacy = tuple(matrices) + else: + penalties = tuple(typed_accessor(feature_index=index) for index in range(len(axes))) + legacy = tuple(legacy_accessor(feature_index=index) for index in range(len(axes))) + except Exception as exc: + raise RepresentationConformanceError(f"{label} failed on fitted data: {exc}") from exc + if not isinstance(penalties, tuple) or len(penalties) != len(axes) or len(legacy) != len(axes): + raise RepresentationConformanceError(f"{label} must provide one PenaltySpec and legacy matrix per fitted axis") + + output_indices = tuple(range(len(names))) + covered_indices = [] + for axis, penalty, reference in zip(axes, penalties, legacy, strict=True): + if not isinstance(penalty, PenaltySpec): + raise RepresentationConformanceError(f"{label} must return PenaltySpec values") + if penalty.axis != (axis,) or penalty.coordinate_system != "output_coefficients": + raise RepresentationConformanceError(f"{label} must identify fitted axis {axis!r} in output coefficients") + indices = penalty.coefficient_indices + if ( + (joint and indices != output_indices) + or any(index >= len(names) for index in indices) + or penalty.coefficient_names != tuple(names[index] for index in indices) + ): + raise RepresentationConformanceError(f"{label} coefficient names and indices must match fitted output") + matrix = penalty.matrix + if not np.array_equal(matrix, reference): + raise RepresentationConformanceError(f"{label} matrix must match {legacy_name}") + if matrix.flags.writeable or np.shares_memory(matrix, reference): + raise RepresentationConformanceError(f"{label} matrix must be read-only and detached from {legacy_name}") + try: + matrix.setflags(write=True) + except ValueError: + pass + else: + matrix.setflags(write=False) + raise RepresentationConformanceError(f"{label} matrix must not allow writes to be re-enabled") + covered_indices.extend(indices) + if not joint and tuple(covered_indices) != output_indices: + raise RepresentationConformanceError(f"{label} must cover consecutive feature blocks in fitted output order") + + def check_representation(cls, *, X=None, y=None): """Run the representation conformance suite on a class. @@ -343,6 +415,9 @@ def check_representation(cls, *, X=None, y=None): width and is unique; the result is deterministic across ``clone`` + refit; the typed :class:`~pretab.RepresentationSpec` agrees with the declared ``scope`` and output width; and a ``"supervised"`` class refuses to fit without ``y``. + A registered ``typed_penalty`` claim additionally checks penalty access + before fit and validates fitted axes, output coordinates, and legacy matrix + parity. Parameters ---------- @@ -365,8 +440,14 @@ class declares ``supervision="supervised"``. On the first failed check, with a message identifying the violation. """ rng = np.random.RandomState(0) + penalty_scopes = { + spec.arity for spec in TRANSFORMER_REGISTRY.values() if spec.transformer_cls is cls and spec.typed_penalty + } + if len(penalty_scopes) > 1: + raise RepresentationConformanceError(f"{cls.__name__} has conflicting typed_penalty scopes") + penalty_scope = next(iter(penalty_scopes), None) if X is None: - X = rng.uniform(-2.0, 2.0, size=(40, 1)).astype(float) + X = rng.uniform(-2.0, 2.0, size=(40, 2 if penalty_scope == "multivariate" else 1)).astype(float) X = np.asarray(X) n_samples = X.shape[0] @@ -442,7 +523,7 @@ def _fit(est): spec = fitted.get_representation_spec() if not isinstance(spec, RepresentationSpec): raise RepresentationConformanceError(f"{cls.__name__}.get_representation_spec must return a RepresentationSpec") - declared_scope = getattr(cls, "scope", "univariate") + declared_scope = getattr(cls, "scope", penalty_scope or "univariate") if spec.scope != declared_scope: raise RepresentationConformanceError( f"{cls.__name__} spec.scope {spec.scope!r} != declared scope {declared_scope!r}" @@ -453,6 +534,12 @@ def _fit(est): ) passed.append("spec_consistent") + if penalty_scope is not None: + if spec.scope != penalty_scope: + raise RepresentationConformanceError(f"{cls.__name__} spec.scope must match its typed_penalty scope") + _check_typed_penalty(fitted, _make(), joint=penalty_scope == "multivariate", names=names) + passed.append("typed_penalty_consistent") + # 7. a supervised class must refuse to fit without y. if needs_y: est = _make() diff --git a/tests/extension/test_conformance.py b/tests/extension/test_conformance.py index 84aeba8..71cb99d 100644 --- a/tests/extension/test_conformance.py +++ b/tests/extension/test_conformance.py @@ -4,8 +4,10 @@ import pytest from sklearn.utils.validation import check_is_fitted -from pretab import BaseRepresentation, check_representation +from pretab import BaseRepresentation, PenaltySpec, check_representation, register_representation +from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.exceptions import RepresentationConformanceError +from pretab.transformers import BSplineTransformer class _Good(BaseRepresentation): @@ -56,6 +58,83 @@ def test_good_supervised_representation_passes(): assert "supervised_requires_y" in passed +_TYPED_PENALTY_METHODS = ("bspline", "cubicspline", "ispline", "mspline", "naturalspline", "pspline", "tensorspline") + + +def test_typed_penalty_registry_is_explicit(): + actual = {name for name, spec in TRANSFORMER_REGISTRY.items() if spec.typed_penalty} + assert actual == set(_TYPED_PENALTY_METHODS) + assert not TRANSFORMER_REGISTRY["tprs"].typed_penalty + + +@pytest.mark.parametrize("name", _TYPED_PENALTY_METHODS) +def test_typed_penalty_builtin_conformance(name): + spec = TRANSFORMER_REGISTRY[name] + assert "typed_penalty_consistent" in check_representation(spec.transformer_cls) + if spec.arity == "univariate": + source = np.linspace(-1, 1, 40) + X = np.column_stack((source, 2 * source + 1)) + assert "typed_penalty_consistent" in check_representation(spec.transformer_cls, X=X) + + +def test_legacy_matrix_does_not_opt_in_to_typed_penalties(): + class _LegacyOnly(_Good): + def get_penalty_matrix(self, feature_index=0): + return np.eye(1) + + record = register_representation("legacy_only", _LegacyOnly) + assert not record.typed_penalty + assert "typed_penalty_consistent" not in check_representation(_LegacyOnly) + register_representation("legacy_only", _LegacyOnly, override=True, typed_penalty=True) + with pytest.raises(RepresentationConformanceError, match=r"get_penalty_spec.*required by typed_penalty"): + check_representation(_LegacyOnly) + + +def test_multivariate_claim_requires_the_plural_accessor(): + class _MarginalOnly(_Good): + scope = "multivariate" + + def get_penalty_spec(self, feature_index=0): + raise AssertionError("must not try to qualify a marginal penalty") + + def get_penalty_matrix(self, feature_index=0): + return np.eye(1) + + register_representation("marginal_only", _MarginalOnly, typed_penalty=True) + with pytest.raises(RepresentationConformanceError, match=r"get_penalty_specs.*required by typed_penalty"): + check_representation(_MarginalOnly) + + +@pytest.mark.parametrize( + ("fault", "message"), + [ + ("unfitted", "before fit must raise PretabNotFittedError"), + ("axis", "must identify fitted axis"), + ("names", "coefficient names and indices must match fitted output"), + ("matrix", "matrix must match get_penalty_matrix"), + ], +) +def test_typed_penalty_conformance_rejects_mismatched_metadata(fault, message): + class _IncorrectPenalty(BSplineTransformer): + def get_penalty_spec(self, feature_index=0, *, diff_order=None): + if fault == "unfitted" and not hasattr(self, "n_basis_"): + raise ValueError("unexpected unfitted error") + penalty = super().get_penalty_spec(feature_index, diff_order=diff_order) + return PenaltySpec( + matrix=2 * penalty.matrix if fault == "matrix" else penalty.matrix, + kind=penalty.kind, + order=penalty.order, + axis=("wrong",) if fault == "axis" else penalty.axis, + coordinate_system=penalty.coordinate_system, + coefficient_names=penalty.coefficient_names[::-1] if fault == "names" else penalty.coefficient_names, + coefficient_indices=penalty.coefficient_indices, + ) + + register_representation("incorrect_penalty", _IncorrectPenalty, typed_penalty=True) + with pytest.raises(RepresentationConformanceError, match=message): + check_representation(_IncorrectPenalty) + + def test_fit_not_returning_self_fails(): class _NoSelf(BaseRepresentation): representation_name = "noself_conf" diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index 6f56d88..bcbbc7d 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -254,7 +254,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._data.PowerTransformer" + "transformer_cls": "sklearn.preprocessing._data.PowerTransformer", + "typed_penalty": false }, "bspline": { "allowed_args": [ @@ -287,7 +288,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.spline.b_spline.BSplineTransformer" + "transformer_cls": "pretab.expansion.spline.b_spline.BSplineTransformer", + "typed_penalty": true }, "cubicspline": { "allowed_args": [ @@ -322,7 +324,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.spline.cubic_regression.CubicRegressionSplineTransformer" + "transformer_cls": "pretab.expansion.spline.cubic_regression.CubicRegressionSplineTransformer", + "typed_penalty": true }, "custombin": { "allowed_args": ["output_dim", "encode"], @@ -348,7 +351,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.encoding.numerical.binning.NumericBinningTransformer" + "transformer_cls": "pretab.encoding.numerical.binning.NumericBinningTransformer", + "typed_penalty": false }, "fourier": { "allowed_args": [ @@ -379,7 +383,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.expansion.functional.fourier.FourierFeatureTransformer" + "transformer_cls": "pretab.expansion.functional.fourier.FourierFeatureTransformer", + "typed_penalty": false }, "int": { "allowed_args": [], @@ -405,7 +410,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.encoding.categorical.ordinal.ContinuousOrdinalTransformer" + "transformer_cls": "pretab.encoding.categorical.ordinal.ContinuousOrdinalTransformer", + "typed_penalty": false }, "ispline": { "allowed_args": [ @@ -438,7 +444,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.spline.i_spline.ISplineTransformer" + "transformer_cls": "pretab.expansion.spline.i_spline.ISplineTransformer", + "typed_penalty": true }, "minmax": { "allowed_args": [], @@ -464,7 +471,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._data.MinMaxScaler" + "transformer_cls": "sklearn.preprocessing._data.MinMaxScaler", + "typed_penalty": false }, "mspline": { "allowed_args": [ @@ -497,7 +505,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.spline.m_spline.MSplineTransformer" + "transformer_cls": "pretab.expansion.spline.m_spline.MSplineTransformer", + "typed_penalty": true }, "naturalspline": { "allowed_args": [ @@ -531,7 +540,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.spline.natural_cubic.NaturalCubicSplineTransformer" + "transformer_cls": "pretab.expansion.spline.natural_cubic.NaturalCubicSplineTransformer", + "typed_penalty": true }, "none": { "allowed_args": [], @@ -557,7 +567,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.preprocessing.floats.NoTransformer" + "transformer_cls": "pretab.preprocessing.floats.NoTransformer", + "typed_penalty": false }, "nystroem": { "allowed_args": [ @@ -590,7 +601,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.kernel_approximation.nystroem.NystroemFeaturesTransformer" + "transformer_cls": "pretab.kernel_approximation.nystroem.NystroemFeaturesTransformer", + "typed_penalty": false }, "one-hot": { "allowed_args": [ @@ -625,7 +637,8 @@ "sparse_output": true, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._encoders.OneHotEncoder" + "transformer_cls": "sklearn.preprocessing._encoders.OneHotEncoder", + "typed_penalty": false }, "onehot_from_ordinal": { "allowed_args": [], @@ -651,7 +664,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.encoding.categorical.one_hot.OneHotFromOrdinalTransformer" + "transformer_cls": "pretab.encoding.categorical.one_hot.OneHotFromOrdinalTransformer", + "typed_penalty": false }, "ple": { "allowed_args": [ @@ -684,7 +698,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "required", - "transformer_cls": "pretab.encoding.numerical.ple.PLETransformer" + "transformer_cls": "pretab.encoding.numerical.ple.PLETransformer", + "typed_penalty": false }, "polynomial": { "allowed_args": ["degree", "interaction_only", "include_bias"], @@ -710,7 +725,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._polynomial.PolynomialFeatures" + "transformer_cls": "sklearn.preprocessing._polynomial.PolynomialFeatures", + "typed_penalty": false }, "pretrained": { "allowed_args": [], @@ -736,7 +752,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.embedding.language.LanguageEmbeddingTransformer" + "transformer_cls": "pretab.embedding.language.LanguageEmbeddingTransformer", + "typed_penalty": false }, "pspline": { "allowed_args": ["output_dim", "degree", "diff_order"], @@ -762,7 +779,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.expansion.spline.p_spline.PSplineTransformer" + "transformer_cls": "pretab.expansion.spline.p_spline.PSplineTransformer", + "typed_penalty": true }, "quantile": { "allowed_args": ["n_quantiles", "output_distribution", "random_state"], @@ -788,7 +806,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._data.QuantileTransformer" + "transformer_cls": "sklearn.preprocessing._data.QuantileTransformer", + "typed_penalty": false }, "rbf": { "allowed_args": [ @@ -822,7 +841,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.functional.rbf.RBFExpansionTransformer" + "transformer_cls": "pretab.expansion.functional.rbf.RBFExpansionTransformer", + "typed_penalty": false }, "relu": { "allowed_args": [ @@ -855,7 +875,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.functional.relu.ReLUExpansionTransformer" + "transformer_cls": "pretab.expansion.functional.relu.ReLUExpansionTransformer", + "typed_penalty": false }, "rff": { "allowed_args": ["n_components", "gamma", "random_state"], @@ -881,7 +902,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.kernel_approximation.random_fourier.RandomFourierFeaturesTransformer" + "transformer_cls": "pretab.kernel_approximation.random_fourier.RandomFourierFeaturesTransformer", + "typed_penalty": false }, "robust": { "allowed_args": [], @@ -907,7 +929,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._data.RobustScaler" + "transformer_cls": "sklearn.preprocessing._data.RobustScaler", + "typed_penalty": false }, "sigmoid": { "allowed_args": [ @@ -940,7 +963,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.functional.sigmoid.SigmoidExpansionTransformer" + "transformer_cls": "pretab.expansion.functional.sigmoid.SigmoidExpansionTransformer", + "typed_penalty": false }, "standardization": { "allowed_args": [], @@ -966,7 +990,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._data.StandardScaler" + "transformer_cls": "sklearn.preprocessing._data.StandardScaler", + "typed_penalty": false }, "tanh": { "allowed_args": [ @@ -1000,7 +1025,8 @@ "sparse_output": false, "supports_adaptive_resolution": true, "target_usage": "optional", - "transformer_cls": "pretab.expansion.functional.tanh.TanhExpansionTransformer" + "transformer_cls": "pretab.expansion.functional.tanh.TanhExpansionTransformer", + "typed_penalty": false }, "tensorspline": { "allowed_args": ["output_dim", "degree", "diff_order"], @@ -1026,7 +1052,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.expansion.spline.multivariate.tensor_product.TensorProductSplineTransformer" + "transformer_cls": "pretab.expansion.spline.multivariate.tensor_product.TensorProductSplineTransformer", + "typed_penalty": true }, "tprs": { "allowed_args": [ @@ -1057,7 +1084,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "pretab.expansion.spline.multivariate.thin_plate.ThinPlateSplineTransformer" + "transformer_cls": "pretab.expansion.spline.multivariate.thin_plate.ThinPlateSplineTransformer", + "typed_penalty": false }, "yeo-johnson": { "allowed_args": [], @@ -1083,7 +1111,8 @@ "sparse_output": false, "supports_adaptive_resolution": false, "target_usage": "forbidden", - "transformer_cls": "sklearn.preprocessing._data.PowerTransformer" + "transformer_cls": "sklearn.preprocessing._data.PowerTransformer", + "typed_penalty": false } }, "selectable_methods": { @@ -1133,7 +1162,7 @@ "pretab.configure_logging": "(level: int = 1, handler: 'logging.Handler | None' = None) -> None", "pretab.list_representations": "(*, feature_kind=None, scope=None, supervised=None, periodic=None, sparse_output=None, adaptive=None, include_optional=True)", "pretab.load_entry_point_representations": "(group='pretab.representations', *, override=False)", - "pretab.register_representation": "(name, cls, *, feature_kind=None, scope=None, supervision=None, allowed_args=(), placement_strategies=(), supports_adaptive_resolution=False, preprocessor_compatible=True, optional_dependency=None, periodic=False, sparse_output=False, override=False)", + "pretab.register_representation": "(name, cls, *, feature_kind=None, scope=None, supervision=None, allowed_args=(), placement_strategies=(), supports_adaptive_resolution=False, preprocessor_compatible=True, optional_dependency=None, periodic=False, sparse_output=False, override=False, typed_penalty=False)", "pretab.set_verbosity": "(level: int = 1) -> None", "pretab.transformers.BSplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", "pretab.transformers.ContinuousOrdinalTransformer": "()", From 3212f363c4e5981078c9e8c0461c03d6b6725ce2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Fri, 20 Nov 2026 18:57:49 +0100 Subject: [PATCH 51/86] feat(spline): add checksummed penalty summaries --- pretab/expansion/spline/penalty.py | 33 ++++++++++ tests/expansion/spline/test_penalty_spec.py | 72 +++++++++++++++++++++ 2 files changed, 105 insertions(+) diff --git a/pretab/expansion/spline/penalty.py b/pretab/expansion/spline/penalty.py index a7a656f..c4a6111 100644 --- a/pretab/expansion/spline/penalty.py +++ b/pretab/expansion/spline/penalty.py @@ -4,8 +4,10 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass, field +from hashlib import sha256 from math import isfinite from numbers import Integral, Real +from struct import pack from types import MappingProxyType from typing import Any @@ -188,6 +190,37 @@ def matrix(self) -> NDArray[np.float64]: width = len(self.coefficient_indices) return np.frombuffer(self._matrix_bytes, dtype=np.float64).reshape(width, width) + def to_summary(self) -> dict[str, Any]: + """Return detached JSON metadata without the dense matrix. + + ``matrix_sha256`` is the hexadecimal SHA-256 digest of the row and + column counts (two unsigned 64-bit little-endian integers), followed + by C-order little-endian float64 matrix bytes. The checksum treats + negative zero as positive zero and does not round any other values. + It identifies exact matrix content, not tolerance-based equivalence. + The summary cannot reconstruct the matrix. + """ + matrix = np.array(self.matrix, dtype=" bool: if not isinstance(other, PenaltySpec): return NotImplemented diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py index 052a141..ae34d10 100644 --- a/tests/expansion/spline/test_penalty_spec.py +++ b/tests/expansion/spline/test_penalty_spec.py @@ -1,8 +1,11 @@ """Value and validation contracts for coefficient-coordinate penalties.""" +import json import pickle from copy import copy, deepcopy from dataclasses import FrozenInstanceError +from hashlib import sha256 +from struct import pack import numpy as np import pandas as pd @@ -34,6 +37,74 @@ def _spec(matrix, **overrides): return PenaltySpec(matrix, **(settings | overrides)) +def test_penalty_summary_has_complete_strict_json_metadata_and_canonical_digest(): + spec = _spec([[2.0, 0.0], [0.0, 0.0]], provenance={"options": [{"bias": False}], "note": None}) + canonical = bytes.fromhex( + "0200000000000000 0200000000000000 0000000000000040 0000000000000000 0000000000000000 0000000000000000" + ) + summary = spec.to_summary() + assert ( + summary + == json.loads(json.dumps(summary, allow_nan=False)) + == { + "shape": [2, 2], + "dtype": "float64", + "kind": "coefficient_difference", + "order": 1, + "axis": ["age"], + "coordinate_system": "output_coefficients", + "coefficient_names": ["age_0", "age_1"], + "coefficient_indices": [2, 3], + "rank": 1, + "nullity": 1, + "atol": 1e-10, + "rtol": 1e-10, + "provenance": {"options": [{"bias": False}], "note": None}, + "matrix_sha256": sha256(canonical).hexdigest(), + } + ) + + +@pytest.mark.parametrize("dtype", ["f8"]) +@pytest.mark.parametrize("layout", ["C", "F", "strided"]) +def test_penalty_summary_checksum_is_independent_of_input_byte_order_and_layout(dtype, layout): + values = [[2.0, -0.5], [np.nextafter(-0.5, 0), 1.0]] + if layout == "strided": + matrix = np.zeros((4, 4), dtype=dtype)[::2, ::2] + matrix[:] = values + else: + matrix = np.array(values, dtype=dtype, order=layout) + canonical = pack(" Date: Sat, 21 Nov 2026 06:42:42 +0100 Subject: [PATCH 52/86] docs(spline): document typed penalty conventions --- docs/api/representations.rst | 9 ++ docs/representations/spline_expansions.md | 116 +++++++++++++++++++--- 2 files changed, 113 insertions(+), 12 deletions(-) diff --git a/docs/api/representations.rst b/docs/api/representations.rst index 2b7f8b6..42ac46d 100644 --- a/docs/api/representations.rst +++ b/docs/api/representations.rst @@ -35,6 +35,15 @@ Multivariate splines Canonical import: ``pretab.expansion.spline.multivariate``. +Typed spline penalties +---------------------- + +.. autoclass:: pretab.PenaltySpec + :members: matrix, to_summary + +The :doc:`spline guide <../representations/spline_expansions>` lists the supported +accessors and shows how to add a penalty to a downstream loss. + Functional expansions ---------------------- diff --git a/docs/representations/spline_expansions.md b/docs/representations/spline_expansions.md index a487a78..4129dcc 100644 --- a/docs/representations/spline_expansions.md +++ b/docs/representations/spline_expansions.md @@ -83,13 +83,10 @@ Increase `output_dim` for more wiggle, decrease it to regularize. ``` ```{note} -Every spline in this family exposes `get_penalty_matrix(feature_index=0, diff_order=2)`, a -`D^T D` second-difference penalty matrix of shape `(m, m)`, where `m` is the fitted non-bias -width (plus the bias -row/column left unpenalized when `include_bias=True`). It is not limited to the "penalized" -splines further down this page. Note that `diff_order` is specific to this B/M/I family; the -cubic, natural cubic, P-spline, tensor-product, and thin-plate variants expose -`get_penalty_matrix(feature_index=0)` with their own fixed penalty construction instead. +The B/M/I family exposes `get_penalty_matrix(feature_index=0, diff_order=2)` and +the corresponding typed `get_penalty_spec()`. The returned matrix covers the +fitted output width, including a zero row and column for the leading bias if present. +See [Typed spline penalties](#typed-spline-penalties) for the other families. ``` ## M-spline and I-spline @@ -186,9 +183,9 @@ $$ \lambda\, \beta^\top D^\top D\, \beta, $$ -where $D$ is the `diff_order`-th order difference operator (the same matrix returned by -`get_penalty_matrix()`) and $\lambda$ is chosen by the downstream penalized model, not by -`PSplineTransformer` itself. +where $D$ is the `diff_order`-th order difference operator. `get_penalty_matrix()` +returns $D^\top D$, padded for the optional unpenalized bias. The downstream model, +not `PSplineTransformer`, chooses $\lambda$ and adds the penalty to its loss. ```python import numpy as np @@ -231,8 +228,9 @@ $$ \Phi_{k_1, \dots, k_d}(x_1, \dots, x_d) = \prod_{j=1}^{d} B_{k_j}(x_j). $$ -It exposes an anisotropic penalty per marginal via -`get_penalty_matrix(feature_index=...)`. +`get_penalty_matrix(feature_index=...)` returns a marginal matrix. +`get_penalty_specs()` returns one full joint matrix per source direction, ready +to apply to the coefficients of the tensor basis. ```python import numpy as np @@ -294,6 +292,100 @@ The [multivariate tutorial](../tutorials/multivariate_features.md) shows how to configure groups and inspect the actual width rather than assigning it to each source. ``` +## Typed spline penalties + +Fit the spline first, then call its typed accessor. Each {py:class}`pretab.PenaltySpec` +pairs a penalty matrix with the ordered `coefficient_names` and zero-based +`coefficient_indices` of the fitted transformer's output. `axis` identifies the +input direction. It does not index the coefficients. The legacy matrix accessors +remain available, and neither accessor changes the fitted basis or trains a model. + +| Spline family | Typed accessor | Matrix convention | +| ---------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| B-spline, M-spline, I-spline | `get_penalty_spec(feature_index=0, diff_order=None)` | Coefficient differences. Defaults to order 2; the accessor accepts an explicit order. | +| P-spline | `get_penalty_spec(feature_index=0)` | Coefficient differences of fitted order 1 or 2. Higher orders remain available through the legacy accessor. | +| Natural cubic | `get_penalty_spec(feature_index=0)` | Approximate integrated squared second derivative, using finite differences and trapezoidal integration. | +| Cubic regression | `get_penalty_spec(feature_index=0)` | Integrated squared second derivative, using piecewise Simpson integration, exact in exact arithmetic. | +| Tensor-product | `get_penalty_specs()` | One full joint coefficient-difference matrix per fitted axis, using the fitted order. | +| Thin-plate | None | Experimental legacy matrix only; positive semidefiniteness is not guaranteed. | + +For $m$ selected coefficients, `matrix` is a detached, read-only `float64` +array of shape $(m, m)$. Let $P$ denote that matrix and $\beta$ the coefficient +vector in the recorded order. The unweighted penalty is $\beta^\top P\beta$, +with no implicit factor of $1/2$. Symmetry, positive semidefiniteness and +numerical rank use the recorded tolerance `atol + rtol * spectral_norm`, where +the norm is of the symmetric part of $P$. Eigenvalues above that threshold +count toward `rank`; `nullity` is $m$ minus `rank`. Accepted entries are not +rounded, clipped, or symmetrized. A penalty can be singular without being invalid. + +For coefficient differences, $P = D^\top D$ and the penalty is +$\lVert D\beta\rVert_2^2$. A difference penalty of order $r$ on $q$ non-bias +coefficients has rank $q-r$ and nullity $r$ when $1 \le r < q$; a leading +bias is unpenalized and adds one null direction. Differences operate on the +ordered coefficients, not derivatives in input units. The two curvature +penalties instead integrate over their fitted input domains. The linear term +and any explicit bias have zero curvature. Scaling inputs before fitting can +change these curvature matrices, even if the output width stays the same. + +The tensor matrices share the full joint coefficient order (C order, with the +last declared axis varying fastest). Each direction applies a marginal +difference operator along its axis, holding the others fixed. With marginal +bias enabled, that direction leaves its own bias index unpenalized; other +directions may still penalize such terms. Apply the matrices to the same +joint coefficients and add their quadratic forms with nonnegative weights +$\lambda_j$. Do not substitute marginal matrices or add matrices defined in +different coefficient coordinates without first aligning them. + +### Fit with a quadratic penalty + +This example fits a P-spline basis, then uses its penalty in a least-squares +model. Because the example uses the **sum** of squared residuals, the normal +equations add $\lambda P$ to the design's Gram matrix. A mean-reduced loss uses +a different effective weight, so choose the weight for your loss convention. + +```python +import numpy as np +from pretab.transformers import PSplineTransformer + +source = np.linspace(0.0, 1.0, 80) +features = source.reshape(-1, 1) +target = np.sin(2.0 * np.pi * source) +spline = PSplineTransformer(output_dim=6, diff_order=2, include_bias=False).fit(features) +penalty = spline.get_penalty_spec() +indices = np.asarray(penalty.coefficient_indices) +assert tuple(spline.get_feature_names_out()[indices]) == penalty.coefficient_names +design = spline.transform(features)[:, indices] + +weight = 0.1 +matrix = penalty.matrix +coefficients = np.linalg.solve(design.T @ design + weight * matrix, design.T @ target) +residuals = design @ coefficients - target +roughness = coefficients @ matrix @ coefficients +loss = residuals @ residuals + weight * roughness + +assert np.isfinite(loss) +np.testing.assert_allclose(roughness, np.sum(np.diff(coefficients, n=2) ** 2)) +``` + +### Use in DeepTab and other estimators + +Apply the quadratic form to the downstream weights that multiply the spline +basis columns directly, not to the input values or activations. `coefficient_indices` +are local to the fitted transformer's output. In a combined model input, use the +fitted block layout and output lineage to find the corresponding columns. For +a tensor group, keep the full joint basis in one block; do not split the penalty +by source or include raw missing indicators in it. The +[multivariate tutorial](../tutorials/multivariate_features.md) shows how to +inspect that fitted layout. This is consumer guidance, not a DeepTab configuration API. + +For a tensor-based training loop, copy the read-only array to a fixed tensor +on the coefficients' device and dtype. If you have several coefficient vectors +for the same basis (for example, several output units), compute the form for each +vector and reduce the results consistently with your task loss. Recheck the +alignment after refitting or changing the design. `to_summary()` can log the +convention, coordinates, numerical rank and matrix checksum without including +the matrix. It is not a way to restore the matrix or train from the summary alone. + ## Where to go next - [Functional expansions](functional_expansions.md) for non-spline bases. From 2edaf48515ce34a1eced489413a12dec694f8e43 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 06:43:12 +0100 Subject: [PATCH 53/86] fix: splines penalty tests --- tests/doc_snippets/test_tutorial_snippets.py | 5 ++++ .../spline/test_penalty_matrix_invariants.py | 24 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index 87480ff..6298ace 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -79,6 +79,11 @@ def isolate_document_state(tmp_path, monkeypatch): "Grouped preprocessing with Preprocessor", id="feature-groups", ), + pytest.param( + ROOT / "docs" / "representations" / "spline_expansions.md", + "Typed spline penalties", + id="spline-penalties", + ), ], ) @pytest.mark.filterwarnings("ignore::pretab.exceptions.LeakageWarning") diff --git a/tests/expansion/spline/test_penalty_matrix_invariants.py b/tests/expansion/spline/test_penalty_matrix_invariants.py index 36647e2..84890f7 100644 --- a/tests/expansion/spline/test_penalty_matrix_invariants.py +++ b/tests/expansion/spline/test_penalty_matrix_invariants.py @@ -79,6 +79,30 @@ def test_tensor_product_penalty_is_symmetric_psd(X_multi): assert_valid_penalty(P) +@pytest.mark.parametrize("include_bias", [False, True]) +@pytest.mark.parametrize("first_weight", [0.0, 3.0]) +def test_weighted_typed_tensor_penalties_match_small_joint_reference(X_multi, include_bias, first_weight): + transformer = TensorProductSplineTransformer(output_dim=3, degree=2, diff_order=2, include_bias=include_bias).fit( + X_multi + ) + first, second = transformer.get_penalty_specs() + combined = first_weight * first.matrix + 2.0 * second.matrix + + difference = np.array([1.0, -2.0, 1.0]) + if include_bias: + difference = np.pad(difference, (1, 0)) + marginal = np.outer(difference, difference) + width = difference.size + identity = np.eye(width) + expected = first_weight * np.kron(marginal, identity) + 2.0 * np.kron(identity, marginal) + np.testing.assert_array_equal(combined, expected) + assert_valid_penalty(combined) + + marginal_nullity = width - 1 + first_nullity = marginal_nullity if first_weight > 0 else width + assert np.linalg.matrix_rank(combined) == width**2 - first_nullity * marginal_nullity + + def test_thinplate_penalty_is_symmetric_but_not_guaranteed_psd(): X = np.linspace(0, 1, 40).reshape(-1, 1) transformer = ThinPlateSplineTransformer(n_components=6, random_state=0).fit(X) From 6915b2a60bc32ae824740c84415fd9b162a40d03 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 07:31:09 +0100 Subject: [PATCH 54/86] feat(core): add task target validation helper --- pretab/core/validation.py | 67 ++++++++++++++++++++++++++++++++++- tests/core/test_validation.py | 52 +++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 tests/core/test_validation.py diff --git a/pretab/core/validation.py b/pretab/core/validation.py index 34d1824..e28bc71 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -12,9 +12,10 @@ import numpy as np import pandas as pd +from sklearn.utils.multiclass import type_of_target from sklearn.utils.validation import _check_feature_names, _check_feature_names_in, check_array -from ..exceptions import DataWarning, IncompatibleParamsError, PretabDataError, invalid_param_error +from ..exceptions import ConfigWarning, DataWarning, IncompatibleParamsError, PretabDataError, invalid_param_error __all__ = ["is_polars_frame", "polars_to_pandas", "resolve_input_features", "single_target", "validate_2d_allow_nan"] @@ -80,6 +81,70 @@ def single_target(y, estimator: str, *, fix: str | None = None) -> np.ndarray: return y.ravel() +def _validate_task_target( + y: object, + *, + task: str, + mode: Literal["off", "warn", "raise"], + estimator: str, + role: str, +) -> None: + """Diagnose clear mismatches for a validated task, mode and target-consuming role. + + Inspect only supported single-output targets. The caller retains ownership + of target validation and passes the original target on to fitting. + """ + if mode == "off" or not isinstance(y, (np.ndarray, pd.Series, pd.DataFrame, pd.Index, list, tuple)): + return + try: + values = np.asarray(y, dtype=object) if isinstance(y, (list, tuple)) else np.asarray(y) + except (TypeError, ValueError, OverflowError): + return + if ( + values.size == 0 + or values.ndim not in (1, 2) + or (values.ndim == 2 and values.shape[-1] != 1) + or values.dtype.kind not in "biufOU" + or pd.isna(values).any() + ): + return + + text_labels = values.dtype.kind == "U" or ( + values.dtype.kind == "O" and all(isinstance(value, str) for value in values.flat) + ) + if values.dtype.kind == "O" and not text_labels: + if not all(isinstance(value, (bool, int, float, np.bool_, np.integer, np.floating)) for value in values.flat): + return + values = np.asarray(values.tolist()) + if values.dtype.kind not in "biuf": + return + integer_limit = -int(np.iinfo(np.int64).min) + if values.dtype.kind == "f" and not (-integer_limit <= float(values.min()) and float(values.max()) < integer_limit): + return + + try: + observed = type_of_target(y) + except (TypeError, ValueError, OverflowError): + return + if task == "classification" and observed == "continuous": + suggested = "regression" + elif task == "regression" and observed in ("binary", "multiclass") and text_labels: + try: + np.asarray(values, dtype=np.float64) + except ValueError: + suggested = "classification" + else: + return + else: + return + + detail = f"{role} uses task={task!r}, but y has target type {observed!r}" + fix = f"use task={suggested!r} or set task_validation='off' if this is intentional" + if mode == "raise": + raise invalid_param_error(estimator, "task", task, f"{detail}; {fix}.") + warnings.warn(f"{estimator}: {detail}; {fix}.", ConfigWarning, stacklevel=2) + + def is_polars_frame(X) -> bool: """Return True if ``X`` is a polars DataFrame, without importing polars. diff --git a/tests/core/test_validation.py b/tests/core/test_validation.py new file mode 100644 index 0000000..50c8622 --- /dev/null +++ b/tests/core/test_validation.py @@ -0,0 +1,52 @@ +"""Contracts for shared target inspection, independent of estimator wiring.""" + +import numpy as np +import pandas as pd +import pytest + +from pretab.core import validation +from pretab.exceptions import ConfigWarning, InvalidParamError + + +@pytest.mark.parametrize( + ("target", "task", "observed", "suggested"), + [ + (np.array([0.1, 1.25, 3.5]), "classification", "continuous", "regression"), + (pd.DataFrame({"response": [0.1, 1.25, 3.5]}), "classification", "continuous", "regression"), + (pd.Series(["private-a", "private-b", "private-a"]), "regression", "binary", "classification"), + ], +) +@pytest.mark.parametrize(("mode", "exception"), [("warn", ConfigWarning), ("raise", InvalidParamError)]) +def test_task_target_diagnoses_only_clear_mismatches(target, task, observed, suggested, mode, exception): + check = pytest.warns if mode == "warn" else pytest.raises + with check(exception, match=rf"(?s)Example.*placement.*task='{task}'.*'{observed}'.*task='{suggested}'") as caught: + validation._validate_task_target(target, task=task, mode=mode, estimator="Example", role="placement") + message = str(caught.value if isinstance(caught, pytest.ExceptionInfo) else caught[0].message) + assert "task_validation='off'" in message + assert "private-" not in message + + +@pytest.mark.parametrize("target", [[0, 1, 2], [True, False], [0.0, 1.0, 2.0], ["0.5", "1e3", "-2"]]) +def test_task_target_leaves_ambiguous_regression_quiet(target): + validation._validate_task_target(target, task="regression", mode="raise", estimator="Example", role="placement") + + +@pytest.mark.parametrize( + ("target", "mode"), + [ + (np.array([0.1, 1.25, 3.5]), "off"), + (None, "raise"), + (np.array([0.5, np.nan]), "raise"), + (np.array([0.5, np.inf]), "raise"), + (np.array([0.5, 1e30]), "raise"), + ([int(np.iinfo(np.int64).max), 0.5], "raise"), + (pd.Series([0.5, pd.NA], dtype="Float64"), "raise"), + (pd.DataFrame({"a": [1, 0], "b": [0, 1]}), "raise"), + ], +) +def test_task_target_skips_indeterminate_inputs_before_sklearn(target, mode, monkeypatch): + def unexpected_inspection(target): + pytest.fail("target should not be sent to sklearn") + + monkeypatch.setattr(validation, "type_of_target", unexpected_inspection) + validation._validate_task_target(target, task="classification", mode=mode, estimator="Example", role="placement") From 302f2328ab4b0ce5ff3ad27655404a42d87448c2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 08:16:32 +0100 Subject: [PATCH 55/86] feat(config): add task validation policy parameter --- pretab/compose/search.py | 20 +++++++++++++++-- pretab/compose/serialize.py | 1 + pretab/core/supervised.py | 12 +++++++++-- pretab/core/validation.py | 6 ++++++ pretab/preprocessor.py | 9 +++++++- tests/compose/test_config.py | 4 ++-- tests/compose/test_search.py | 23 ++++++++++++++++++-- tests/core/test_cross_fitted.py | 22 ++++++++++++++++++- tests/core/test_validation.py | 11 ++++++++++ tests/integration/test_preprocessor.py | 24 +++++++++++++++++++++ tests/integration/test_serialization.py | 19 +++++++++++++++- tests/regression/_snapshots/public_api.json | 6 +++--- 12 files changed, 143 insertions(+), 14 deletions(-) diff --git a/pretab/compose/search.py b/pretab/compose/search.py index a3c9020..b3da8bb 100644 --- a/pretab/compose/search.py +++ b/pretab/compose/search.py @@ -21,7 +21,7 @@ from sklearn.utils.validation import _check_method_params, check_is_fitted from ..core._typing import PredictorLike -from ..core.validation import is_polars_frame, polars_to_pandas +from ..core.validation import _validate_task_validation, is_polars_frame, polars_to_pandas from ..exceptions import InvalidParamError from ..preprocessor import Preprocessor @@ -101,13 +101,28 @@ class RepresentationSearchCV(BaseEstimator): string column names. """ - def __init__(self, estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None): + def __init__( + self, + estimator, + methods, + *, + cv=5, + scoring=None, + preprocessor_params=None, + random_state=None, + task_validation="off", + ): self.estimator = estimator self.methods = methods self.cv = cv self.scoring = scoring self.preprocessor_params = preprocessor_params self.random_state = random_state + self.task_validation = task_validation + + def __setstate__(self, state): + super().__setstate__(state) + self.__dict__.setdefault("task_validation", "off") def _make_preprocessor(self, method): """Build a Preprocessor for ``method`` with the shared parameters. @@ -157,6 +172,7 @@ def fit(self, X, y=None, *, groups=None, **fit_params): raise InvalidParamError("methods must be a non-empty sequence of numerical methods.") if y is None: raise InvalidParamError("RepresentationSearchCV requires y at fit time; got y=None.") + _validate_task_validation(self.task_validation, type(self).__name__) y_arr = np.asarray(y).ravel() if is_polars_frame(X): # Converted once, so every fold's rows carry the dtypes of the whole frame, diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 6498ff5..0b0a69b 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -399,5 +399,6 @@ def preprocessor_from_spec(data: dict): obj = Preprocessor.__new__(Preprocessor) obj.__dict__.update(_decode_mapping(data["state"])) obj.__dict__.setdefault("feature_groups", None) + obj.__dict__.setdefault("task_validation", "off") _repair_legacy_sparse_feature_counts(obj) return obj diff --git a/pretab/core/supervised.py b/pretab/core/supervised.py index 6c54fae..0b2a2ae 100644 --- a/pretab/core/supervised.py +++ b/pretab/core/supervised.py @@ -34,7 +34,7 @@ from ._typing import TransformerLike from .parameters import validate_task from .representation import RepresentationSpecMixin -from .validation import is_polars_frame, polars_to_pandas +from .validation import _validate_task_validation, is_polars_frame, polars_to_pandas __all__ = ["CrossFittedTransformer", "in_controlled_context", "warn_target_leakage"] @@ -194,12 +194,19 @@ class CrossFittedTransformer(RepresentationSpecMixin, TransformerMixin, BaseEsti _representation_supervision = "supervised" - def __init__(self, transformer, n_folds=5, task="regression", shuffle=True, random_state=None): + def __init__( + self, transformer, n_folds=5, task="regression", shuffle=True, random_state=None, *, task_validation="off" + ): self.transformer = transformer self.n_folds = n_folds self.task = task self.shuffle = shuffle self.random_state = random_state + self.task_validation = task_validation + + def __setstate__(self, state): + super().__setstate__(state) + self.__dict__.setdefault("task_validation", "off") def _make_splitter(self): """Return the cross-fitting splitter for the configured task.""" @@ -215,6 +222,7 @@ def _fit_full(self, X, y): if not isinstance(self.n_folds, (int, np.integer)) or self.n_folds < 2: raise InvalidParamError(f"n_folds must be an integer >= 2; got {self.n_folds!r}.") validate_task(self.task, type(self).__name__) + _validate_task_validation(self.task_validation, type(self).__name__) X_arr = _as_2d(X) y_arr = np.asarray(y).ravel() if len(X_arr) != len(y_arr): diff --git a/pretab/core/validation.py b/pretab/core/validation.py index e28bc71..0bdbdeb 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -81,6 +81,12 @@ def single_target(y, estimator: str, *, fix: str | None = None) -> np.ndarray: return y.ravel() +def _validate_task_validation(mode: object, estimator: str) -> None: + """Validate the requested consistency policy without normalizing it.""" + if not isinstance(mode, str) or mode not in ("off", "warn", "raise"): + raise invalid_param_error(estimator, "task_validation", mode, "must be 'off', 'warn', or 'raise'") + + def _validate_task_target( y: object, *, diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index cc94907..af2f646 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -52,6 +52,7 @@ from .core.logging import configure_logging, get_logger from .core.parameters import UNSET, validate_task from .core.policy import RepresentationPolicy, apply_constant_policy +from .core.validation import _validate_task_validation from .exceptions import ( ConfigWarning, DataWarning, @@ -511,6 +512,7 @@ def __init__( preset=None, *, feature_groups=None, + task_validation="off", ): """ Initialize the Preprocessor with various transformation options for tabular data. @@ -549,11 +551,13 @@ def __init__( self.verbose = verbose self.preset = preset self.feature_groups = feature_groups + self.task_validation = task_validation def __setstate__(self, state): super().__setstate__(state) if not hasattr(self, "feature_groups"): self.feature_groups = None + self.__dict__.setdefault("task_validation", "off") _repair_legacy_sparse_feature_counts(self) def fit(self, X, y=None, embeddings=None): @@ -907,6 +911,7 @@ def _resolved_params(self): """ params = self.get_params(deep=False) preset = params.pop("preset", None) + _validate_task_validation(params["task_validation"], type(self).__name__) resolved = {key: (_PRESET_PARAM_DEFAULTS[key] if value is UNSET else value) for key, value in params.items()} validate_task(resolved["task"], type(self).__name__) if preset is None: @@ -950,7 +955,7 @@ def get_resolved_config(self): Raises ------ InvalidParamError - If ``task``, ``preset``, or a declared representation is invalid. + If ``task``, ``task_validation``, ``preset``, or a declared representation is invalid. """ resolved = self._resolved_params() if resolved["feature_preprocessing"] or resolved["feature_groups"] is not None: @@ -1548,6 +1553,8 @@ def _canonical_spec(self) -> dict: } if not getattr(self, "feature_groups", None): state.pop("feature_groups", None) + if state.get("task_validation") == "off": + state.pop("task_validation") return { "schema_version": spec["schema_version"], "pretab_version": spec["pretab_version"], diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index 794b4b4..d9eb95a 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -62,6 +62,7 @@ def test_resolved_config_matches_inline_preset_contract(task, preset, overrides) "dtype": None, "verbose": 0, "feature_groups": None, + "task_validation": "off", **overrides, } @@ -209,14 +210,13 @@ def test_invalid_group_declarations_raise_contextual_errors(make_config, request make_config(feature_groups=requested) -def test_group_parameter_is_last_keyword_only_and_remains_raw_for_sklearn(): +def test_group_parameter_is_keyword_only_and_remains_raw_for_sklearn(): declarations = { "location": {"columns": [1, "latitude"], "representation": {"method": "thinplate", "n_components": 4}} } processor = Preprocessor(feature_groups=declarations, random_state=17) parameters = inspect.signature(Preprocessor).parameters - assert list(parameters)[-1] == "feature_groups" assert parameters["feature_groups"].kind is inspect.Parameter.KEYWORD_ONLY assert parameters["feature_groups"].default is None assert processor.get_params(deep=False)["feature_groups"] is declarations diff --git a/tests/compose/test_search.py b/tests/compose/test_search.py index 2d94d76..388cf31 100644 --- a/tests/compose/test_search.py +++ b/tests/compose/test_search.py @@ -129,11 +129,24 @@ def test_predict_before_fit_raises(nonlinear_data): def test_get_params_and_clone_preserve_config(): from sklearn.base import clone - search = RepresentationSearchCV(LinearRegression(), methods=["bspline", "standardization"], cv=3) + search = RepresentationSearchCV( + LinearRegression(), methods=["bspline", "standardization"], cv=3, task_validation="warn" + ) assert search.get_params()["methods"] == ["bspline", "standardization"] cloned = clone(search) assert isinstance(cloned, RepresentationSearchCV) assert cloned.get_params()["cv"] == 3 + assert cloned.get_params()["task_validation"] == "warn" + cloned.set_params(task_validation="raise") + assert cloned.get_params()["task_validation"] == "raise" + + +def test_invalid_search_task_validation_rejected(nonlinear_data): + X, y = nonlinear_data + search = RepresentationSearchCV(LinearRegression(), methods=["bspline"], task_validation="WARN") + assert search.get_params()["task_validation"] == "WARN" + with pytest.raises(InvalidParamError, match=r"RepresentationSearchCV\.task_validation"): + search.fit(X, y) class _RowRecorder(RegressorMixin, BaseEstimator): @@ -378,9 +391,15 @@ def test_classifier_search_places_against_class_labels(class_data): def test_classifier_search_keeps_an_explicit_task(class_data): X, y = class_data search = RepresentationSearchCV( - LogisticRegression(), methods=["minmax"], cv=3, preprocessor_params={"task": "regression"} + LogisticRegression(), + methods=["minmax"], + cv=3, + preprocessor_params={"task": "regression", "task_validation": "warn"}, + task_validation="raise", ).fit(X, (y == "pos").astype(int)) assert search.best_preprocessor_.task == "regression" + assert search.best_preprocessor_.task_validation == "warn" + assert search.task_validation == "raise" def test_regressor_search_keeps_the_regression_task(nonlinear_data): diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index e7b6b81..f48ef6c 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -11,7 +11,7 @@ import numpy as np import pytest -from sklearn.base import BaseEstimator, TransformerMixin +from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn.model_selection import KFold, StratifiedKFold from pretab import CrossFittedTransformer, LeakageWarning @@ -110,6 +110,26 @@ def test_invalid_task_rejected(data): CrossFittedTransformer(PLETransformer(), task="classificaton").fit_transform(X, y) +@pytest.mark.parametrize("operation", ["fit", "fit_transform"]) +def test_invalid_task_validation_rejected(data, operation): + X, y = data + transformer = CrossFittedTransformer(PLETransformer(), task_validation="WARN") + assert transformer.get_params()["task_validation"] == "WARN" + with pytest.raises(InvalidParamError, match=r"CrossFittedTransformer\.task_validation"): + getattr(transformer, operation)(X, y) + + +def test_cross_fit_task_validation_survives_clone_and_fit(data): + X, y = data + transformer = CrossFittedTransformer(PLETransformer(), 3, "regression", False, 0) + assert transformer.get_params(deep=False)["task_validation"] == "off" + transformer.set_params(task_validation="raise") + copied = clone(transformer) + assert isinstance(copied, CrossFittedTransformer) + copied.fit(X, y) + assert copied.get_params(deep=False) == transformer.get_params(deep=False) | {"transformer": copied.transformer} + + # --- fit_transform returns the kind of output transform returns (issue #90) --------- diff --git a/tests/core/test_validation.py b/tests/core/test_validation.py index 50c8622..a1db221 100644 --- a/tests/core/test_validation.py +++ b/tests/core/test_validation.py @@ -8,6 +8,17 @@ from pretab.exceptions import ConfigWarning, InvalidParamError +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_task_validation_accepts_exact_modes(mode): + validation._validate_task_validation(mode, "Example") + + +@pytest.mark.parametrize("mode", ["WARN", " off", "", None, True, False, 1, ["warn"], np.array(["warn"])]) +def test_task_validation_rejects_invalid_modes(mode): + with pytest.raises(InvalidParamError, match=r"(?s)Example\.task_validation.*'off', 'warn', or 'raise'"): + validation._validate_task_validation(mode, "Example") + + @pytest.mark.parametrize( ("target", "task", "observed", "suggested"), [ diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 3f257cd..25019b9 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -12,6 +12,7 @@ from sklearn.utils.validation import check_is_fitted from pretab import RepresentationConfig +from pretab.core.parameters import UNSET from pretab.exceptions import IncompatibleParamsError, InvalidParamError, PretabDataError from pretab.expansion.functional.rbf import RBFExpansionTransformer from pretab.preprocessor import Preprocessor # Adjust the import as needed @@ -203,6 +204,7 @@ def test_dict_keys_reflect_column_names(sample_data): "verbose", "preset", "feature_groups", + "task_validation", } @@ -225,12 +227,34 @@ def test_clone_preserves_every_param(): adaptive=True, feature_preprocessing={"a": "pspline"}, verbose=1, + task_validation="warn", ) cloned = clone(pre) assert isinstance(cloned, Preprocessor) assert cloned.get_params() == pre.get_params() +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_task_validation_resolves_after_set_params(mode): + processor = Preprocessor(task="classification") + assert processor.get_params(deep=False)["task_validation"] == "off" + processor.set_params(task_validation=mode) + resolved = processor.get_resolved_config() + assert resolved["task_validation"] == mode + assert resolved["task"] == "classification" + + +@pytest.mark.parametrize("mode", [None, "WARN", UNSET]) +def test_invalid_facade_task_validation_rejected(sample_data, mode): + frame, target = sample_data + processor = Preprocessor(task_validation=mode) + assert processor.get_params(deep=False)["task_validation"] is mode + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task_validation"): + processor.get_resolved_config() + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task_validation"): + processor.fit(frame, target) + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("fitted", [False, True], ids=["unfitted", "fitted"]) def test_structured_feature_params_survive_fit_and_clone(sample_data, typed, fitted): diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index 64290ea..9435391 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -43,26 +43,43 @@ def target(): @pytest.mark.parametrize("restore_format", ["pickle", "spec"]) -def test_legacy_state_without_groups_restores_the_constructor_default(frame, restore_format): +def test_legacy_state_restores_constructor_defaults(frame, restore_format): processor = Preprocessor(numerical_method="rbf", target_aware=False, placement_strategy="uniform").fit(frame) expected = processor.transform(frame) fingerprint = processor.fingerprint_ if restore_format == "pickle": del processor.feature_groups + del processor.task_validation restored = pickle.loads(pickle.dumps(processor)) # noqa: S301 else: spec = processor.to_spec() del spec["state"]["feature_groups"] del spec["params"]["feature_groups"] + del spec["state"]["task_validation"] + del spec["params"]["task_validation"] restored = Preprocessor.from_spec(spec) assert restored.get_params(deep=False)["feature_groups"] is None + assert restored.get_params(deep=False)["task_validation"] == "off" assert restored.get_resolved_config()["feature_groups"] is None + assert restored.get_resolved_config()["task_validation"] == "off" assert restored.fingerprint_ == fingerprint np.testing.assert_array_equal(restored.transform(frame), expected) copied = clone(restored) assert isinstance(copied, Preprocessor) assert copied.feature_groups is None + assert copied.task_validation == "off" + + +def test_spec_preserves_nondefault_task_validation(frame): + processor = Preprocessor(numerical_method="minmax", task_validation="raise").fit(frame) + expected = processor.transform(frame) + spec = processor.to_spec() + assert spec["params"]["task_validation"] == "raise" + restored = Preprocessor.from_spec(spec) + assert restored.get_resolved_config()["task_validation"] == "raise" + assert restored.fingerprint_ == processor.fingerprint_ + np.testing.assert_array_equal(restored.transform(frame), expected) # Representation configs that round-trip; each is (params, id). diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json index bcbbc7d..b0050c6 100644 --- a/tests/regression/_snapshots/public_api.json +++ b/tests/regression/_snapshots/public_api.json @@ -1149,14 +1149,14 @@ }, "signatures": { "pretab.BaseRepresentation": "()", - "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None)", + "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None, *, task_validation='off')", "pretab.FeatureGroup": "(name: 'str', columns: 'Sequence[Any]', representation: 'str | Mapping[str, Any] | RepresentationConfig') -> None", "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool, group_id: str | None = None) -> None", "pretab.PenaltySpec": "(matrix: 'ArrayLike', kind: 'str', order: 'int | None', axis: 'Sequence[str]', coordinate_system: 'str', coefficient_names: 'Sequence[str]', coefficient_indices: 'Sequence[int]', atol: 'float' = 1e-10, rtol: 'float' = 1e-10, provenance: 'Mapping[str, Any] | None' = None) -> 'None'", - "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None, *, feature_groups=None)", + "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None, *, feature_groups=None, task_validation='off')", "pretab.RepresentationConfig": "(method: 'str', output_dim: 'int | _Unset' = UNSET, target_aware: 'bool | _Unset' = UNSET, placement_strategy: 'str | _Unset' = UNSET, adaptive: 'bool | _Unset' = UNSET, min_output_dim: 'int | _Unset | None' = UNSET, max_output_dim: 'int | _Unset | None' = UNSET, params: 'Mapping[str, Any]' = , name: 'str | None' = None) -> None", "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", - "pretab.RepresentationSearchCV": "(estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None)", + "pretab.RepresentationSearchCV": "(estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None, task_validation='off')", "pretab.RepresentationSpec": "(family: str, component_kind: str, scope: str, supervision: str, uses_target: bool, is_interaction: bool, input_features: tuple[str, ...], output_features: tuple[str, ...], output_dim: int, degree: int | None, include_bias: bool, periodic: bool, period: float | None, local_support: bool, location_kind: str | None, locations: tuple[tuple[float, ...], ...] | None, dtype: str = 'float64', cross_fitted: bool = False, n_folds: int | None = None) -> None", "pretab.check_representation": "(cls, *, X=None, y=None)", "pretab.configure_logging": "(level: int = 1, handler: 'logging.Handler | None' = None) -> None", From 0d8f675f1b32258af3fe7649b9a9853f40a54e90 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 09:39:46 +0100 Subject: [PATCH 56/86] feat(core): validate task targets before fitting --- pretab/compose/inspection.py | 15 +++ pretab/core/supervised.py | 61 ++++++++--- pretab/core/validation.py | 47 +++++++++ pretab/preprocessor.py | 137 +++++++++++++++---------- tests/core/test_cross_fitted.py | 32 +++++- tests/integration/test_preprocessor.py | 11 ++ 6 files changed, 236 insertions(+), 67 deletions(-) diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index 7a4ca43..0bfe761 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -401,6 +401,21 @@ def _resolve_block_representation(pipeline, columns): return _locate_block_representation(pipeline, columns)[1] +def _block_uses_task(transformer) -> bool: + """Check a constructed block for a target consumer configured with a task.""" + separate_state = _separate_state_branches(transformer) + representation = separate_state[0] if separate_state is not None else transformer + for name, step in representation.steps: + spec = TRANSFORMER_REGISTRY.get(name) + if spec is None or not isinstance(step, spec.transformer_cls) or getattr(step, "task", None) is None: + continue + if spec.target_usage == "required" or ( + spec.target_usage == "optional" and getattr(step, "target_aware", False) + ): + return True + return False + + def block_uses_target(transformer) -> bool: """Whether a fitted single-feature or joint block's representation consumed ``y``. diff --git a/pretab/core/supervised.py b/pretab/core/supervised.py index 0b2a2ae..cb6bf49 100644 --- a/pretab/core/supervised.py +++ b/pretab/core/supervised.py @@ -23,6 +23,7 @@ from scipy import sparse as sp from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn.model_selection import KFold, StratifiedKFold +from sklearn.pipeline import Pipeline from sklearn.utils.validation import check_is_fitted from ..exceptions import ( @@ -34,7 +35,13 @@ from ._typing import TransformerLike from .parameters import validate_task from .representation import RepresentationSpecMixin -from .validation import _validate_task_validation, is_polars_frame, polars_to_pandas +from .validation import ( + _check_task_target_once, + _task_target_scope, + _validate_task_validation, + is_polars_frame, + polars_to_pandas, +) __all__ = ["CrossFittedTransformer", "in_controlled_context", "warn_target_leakage"] @@ -215,27 +222,55 @@ def _make_splitter(self): return StratifiedKFold(n_splits=self.n_folds, shuffle=self.shuffle, random_state=seed) return KFold(n_splits=self.n_folds, shuffle=self.shuffle, random_state=seed) - def _fit_full(self, X, y): - """Validate inputs and fit ``estimator_``; return 2D input and target array.""" + def _validate_fit_params(self, y): if y is None: raise IncompatibleParamsError("CrossFittedTransformer requires y at fit time; got y=None.") if not isinstance(self.n_folds, (int, np.integer)) or self.n_folds < 2: raise InvalidParamError(f"n_folds must be an integer >= 2; got {self.n_folds!r}.") validate_task(self.task, type(self).__name__) _validate_task_validation(self.task_validation, type(self).__name__) + + def _preflight_task_target(self, X, y): + self._validate_fit_params(y) + self._check_fit_target(X, y) + + def _check_fit_target(self, X, y): + _check_task_target_once( + y, + task=self.task, + mode=self.task_validation, + estimator=type(self).__name__, + role="cross-fitting", + n_samples=len(X), + ) + transformer = self.transformer + while isinstance(transformer, Pipeline): + transformer = next( + (step for _, step in transformer.steps if step is not None and step != "passthrough"), None + ) + preflight = getattr(transformer, "_preflight_task_target", None) + if preflight is not None: + preflight(X, y) + + def _fit_full(self, X, y): + """Validate inputs and fit ``estimator_``; return input, target and diagnostic receipts.""" + self._validate_fit_params(y) X_arr = _as_2d(X) y_arr = np.asarray(y).ravel() if len(X_arr) != len(y_arr): raise PretabDataError(f"X and y must have same length. Got {len(X_arr)} and {len(y_arr)}") - estimator = cast(TransformerLike, clone(self.transformer)) - token = _cross_fit_active.set(True) - try: - estimator.fit(X_arr, y_arr) - finally: - _cross_fit_active.reset(token) + with _task_target_scope(y) as receipts: + self._check_fit_target(X_arr, y) + estimator = cast(TransformerLike, clone(self.transformer)) + token = _cross_fit_active.set(True) + try: + with _task_target_scope(y_arr, receipts): + estimator.fit(X_arr, y_arr) + finally: + _cross_fit_active.reset(token) self.estimator_ = estimator self.n_features_in_ = X_arr.shape[1] - return X_arr, y_arr + return X_arr, y_arr, receipts def fit(self, X, y=None): """Fit the all-data ``estimator_`` used by :meth:`transform`.""" @@ -280,7 +315,7 @@ def fit_transform(self, X, y=None): or if a fold's output has an invalid shape, a different width, or DataFrame columns other than the all-data fit's. """ - X_arr, y_arr = self._fit_full(X, y) + X_arr, y_arr, receipts = self._fit_full(X, y) names = list(self.estimator_.get_feature_names_out()) width = len(names) blocks, test_indices = [], [] @@ -288,7 +323,9 @@ def fit_transform(self, X, y=None): token = _cross_fit_active.set(True) try: for train_idx, test_idx in splitter.split(X_arr, y_arr): - fold = self._fit_fold(_take_rows(X_arr, train_idx), y_arr[train_idx]) + train_y = y_arr[train_idx] + with _task_target_scope(train_y, receipts): + fold = self._fit_fold(_take_rows(X_arr, train_idx), train_y) fold_out = fold.transform(_take_rows(X_arr, test_idx)) if isinstance(fold_out, dict): raise IncompatibleParamsError( diff --git a/pretab/core/validation.py b/pretab/core/validation.py index 0bdbdeb..ad306fa 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -8,6 +8,8 @@ import sys import warnings +from contextlib import contextmanager +from contextvars import ContextVar from typing import Literal, cast import numpy as np @@ -87,6 +89,49 @@ def _validate_task_validation(mode: object, estimator: str) -> None: raise invalid_param_error(estimator, "task_validation", mode, "must be 'off', 'warn', or 'raise'") +_TaskTargetContract = tuple[str, Literal["off", "warn", "raise"], str] +_task_target_context: ContextVar[tuple[object, set[_TaskTargetContract]] | None] = ContextVar( + "_task_target_context", default=None +) + + +@contextmanager +def _task_target_scope(y: object, receipts: set[_TaskTargetContract] | None = None): + """Bind completed checks only to this target or an explicitly related fold.""" + active = _task_target_context.get() + if receipts is None and active is not None and active[0] is y: + yield active[1] + return + if receipts is None: + receipts = set() + token = _task_target_context.set((y, receipts)) + try: + yield receipts + finally: + _task_target_context.reset(token) + + +def _check_task_target_once( + y: object, + *, + task: str, + mode: Literal["off", "warn", "raise"], + estimator: str, + role: str, + n_samples: int, +) -> None: + if mode == "off" or y is None: + return + active = _task_target_context.get() + receipts = active[1] if active is not None and active[0] is y else None + contract = (task, mode, role) + if receipts is not None and contract in receipts: + return + _validate_task_target(y, task=task, mode=mode, estimator=estimator, role=role, n_samples=n_samples) + if receipts is not None: + receipts.add(contract) + + def _validate_task_target( y: object, *, @@ -94,6 +139,7 @@ def _validate_task_target( mode: Literal["off", "warn", "raise"], estimator: str, role: str, + n_samples: int | None = None, ) -> None: """Diagnose clear mismatches for a validated task, mode and target-consuming role. @@ -109,6 +155,7 @@ def _validate_task_target( if ( values.size == 0 or values.ndim not in (1, 2) + or (n_samples is not None and values.shape[0] != n_samples) or (values.ndim == 2 and values.shape[-1] != 1) or values.dtype.kind not in "biufOU" or pd.isna(values).any() diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index af2f646..1378c19 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -24,6 +24,7 @@ with_string_labels, ) from .compose.inspection import ( + _block_uses_task, _iter_fitted_blocks, block_uses_target, build_feature_info, @@ -52,7 +53,7 @@ from .core.logging import configure_logging, get_logger from .core.parameters import UNSET, validate_task from .core.policy import RepresentationPolicy, apply_constant_policy -from .core.validation import _validate_task_validation +from .core.validation import _check_task_target_once, _validate_task_validation from .exceptions import ( ConfigWarning, DataWarning, @@ -609,29 +610,7 @@ def fit(self, X, y=None, embeddings=None): start_time = time.perf_counter() resolved = self._resolved_params() - config = PreprocessorConfig.from_params( - numerical_method=resolved["numerical_method"], - categorical_method=resolved["categorical_method"], - feature_preprocessing=resolved["feature_preprocessing"], - output_dim=resolved["output_dim"], - degree=resolved["degree"], - target_aware=resolved["target_aware"], - placement_strategy=resolved["placement_strategy"], - task=resolved["task"], - adaptive=resolved["adaptive"], - min_output_dim=resolved["min_output_dim"], - max_output_dim=resolved["max_output_dim"], - random_state=resolved["random_state"], - scaling=resolved["scaling"], - cat_cutoff=resolved["cat_cutoff"], - treat_all_integers_as_numerical=resolved["treat_all_integers_as_numerical"], - numerical_imputation=resolved["numerical_imputation"], - categorical_imputation=resolved["categorical_imputation"], - add_missing_indicator=resolved["add_missing_indicator"], - missing_policy=resolved["missing_policy"], - verbose=resolved["verbose"], - feature_groups=resolved["feature_groups"], - ) + config = self._fit_config(resolved) if config.feature_groups: group_frame = to_dataframe(X) @@ -647,16 +626,7 @@ def fit(self, X, y=None, embeddings=None): fitted_on_array = not has_column_labels(X) X = to_dataframe(X) - if self.feature_preprocessing: - unknown_features = set(self.feature_preprocessing) - set(X.columns) - if unknown_features: - raise invalid_param_error( - type(self).__name__, - "feature_preprocessing", - sorted(unknown_features), - "every key must name a column present in X", - valid=X.columns, - ) + self._validate_feature_overrides(X) if self.missing_policy == "error": self._reject_missing(X) @@ -697,25 +667,7 @@ def fit(self, X, y=None, embeddings=None): numeric_values[:, np.isnan(numeric_values).all(axis=0)] = 0.0 apply_constant_policy(numeric_values, self.policy_, estimator=self) - valid_formats = ("auto", "dense", "sparse") - if self.output_format not in valid_formats: - raise invalid_param_error( - type(self).__name__, - "output_format", - self.output_format, - "must be one of 'auto', 'dense', 'sparse'", - valid=set(valid_formats), - ) - - valid_structures = ("matrix", "blocks") - if self.output_structure not in valid_structures: - raise invalid_param_error( - type(self).__name__, - "output_structure", - self.output_structure, - "must be one of 'matrix', 'blocks'", - valid=set(valid_structures), - ) + self._validate_fit_output() # Ask ColumnTransformer to assemble the representation in the requested # container whenever its component outputs permit it. In particular, @@ -735,6 +687,7 @@ def fit(self, X, y=None, embeddings=None): # ColumnTransformer.fit runs fit_transform internally; keep the training # output to resolve output_format="auto" once, from the training density. X_ct = self._column_transformer_input(X) + self._check_placement_target(self.column_transformer_, y, config.task, resolved["task_validation"], len(X_ct)) try: training_output = self.column_transformer_.fit_transform(X_ct, y) except ValueError as exc: @@ -890,6 +843,84 @@ def fit_transform(self, X, y=None, embeddings=None, return_array=None): return self.fit(X, y, embeddings=embeddings).transform(X, embeddings, return_array) + @staticmethod + def _fit_config(resolved): + return PreprocessorConfig.from_params( + **{field.name: resolved[field.name] for field in fields(PreprocessorConfig)} + ) + + def _validate_feature_overrides(self, frame): + if self.feature_preprocessing: + unknown_features = set(self.feature_preprocessing) - set(frame.columns) + if unknown_features: + raise invalid_param_error( + type(self).__name__, + "feature_preprocessing", + sorted(unknown_features), + "every key must name a column present in X", + valid=frame.columns, + ) + + def _validate_fit_output(self): + valid_formats = ("auto", "dense", "sparse") + if self.output_format not in valid_formats: + raise invalid_param_error( + type(self).__name__, + "output_format", + self.output_format, + "must be one of 'auto', 'dense', 'sparse'", + valid=set(valid_formats), + ) + + valid_structures = ("matrix", "blocks") + if self.output_structure not in valid_structures: + raise invalid_param_error( + type(self).__name__, + "output_structure", + self.output_structure, + "must be one of 'matrix', 'blocks'", + valid=set(valid_structures), + ) + + def _check_placement_target(self, transformer, y, task, mode, n_samples, *, estimator=None): + if mode == "off" or y is None: + return + blocks = transformer.get_params(deep=False)["transformers"] + if any(_block_uses_task(block) for _, block, _ in blocks): + _check_task_target_once( + y, + task=task, + mode=mode, + estimator=estimator or type(self).__name__, + role="target-aware placement", + n_samples=n_samples, + ) + + def _preflight_task_target(self, X, y, *, outer_mode="off", owner=None): + """Check active placement contracts on a wrapper's full input before it fits clones.""" + _validate_task_validation(self.task_validation, type(self).__name__) + if y is None or (self.task_validation == "off" and outer_mode == "off"): + return + resolved = self._resolved_params() + config = self._fit_config(resolved) + frame = to_dataframe(X) + self._validate_feature_overrides(frame) + if self.missing_policy == "error": + self._reject_missing(frame) + numerical, categorical = detect_column_types( + frame, + cat_cutoff=config.cat_cutoff, + treat_all_integers_as_numerical=config.treat_all_integers_as_numerical, + estimator_name=type(self).__name__, + ) + if config.feature_groups: + config.validate_feature_groups(frame.columns, numerical, y=y) + with_string_labels(frame) + self._validate_fit_output() + transformer = build_column_transformer(config, numerical, categorical) + self._check_placement_target(transformer, y, config.task, outer_mode, len(frame), estimator=owner) + self._check_placement_target(transformer, y, config.task, resolved["task_validation"], len(frame)) + def _resolved_params(self): """Return the effective parameters after expanding ``preset``. diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index f48ef6c..f6a48ee 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -14,9 +14,9 @@ from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn.model_selection import KFold, StratifiedKFold -from pretab import CrossFittedTransformer, LeakageWarning +from pretab import CrossFittedTransformer, LeakageWarning, Preprocessor from pretab.core._typing import TransformerLike -from pretab.exceptions import IncompatibleParamsError, InvalidParamError +from pretab.exceptions import ConfigWarning, IncompatibleParamsError, InvalidParamError from pretab.transformers import PLETransformer @@ -130,6 +130,34 @@ def test_cross_fit_task_validation_survives_clone_and_fit(data): assert copied.get_params(deep=False) == transformer.get_params(deep=False) | {"transformer": copied.transformer} +def test_nested_cross_fit_task_diagnostic_emits_once_per_operation(data): + X, _ = data + target = np.where(X[:, 0] < 0, "low", "high") + inner = CrossFittedTransformer(PLETransformer(task="classification"), n_folds=3, task_validation="warn") + outer = CrossFittedTransformer(inner, n_folds=3, task_validation="warn") + + for _ in range(2): + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ConfigWarning) + outer.fit_transform(X, target) + diagnostics = [item for item in recorded if item.category is ConfigWarning] + assert len(diagnostics) == 1 + assert "cross-fitting uses task='regression'" in str(diagnostics[0].message) + + +def test_cross_fit_preflights_inner_policy_before_cloning(data, monkeypatch): + X, target = data + inner = Preprocessor(numerical_method="rbf", task="classification", task_validation="raise") + outer = CrossFittedTransformer(inner) + + def reject_clone(*args, **kwargs): + pytest.fail("cloned before checking the inner task policy") + + monkeypatch.setattr("pretab.core.supervised.clone", reject_clone) + with pytest.raises(InvalidParamError, match=r"(?s)Preprocessor\.task.*target-aware placement.*continuous"): + outer.fit(X, target) + + # --- fit_transform returns the kind of output transform returns (issue #90) --------- diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 25019b9..967695a 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -255,6 +255,17 @@ def test_invalid_facade_task_validation_rejected(sample_data, mode): processor.fit(frame, target) +def test_task_diagnostic_requires_active_placement(): + frame = pd.DataFrame({"value": np.linspace(0, 1, 24)}) + target = frame["value"] + processor = Preprocessor(numerical_method="rbf", task="classification", task_validation="raise") + with pytest.raises(InvalidParamError, match=r"target-aware placement.*continuous"): + processor.fit(frame, target) + + processor.set_params(feature_preprocessing={"value": "minmax"}) + processor.fit(frame, target) + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("fitted", [False, True], ids=["unfitted", "fitted"]) def test_structured_feature_params_survive_fit_and_clone(sample_data, typed, fitted): From c26be2cc0bde1f27dba0805a90acb061ae4a0777 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 15:55:45 +0100 Subject: [PATCH 57/86] feat(search): validate task targets before cross-validation --- pretab/compose/search.py | 42 ++++++++++++-- pretab/core/supervised.py | 19 +++--- pretab/core/validation.py | 12 ++-- tests/compose/test_search.py | 109 ++++++++++++++++++++++++++++++++++- 4 files changed, 160 insertions(+), 22 deletions(-) diff --git a/pretab/compose/search.py b/pretab/compose/search.py index b3da8bb..c1dd4f9 100644 --- a/pretab/compose/search.py +++ b/pretab/compose/search.py @@ -13,7 +13,7 @@ from typing import cast import numpy as np -from sklearn.base import BaseEstimator, clone, is_classifier +from sklearn.base import BaseEstimator, clone, is_classifier, is_regressor from sklearn.metrics import check_scoring from sklearn.model_selection import BaseCrossValidator, check_cv from sklearn.utils import get_tags @@ -21,7 +21,14 @@ from sklearn.utils.validation import _check_method_params, check_is_fitted from ..core._typing import PredictorLike -from ..core.validation import _validate_task_validation, is_polars_frame, polars_to_pandas +from ..core.validation import ( + _check_task_target_once, + _task_target_scope, + _TaskValidationMode, + _validate_task_validation, + is_polars_frame, + polars_to_pandas, +) from ..exceptions import InvalidParamError from ..preprocessor import Preprocessor @@ -136,6 +143,23 @@ def _make_preprocessor(self, method): params.setdefault("task", "classification") return Preprocessor(numerical_method=method, **params) + def _preflight_task_targets(self, X, y, methods, *, mode: _TaskValidationMode, classifier, n_samples): + inner_mode = dict(self.preprocessor_params or {}).get("task_validation", "off") + if mode == "off" and isinstance(inner_mode, str) and inner_mode == "off": + return + owner = type(self).__name__ + for method in methods: + self._make_preprocessor(method)._preflight_task_target(X, y, outer_mode=mode, owner=owner) + if mode != "off" and (classifier or is_regressor(self.estimator)): + _check_task_target_once( + y, + task="classification" if classifier else "regression", + mode=mode, + estimator=owner, + role="representation search", + n_samples=n_samples, + ) + def fit(self, X, y=None, *, groups=None, **fit_params): """Search over ``methods`` and refit the best representation on all data. @@ -172,7 +196,7 @@ def fit(self, X, y=None, *, groups=None, **fit_params): raise InvalidParamError("methods must be a non-empty sequence of numerical methods.") if y is None: raise InvalidParamError("RepresentationSearchCV requires y at fit time; got y=None.") - _validate_task_validation(self.task_validation, type(self).__name__) + mode = _validate_task_validation(self.task_validation, type(self).__name__) y_arr = np.asarray(y).ravel() if is_polars_frame(X): # Converted once, so every fold's rows carry the dtypes of the whole frame, @@ -182,7 +206,10 @@ def fit(self, X, y=None, *, groups=None, **fit_params): # As in scikit-learn's searches: per-sample fit params are made indexable # so each fold can take its training rows. fit_params = _check_method_params(X, params=fit_params) - cv = cast(BaseCrossValidator, check_cv(self.cv, y_arr, classifier=is_classifier(self.estimator))) + classifier = is_classifier(self.estimator) + cv = cast(BaseCrossValidator, check_cv(self.cv, y_arr, classifier=classifier)) + with _task_target_scope(y) as receipts: + self._preflight_task_targets(X, y, methods, mode=mode, classifier=classifier, n_samples=n_samples) # Reuse the same held-out rows for every candidate, including splitters # whose random state advances on each call to split(). splits = list(cv.split(np.zeros(n_samples), y_arr, groups)) @@ -195,7 +222,9 @@ def fit(self, X, y=None, *, groups=None, **fit_params): for train_idx, test_idx in splits: pre = self._make_preprocessor(method) est = cast(PredictorLike, clone(self.estimator)) - x_train = pre.fit_transform(_row_subset(X, train_idx), y_arr[train_idx], return_array=True) + train_y = y_arr[train_idx] + with _task_target_scope(train_y, receipts.copy()): + x_train = pre.fit_transform(_row_subset(X, train_idx), train_y, return_array=True) fold_params = _check_method_params(X, params=fit_params, indices=train_idx) est.fit(x_train, y_arr[train_idx], **fold_params) scorer = cast("Callable[..., float]", check_scoring(est, scoring=self.scoring)) @@ -211,7 +240,8 @@ def fit(self, X, y=None, *, groups=None, **fit_params): self.best_method_ = best_method self.best_score_ = best_score self.best_preprocessor_ = self._make_preprocessor(best_method) - x_all = self.best_preprocessor_.fit_transform(X, y_arr, return_array=True) + with _task_target_scope(y_arr, receipts.copy()): + x_all = self.best_preprocessor_.fit_transform(X, y_arr, return_array=True) self.best_estimator_ = cast(PredictorLike, clone(self.estimator)).fit(x_all, y_arr, **fit_params) self.n_features_in_ = self.best_preprocessor_.n_features_in_ # scikit-learn convention: feature names are recorded only for input whose diff --git a/pretab/core/supervised.py b/pretab/core/supervised.py index cb6bf49..9ed0435 100644 --- a/pretab/core/supervised.py +++ b/pretab/core/supervised.py @@ -38,6 +38,7 @@ from .validation import ( _check_task_target_once, _task_target_scope, + _TaskValidationMode, _validate_task_validation, is_polars_frame, polars_to_pandas, @@ -222,23 +223,23 @@ def _make_splitter(self): return StratifiedKFold(n_splits=self.n_folds, shuffle=self.shuffle, random_state=seed) return KFold(n_splits=self.n_folds, shuffle=self.shuffle, random_state=seed) - def _validate_fit_params(self, y): + def _validate_fit_params(self, y) -> _TaskValidationMode: if y is None: raise IncompatibleParamsError("CrossFittedTransformer requires y at fit time; got y=None.") if not isinstance(self.n_folds, (int, np.integer)) or self.n_folds < 2: raise InvalidParamError(f"n_folds must be an integer >= 2; got {self.n_folds!r}.") validate_task(self.task, type(self).__name__) - _validate_task_validation(self.task_validation, type(self).__name__) + return _validate_task_validation(self.task_validation, type(self).__name__) def _preflight_task_target(self, X, y): - self._validate_fit_params(y) - self._check_fit_target(X, y) + mode = self._validate_fit_params(y) + self._check_fit_target(X, y, mode=mode) - def _check_fit_target(self, X, y): + def _check_fit_target(self, X, y, *, mode: _TaskValidationMode): _check_task_target_once( y, task=self.task, - mode=self.task_validation, + mode=mode, estimator=type(self).__name__, role="cross-fitting", n_samples=len(X), @@ -254,13 +255,13 @@ def _check_fit_target(self, X, y): def _fit_full(self, X, y): """Validate inputs and fit ``estimator_``; return input, target and diagnostic receipts.""" - self._validate_fit_params(y) + mode = self._validate_fit_params(y) X_arr = _as_2d(X) y_arr = np.asarray(y).ravel() if len(X_arr) != len(y_arr): raise PretabDataError(f"X and y must have same length. Got {len(X_arr)} and {len(y_arr)}") with _task_target_scope(y) as receipts: - self._check_fit_target(X_arr, y) + self._check_fit_target(X_arr, y, mode=mode) estimator = cast(TransformerLike, clone(self.transformer)) token = _cross_fit_active.set(True) try: @@ -324,7 +325,7 @@ def fit_transform(self, X, y=None): try: for train_idx, test_idx in splitter.split(X_arr, y_arr): train_y = y_arr[train_idx] - with _task_target_scope(train_y, receipts): + with _task_target_scope(train_y, receipts.copy()): fold = self._fit_fold(_take_rows(X_arr, train_idx), train_y) fold_out = fold.transform(_take_rows(X_arr, test_idx)) if isinstance(fold_out, dict): diff --git a/pretab/core/validation.py b/pretab/core/validation.py index ad306fa..68ee5cc 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -83,13 +83,17 @@ def single_target(y, estimator: str, *, fix: str | None = None) -> np.ndarray: return y.ravel() -def _validate_task_validation(mode: object, estimator: str) -> None: +_TaskValidationMode = Literal["off", "warn", "raise"] + + +def _validate_task_validation(mode: object, estimator: str) -> _TaskValidationMode: """Validate the requested consistency policy without normalizing it.""" if not isinstance(mode, str) or mode not in ("off", "warn", "raise"): raise invalid_param_error(estimator, "task_validation", mode, "must be 'off', 'warn', or 'raise'") + return cast(_TaskValidationMode, mode) -_TaskTargetContract = tuple[str, Literal["off", "warn", "raise"], str] +_TaskTargetContract = tuple[str, _TaskValidationMode, str] _task_target_context: ContextVar[tuple[object, set[_TaskTargetContract]] | None] = ContextVar( "_task_target_context", default=None ) @@ -115,7 +119,7 @@ def _check_task_target_once( y: object, *, task: str, - mode: Literal["off", "warn", "raise"], + mode: _TaskValidationMode, estimator: str, role: str, n_samples: int, @@ -136,7 +140,7 @@ def _validate_task_target( y: object, *, task: str, - mode: Literal["off", "warn", "raise"], + mode: _TaskValidationMode, estimator: str, role: str, n_samples: int | None = None, diff --git a/tests/compose/test_search.py b/tests/compose/test_search.py index 388cf31..bf66048 100644 --- a/tests/compose/test_search.py +++ b/tests/compose/test_search.py @@ -6,6 +6,9 @@ (``bspline``) must beat a linear ``standardization`` baseline. """ +import os +import warnings + import numpy as np import pandas as pd import pytest @@ -20,11 +23,12 @@ StratifiedKFold, check_cv, cross_val_score, + cross_validate, ) from sklearn.svm import SVC from pretab import RepresentationSearchCV -from pretab.exceptions import InvalidParamError +from pretab.exceptions import ConfigWarning, InvalidParamError # Unsupervised, deterministic placement so scores are reproducible fold to fold. _UNSUPERVISED = {"target_aware": False, "placement_strategy": "uniform", "output_dim": 10} @@ -149,6 +153,104 @@ def test_invalid_search_task_validation_rejected(nonlinear_data): search.fit(X, y) +def test_search_preserves_inner_mode_validation(nonlinear_data): + X, y = nonlinear_data + search = RepresentationSearchCV( + LinearRegression(), methods=["minmax"], preprocessor_params={"task_validation": np.array(["off", "warn"])} + ) + + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task_validation"): + search.fit(X, y) + + +def test_search_checks_later_candidate_before_cloning(nonlinear_data, monkeypatch): + X, y = nonlinear_data + search = RepresentationSearchCV( + LinearRegression(), + methods=["minmax", "rbf"], + preprocessor_params={"task": "classification", "task_validation": "raise"}, + ) + + def reject_clone(*args, **kwargs): + pytest.fail("cloned before checking the later candidate") + + monkeypatch.setattr("pretab.compose.search.clone", reject_clone) + with pytest.raises(InvalidParamError, match=r"(?s)Preprocessor\.task.*target-aware placement.*continuous"): + search.fit(X, pd.Series(y)) + + +def test_search_checks_outer_classification_before_splitting(nonlinear_data): + X, y = nonlinear_data + search = RepresentationSearchCV(LogisticRegression(), methods=["minmax"], task_validation="raise") + + with pytest.raises(InvalidParamError, match=r"(?s)RepresentationSearchCV\.task.*representation search.*continuous"): + search.fit(X, y) + + +@pytest.mark.parametrize("inner_mode", ["warn", "raise"]) +def test_search_keeps_distinct_contracts_after_failed_fit(inner_mode): + values = np.linspace(-2, 2, 18) + X = pd.DataFrame({"value": values}) + target = pd.Series(values**2 + 0.123) + search = RepresentationSearchCV( + LogisticRegression(), + methods=["rbf"], + cv=2, + preprocessor_params={"task_validation": inner_mode, "output_dim": 3}, + task_validation="warn", + ) + exception = InvalidParamError if inner_mode == "raise" else ValueError + match = r"(?s)Preprocessor\.task.*target-aware placement.*continuous" if inner_mode == "raise" else "continuous" + + for _ in range(2): + with pytest.warns(ConfigWarning) as diagnostics, pytest.raises(exception, match=match): + search.fit(X, target) + messages = [str(item.message) for item in diagnostics] + expected_roles = ["target-aware placement"] + if inner_mode == "warn": + expected_roles.append("representation search") + assert len(messages) == len(expected_roles) + for message, role in zip(messages, expected_roles, strict=True): + assert message.startswith(f"RepresentationSearchCV: {role}") + + +class _DiagnosticRecordingSearch(RepresentationSearchCV): + def fit(self, X, y=None, *, groups=None, **fit_params): + self.fit_pid_ = os.getpid() + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ConfigWarning) + super().fit(X, y, groups=groups, **fit_params) + self.task_diagnostics_ = [str(item.message) for item in recorded if item.category is ConfigWarning] + return self + + +@pytest.mark.parametrize("n_jobs", [1, 2], ids=["serial", "worker-process"]) +@pytest.mark.parametrize(("outer_mode", "owner"), [("off", "Preprocessor"), ("warn", "_DiagnosticRecordingSearch")]) +def test_search_owns_placement_diagnostic_once_per_cv_fit(n_jobs, outer_mode, owner): + values = np.linspace(-2, 2, 18) + X = pd.DataFrame({"value": values}) + target = pd.Series(values**2 + 0.123) + search = _DiagnosticRecordingSearch( + LinearRegression(), + methods=["rbf", "relu"], + cv=2, + preprocessor_params={"task": "classification", "task_validation": "warn", "output_dim": 3}, + task_validation=outer_mode, + ) + + result = cross_validate(search, X, target, cv=3, n_jobs=n_jobs, return_estimator=True) + + assert np.isfinite(result["test_score"]).all() + assert len(result["estimator"]) == 3 + for fitted in result["estimator"]: + assert (fitted.fit_pid_ == os.getpid()) == (n_jobs == 1) + assert set(fitted.cv_results_) == {"rbf", "relu"} + assert fitted.best_preprocessor_.task_validation == "warn" + assert len(fitted.task_diagnostics_) == 1 + assert fitted.task_diagnostics_[0].startswith(f"{owner}: target-aware placement") + assert "target type 'continuous'" in fitted.task_diagnostics_[0] + + class _RowRecorder(RegressorMixin, BaseEstimator): """Mean regressor whose ``fit`` records the ``row_id`` fit parameter it gets.""" @@ -388,7 +490,8 @@ def test_classifier_search_places_against_class_labels(class_data): assert set(search.predict(X)) <= {"pos", "neg"} -def test_classifier_search_keeps_an_explicit_task(class_data): +@pytest.mark.parametrize("use_string_labels", [False, True]) +def test_classifier_search_keeps_an_explicit_task(class_data, use_string_labels): X, y = class_data search = RepresentationSearchCV( LogisticRegression(), @@ -396,7 +499,7 @@ def test_classifier_search_keeps_an_explicit_task(class_data): cv=3, preprocessor_params={"task": "regression", "task_validation": "warn"}, task_validation="raise", - ).fit(X, (y == "pos").astype(int)) + ).fit(X, y if use_string_labels else (y == "pos").astype(int)) assert search.best_preprocessor_.task == "regression" assert search.best_preprocessor_.task_validation == "warn" assert search.task_validation == "raise" From bd1825acc218815b365c55d470d75ef7e2bb1492 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 16:14:41 +0100 Subject: [PATCH 58/86] test(core): verify pipeline diagnostics before cross-fit folds --- tests/core/test_cross_fitted.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index f6a48ee..b008560 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -13,6 +13,8 @@ import pytest from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn.model_selection import KFold, StratifiedKFold +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler from pretab import CrossFittedTransformer, LeakageWarning, Preprocessor from pretab.core._typing import TransformerLike @@ -158,6 +160,32 @@ def reject_clone(*args, **kwargs): outer.fit(X, target) +def test_pipeline_placement_diagnostic_is_reused_by_cross_fit_folds(monkeypatch): + X = np.linspace(-2, 2, 12).reshape(-1, 1) + target = X[:, 0] ** 2 + 0.123 + pipeline = make_pipeline( + StandardScaler(), + Preprocessor(numerical_method="rbf", task="classification", task_validation="warn", output_dim=3), + ) + cross_fit = CrossFittedTransformer(pipeline, n_folds=3, shuffle=False) + make_splitter = cross_fit._make_splitter + + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ConfigWarning) + + def check_before_split(): + diagnostics = [item for item in recorded if item.category is ConfigWarning] + assert len(diagnostics) == 1 + assert "target-aware placement uses task='classification'" in str(diagnostics[0].message) + return make_splitter() + + monkeypatch.setattr(cross_fit, "_make_splitter", check_before_split) + result = cross_fit.fit_transform(X, target) + + assert result.shape == (len(target), 3) + assert sum(item.category is ConfigWarning for item in recorded) == 1 + + # --- fit_transform returns the kind of output transform returns (issue #90) --------- From 4f92de2f2e7d14bed2c1346d57ad52a925998eaf Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 16:51:06 +0100 Subject: [PATCH 59/86] test(core): guard strict pipeline diagnostics before cross-fit folds --- tests/core/test_cross_fitted.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index b008560..e73741e 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -12,6 +12,7 @@ import numpy as np import pytest from sklearn.base import BaseEstimator, TransformerMixin, clone +from sklearn.compose import ColumnTransformer from sklearn.model_selection import KFold, StratifiedKFold from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler @@ -186,6 +187,23 @@ def check_before_split(): assert sum(item.category is ConfigWarning for item in recorded) == 1 +def test_pipeline_placement_strict_policy_rejects_before_representation_fit_or_folds(data, monkeypatch): + X, target = data + pipeline = make_pipeline( + StandardScaler(), + Preprocessor(numerical_method="rbf", task="classification", task_validation="raise"), + ) + cross_fit = CrossFittedTransformer(pipeline, n_folds=3) + + def reject_fit_or_split(*args, **kwargs): + pytest.fail("started representation fitting or fold splitting before validating the target") + + monkeypatch.setattr(ColumnTransformer, "fit_transform", reject_fit_or_split) + monkeypatch.setattr(cross_fit, "_make_splitter", reject_fit_or_split) + with pytest.raises(InvalidParamError, match=r"(?s)Preprocessor\.task.*target-aware placement.*continuous"): + cross_fit.fit_transform(X, target) + + # --- fit_transform returns the kind of output transform returns (issue #90) --------- From 142d4cd01b919750d0f0f2b5cb54859c0f5dfe9b Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 17:45:40 +0100 Subject: [PATCH 60/86] test(core): verify task target detection contracts --- .../core_concepts/resolution_and_placement.md | 7 ++ tests/integration/test_preprocessor.py | 65 +++++++++++++++---- 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/docs/core_concepts/resolution_and_placement.md b/docs/core_concepts/resolution_and_placement.md index a3d19e9..aa274af 100644 --- a/docs/core_concepts/resolution_and_placement.md +++ b/docs/core_concepts/resolution_and_placement.md @@ -116,6 +116,13 @@ switching to `target_aware=False` also means passing `placement_strategy="unifor Target-aware placement is a supervised decision and carries leakage considerations. See [Target awareness](target_awareness.md). +```{note} +Few distinct integer values do not make a target categorical. For example, daily order +counts of `0`, `1`, and `2` can be regression outcomes, while the same values can label +three classes. The task diagnostic leaves both interpretations open and never changes +the configured task. +``` + ## Resolution and placement are independent Keeping the two axes separate is what makes the system predictable. You choose a width diff --git a/tests/integration/test_preprocessor.py b/tests/integration/test_preprocessor.py index 967695a..2e806be 100644 --- a/tests/integration/test_preprocessor.py +++ b/tests/integration/test_preprocessor.py @@ -255,17 +255,48 @@ def test_invalid_facade_task_validation_rejected(sample_data, mode): processor.fit(frame, target) -def test_task_diagnostic_requires_active_placement(): +@pytest.mark.parametrize( + ("task", "target", "target_type"), + [ + ("classification", np.linspace(0, 1, 24), "continuous"), + ("regression", np.resize(["first", "second", "third"], 24), "multiclass"), + ], +) +def test_task_diagnostic_requires_active_placement(task, target, target_type): frame = pd.DataFrame({"value": np.linspace(0, 1, 24)}) - target = frame["value"] - processor = Preprocessor(numerical_method="rbf", task="classification", task_validation="raise") - with pytest.raises(InvalidParamError, match=r"target-aware placement.*continuous"): + target = pd.Series(target) + processor = Preprocessor(numerical_method="rbf", task=task, task_validation="raise") + with pytest.raises(InvalidParamError, match=rf"target-aware placement.*task='{task}'.*'{target_type}'"): processor.fit(frame, target) processor.set_params(feature_preprocessing={"value": "minmax"}) processor.fit(frame, target) +@pytest.mark.parametrize( + ("task", "pattern"), + [ + pytest.param("regression", [0, 1], id="binary-counts"), + pytest.param("regression", [0, 1, 2], id="multiclass-counts"), + pytest.param("regression", np.linspace(0.25, 1, 24), id="continuous"), + pytest.param("classification", ["first", "second"], id="binary-labels"), + pytest.param("classification", ["first", "second", "third"], id="multiclass-labels"), + ], +) +def test_task_diagnostic_preserves_valid_placement_outputs(task, pattern): + frame = pd.DataFrame({"value": np.linspace(0, 1, 24)}) + target = pd.Series(np.resize(pattern, len(frame))) + strict = Preprocessor(numerical_method="rbf", task=task, task_validation="raise", output_dim=3, random_state=0) + baseline = clone(strict) + assert isinstance(baseline, Preprocessor) + baseline.set_params(task_validation="off") + + np.testing.assert_array_equal( + strict.fit_transform(frame, target, return_array=True), + baseline.fit_transform(frame, target, return_array=True), + ) + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("fitted", [False, True], ids=["unfitted", "fitted"]) def test_structured_feature_params_survive_fit_and_clone(sample_data, typed, fitted): @@ -769,15 +800,25 @@ def test_transform_accepts_positional_input_of_the_fitted_width(as_list): @pytest.mark.parametrize("method", ["bspline", "mspline", "ispline", "pspline", "naturalspline", "rbf"]) -def test_unsupervised_numerical_method_accepts_a_multi_output_target(method): +@pytest.mark.parametrize("task", ["regression", "classification"]) +def test_unsupervised_numerical_method_accepts_a_multi_output_target(method, task): """The B/M/I splines flattened y even when target_aware=False, so a 2-D target raised an IndexError in fit while the other methods ignored it.""" rng = np.random.default_rng(0) frame = pd.DataFrame({"a": rng.normal(size=200), "b": rng.normal(size=200)}) - Y = np.column_stack([np.sin(frame["a"]), np.cos(frame["b"])]) - options = {"numerical_method": method, "target_aware": False, "placement_strategy": "uniform"} + if task == "classification": + targets = np.column_stack([frame["a"] > 0, frame["b"] > 0]) + else: + targets = np.column_stack([np.sin(frame["a"]), np.cos(frame["b"])]) + options = { + "numerical_method": method, + "target_aware": False, + "placement_strategy": "uniform", + "task": task, + } reference = Preprocessor(**options).fit(frame).transform(frame) - np.testing.assert_array_equal(Preprocessor(**options).fit(frame, Y).transform(frame), reference) + strict = Preprocessor(**options).set_params(task_validation="raise") + np.testing.assert_array_equal(strict.fit(frame, targets).transform(frame), reference) @pytest.mark.parametrize("method", ["bspline", "mspline", "ispline"]) @@ -801,18 +842,20 @@ def test_multi_output_pipeline_imputes_before_unsupervised_spline(method): @pytest.mark.parametrize("method", ["bspline", "naturalspline", "rbf", "ple"]) -def test_target_aware_numerical_method_rejects_a_multi_output_target(method): +@pytest.mark.parametrize("mode", ["off", "raise"]) +def test_target_aware_numerical_method_rejects_a_multi_output_target(method, mode): """Target-aware placement fits one model on one target. A 2-D target was flattened into twice as many values and failed with an unrelated IndexError / broadcasting error; it now raises a clear error pointing to target_aware=False.""" rng = np.random.default_rng(0) frame = pd.DataFrame({"a": rng.normal(size=200), "b": rng.normal(size=200)}) Y = np.column_stack([np.sin(frame["a"]), np.cos(frame["b"])]) + processor = Preprocessor(numerical_method=method, task_validation=mode) with pytest.raises(IncompatibleParamsError, match=r"single target, but y has shape \(200, 2\)"): - Preprocessor(numerical_method=method).fit(frame, Y) + processor.fit(frame, Y) # A column vector is a single target. - Preprocessor(numerical_method=method).fit(frame, Y[:, :1]) + processor.fit(frame, Y[:, :1]) @pytest.mark.parametrize( From bf648e14b9024d0abc74bab657437bd63900c9d5 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 18:56:18 +0100 Subject: [PATCH 61/86] test(core): cover task validation policy matrix --- tests/compose/test_search.py | 26 ++++++++++--- tests/core/test_validation.py | 58 ++++++++++++++++++++++------ tests/integration/test_exceptions.py | 5 ++- 3 files changed, 70 insertions(+), 19 deletions(-) diff --git a/tests/compose/test_search.py b/tests/compose/test_search.py index bf66048..821e946 100644 --- a/tests/compose/test_search.py +++ b/tests/compose/test_search.py @@ -163,20 +163,26 @@ def test_search_preserves_inner_mode_validation(nonlinear_data): search.fit(X, y) -def test_search_checks_later_candidate_before_cloning(nonlinear_data, monkeypatch): +@pytest.mark.parametrize( + ("mode", "exception", "owner"), + [("raise", InvalidParamError, r"Preprocessor\.task"), ("warn", ConfigWarning, "Preprocessor:")], +) +def test_search_checks_later_candidate_before_cloning(nonlinear_data, monkeypatch, mode, exception, owner): X, y = nonlinear_data search = RepresentationSearchCV( LinearRegression(), methods=["minmax", "rbf"], - preprocessor_params={"task": "classification", "task_validation": "raise"}, + preprocessor_params={"task": "classification", "task_validation": mode}, ) def reject_clone(*args, **kwargs): pytest.fail("cloned before checking the later candidate") monkeypatch.setattr("pretab.compose.search.clone", reject_clone) - with pytest.raises(InvalidParamError, match=r"(?s)Preprocessor\.task.*target-aware placement.*continuous"): - search.fit(X, pd.Series(y)) + with warnings.catch_warnings(): + warnings.simplefilter("error", ConfigWarning) + with pytest.raises(exception, match=rf"(?s){owner}.*target-aware placement.*continuous"): + search.fit(X, pd.Series(y)) def test_search_checks_outer_classification_before_splitting(nonlinear_data): @@ -481,11 +487,19 @@ def test_refit_replaces_named_input_metadata(nonlinear_data, class_data, frame_t np.testing.assert_allclose(search.predict(renamed), fresh.predict(renamed)) -def test_classifier_search_places_against_class_labels(class_data): +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_classifier_search_places_against_class_labels(class_data, mode): """A classifier made the search keep task="regression": string labels crashed the target-aware placement and integer labels were treated as a regression target.""" X, y = class_data - search = RepresentationSearchCV(LogisticRegression(), methods=["minmax", "ple"], cv=3, random_state=0).fit(X, y) + search = RepresentationSearchCV( + LogisticRegression(), + methods=["minmax", "ple"], + cv=3, + random_state=0, + preprocessor_params={"task_validation": mode}, + task_validation=mode, + ).fit(X, y) assert search.best_preprocessor_.task == "classification" assert set(search.predict(X)) <= {"pos", "neg"} diff --git a/tests/core/test_validation.py b/tests/core/test_validation.py index a1db221..bed4650 100644 --- a/tests/core/test_validation.py +++ b/tests/core/test_validation.py @@ -1,5 +1,7 @@ """Contracts for shared target inspection, independent of estimator wiring.""" +import warnings + import numpy as np import pandas as pd import pytest @@ -20,21 +22,55 @@ def test_task_validation_rejects_invalid_modes(mode): @pytest.mark.parametrize( - ("target", "task", "observed", "suggested"), + ("values", "inconsistent_task", "observed"), [ - (np.array([0.1, 1.25, 3.5]), "classification", "continuous", "regression"), - (pd.DataFrame({"response": [0.1, 1.25, 3.5]}), "classification", "continuous", "regression"), - (pd.Series(["private-a", "private-b", "private-a"]), "regression", "binary", "classification"), + pytest.param([0.1, 1.25, 3.5], "classification", "continuous", id="continuous"), + pytest.param([[0.1], [1.25], [3.5]], "classification", "continuous", id="column-vector"), + pytest.param(["private-a", "private-b", "private-a"], "regression", "binary", id="binary-text"), + pytest.param(["private-a", "private-b", "private-c"], "regression", "multiclass", id="multiclass-text"), + pytest.param([0, 1, 0], None, None, id="binary-integer"), + pytest.param([0, 1, 2], None, None, id="multiclass-integer"), + pytest.param([True, False, True], None, None, id="boolean"), + pytest.param([0.0, 1.0, 0.0], None, None, id="binary-integral-float"), + pytest.param([0.0, 1.0, 2.0], None, None, id="multiclass-integral-float"), + pytest.param(["0.5", "1e3", "-2"], None, None, id="numeric-text"), + pytest.param([[0, 1], [1, 0], [1, 1]], None, None, id="multilabel"), + pytest.param([[0.1, 1.1], [1.2, 2.3], [4.5, 0.3]], None, None, id="continuous-multioutput"), + pytest.param([0.1, np.nan, 3.5], None, None, id="missing"), + pytest.param(np.array([0, "private-a", 2], dtype=object), None, None, id="mixed-object"), ], ) -@pytest.mark.parametrize(("mode", "exception"), [("warn", ConfigWarning), ("raise", InvalidParamError)]) -def test_task_target_diagnoses_only_clear_mismatches(target, task, observed, suggested, mode, exception): - check = pytest.warns if mode == "warn" else pytest.raises - with check(exception, match=rf"(?s)Example.*placement.*task='{task}'.*'{observed}'.*task='{suggested}'") as caught: +@pytest.mark.parametrize("container", ["numpy", "pandas"]) +@pytest.mark.parametrize("task", ["classification", "regression"]) +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_task_target_policy_matrix(values, inconsistent_task, observed, container, task, mode): + array = np.asarray(values) + target = (pd.Series(array) if array.ndim == 1 else pd.DataFrame(array)) if container == "pandas" else array + original = np.asarray(target).copy() + + def inspect_target(): validation._validate_task_target(target, task=task, mode=mode, estimator="Example", role="placement") - message = str(caught.value if isinstance(caught, pytest.ExceptionInfo) else caught[0].message) - assert "task_validation='off'" in message - assert "private-" not in message + + if mode == "off" or task != inconsistent_task: + with warnings.catch_warnings(): + warnings.simplefilter("error") + inspect_target() + else: + suggested = "regression" if task == "classification" else "classification" + match = rf"(?s)Example.*placement.*task='{task}'.*'{observed}'.*task='{suggested}'" + if mode == "warn": + with pytest.warns(ConfigWarning, match=match) as recorded: + inspect_target() + assert len(recorded) == 1 + message = str(recorded[0].message) + else: + with pytest.raises(InvalidParamError, match=match) as caught: + inspect_target() + message = str(caught.value) + assert "task_validation='off'" in message + assert "private-" not in message + + np.testing.assert_array_equal(np.asarray(target), original) @pytest.mark.parametrize("target", [[0, 1, 2], [True, False], [0.0, 1.0, 2.0], ["0.5", "1e3", "-2"]]) diff --git a/tests/integration/test_exceptions.py b/tests/integration/test_exceptions.py index 3838bc3..ad33cf6 100644 --- a/tests/integration/test_exceptions.py +++ b/tests/integration/test_exceptions.py @@ -249,12 +249,13 @@ def test_preprocessor_unknown_numerical_method(): @pytest.mark.parametrize("method", ["bspline", "naturalspline", "rbf", "ple", "minmax"]) -def test_preprocessor_unknown_task(method): +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_preprocessor_unknown_task(method, mode): """Before, ``task="Regression"`` gave classification knots, or failed deep in scikit-learn.""" df = pd.DataFrame({"a": np.linspace(0, 10, 200)}) y = np.sin(df["a"].to_numpy()) with pytest.raises(InvalidParamError, match=r"Preprocessor\.task = 'Regression' is invalid"): - Preprocessor(numerical_method=method, task="Regression").fit(df, y) + Preprocessor(numerical_method=method, task="Regression", task_validation=mode).fit(df, y) def test_preprocessor_unknown_categorical_method(): From 9ee18ed36725e979be3da6aa8667d83d3a1417f4 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 19:11:26 +0100 Subject: [PATCH 62/86] docs(core): explain task target validation --- docs/api/preprocessor.rst | 14 ++++ docs/api/search_and_cross_fitting.rst | 18 +++++ .../core_concepts/resolution_and_placement.md | 79 ++++++++++++++++++- tests/doc_snippets/test_tutorial_snippets.py | 5 ++ 4 files changed, 112 insertions(+), 4 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 33ad9e1..17150d6 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -13,6 +13,20 @@ configuration, and produces model-ready output with full lineage. Preprocessor +Task and target validation +-------------------------- + +``task`` is ``"regression"`` by default. Set it to ``"classification"`` for class +labels. ``task_validation`` is keyword-only: ``"off"`` (default) skips the +consistency check, ``"warn"`` emits ``ConfigWarning``, and ``"raise"`` raises +``InvalidParamError`` before fitting the representations. + +The check applies to supported single-output targets when a fitted representation +uses ``y`` for placement. It does not infer the task, change the target, or extend +the supported target shapes. Turning it off does not disable task-string validation +or leakage warnings. See :doc:`../core_concepts/resolution_and_placement` for +examples and the limits of the diagnostic. + Representation values --------------------- diff --git a/docs/api/search_and_cross_fitting.rst b/docs/api/search_and_cross_fitting.rst index 6b3f299..7758e67 100644 --- a/docs/api/search_and_cross_fitting.rst +++ b/docs/api/search_and_cross_fitting.rst @@ -12,6 +12,13 @@ Representation search Cross-validate a downstream estimator over candidate numerical methods and refit the best one. +Classifier searches use ``task="classification"`` for preprocessing unless +``preprocessor_params`` specifies ``task``. The search's keyword-only +``task_validation`` checks the downstream classifier or regressor task and active +candidate placement tasks. A candidate's own policy in +``preprocessor_params["task_validation"]`` is independent. Turning one off does +not turn the other off. + .. autosummary:: :toctree: _autosummary :nosignatures: @@ -24,6 +31,17 @@ Cross-fitting Produce out-of-fold training features from a supervised transformer while transforming new data with an all-data model. +The wrapper's keyword-only ``task_validation`` checks its splitter's configured +task. It does not replace the wrapped estimator's policy. If a later pipeline +step needs transformed inputs to determine target use, it checks when those +inputs are available, before training its representations and before any folds. + +Both wrappers accept ``"off"`` (default), ``"warn"`` (``ConfigWarning``), and +``"raise"`` (``InvalidParamError``). Matching checks for the same task, mode, +target and use need not repeat in the folds of one fit. An independent fit checks +again. See :doc:`../core_concepts/resolution_and_placement` for policy selection, +suppression and target-type limits. + .. autosummary:: :toctree: _autosummary :nosignatures: diff --git a/docs/core_concepts/resolution_and_placement.md b/docs/core_concepts/resolution_and_placement.md index aa274af..7746f64 100644 --- a/docs/core_concepts/resolution_and_placement.md +++ b/docs/core_concepts/resolution_and_placement.md @@ -116,13 +116,84 @@ switching to `target_aware=False` also means passing `placement_strategy="unifor Target-aware placement is a supervised decision and carries leakage considerations. See [Target awareness](target_awareness.md). +## Choose a task and validate the target + +Set `task="classification"` when `y` contains class labels, such as whether a home sold. +Use `task="regression"` for numeric outcomes such as sale prices. `Preprocessor` defaults +to regression and never infers the task from `y`. + +Use `task_validation` to catch a clear mismatch before fitting the target-aware representation: + +- `"off"` (default) skips the consistency check. Use it to preserve existing behavior or + silence this diagnostic for an intentional configuration. +- `"warn"` emits a `ConfigWarning` and lets fitting proceed. The estimator may still reject + the target, and a Python warnings-as-errors filter can stop the fit at the warning. +- `"raise"` stops the fit with `InvalidParamError`. Use it when a clear mismatch should + fail the pipeline. + +For example, a classifier for sale status should receive class labels, not sale prices: + +```python +import numpy as np +import pandas as pd + +from pretab import Preprocessor +from pretab.exceptions import InvalidParamError + +homes = pd.DataFrame({"listing_views": np.arange(32)}) +sale_status = np.where(homes["listing_views"] >= 16, "sold", "not sold") +sale_price = np.linspace(120_000.25, 450_000.75, len(homes)) + +pre = Preprocessor( + numerical_method="rbf", output_dim=3, task="classification", task_validation="raise" +) +try: + pre.fit(homes, sale_price) +except InvalidParamError as error: + assert "target type 'continuous'" in str(error) +else: + raise AssertionError("Expected the classifier's continuous target to be rejected") + +pre.fit(homes, sale_status) +``` + +The check also catches nonnumeric class labels used for target-aware regression. It does not +apply to representations that ignore `y`. Missing, multilabel, and other multi-output targets +are left to the usual input checks. Silence does not mean a target shape is supported. + ```{note} -Few distinct integer values do not make a target categorical. For example, daily order -counts of `0`, `1`, and `2` can be regression outcomes, while the same values can label -three classes. The task diagnostic leaves both interpretations open and never changes -the configured task. +Few distinct integer values do not tell you which task to use. Daily order counts of `0`, +`1`, and `2` can be regression outcomes, while the same values can label three classes. +The diagnostic leaves both interpretations open. Numeric-looking strings can also be +ambiguous. It does not rewrite `y` or the configured task. ``` +`RepresentationSearchCV` defaults its preprocessing task to classification when the +downstream estimator is a classifier and no `task` was passed in `preprocessor_params`. +An explicitly supplied preprocessing task takes precedence. Set `task_validation` on +the search and in `preprocessor_params` independently: + +```python +from sklearn.linear_model import LogisticRegression + +from pretab import RepresentationSearchCV + +search = RepresentationSearchCV( + LogisticRegression(), + methods=["rbf"], + cv=3, + preprocessor_params={"output_dim": 3, "task_validation": "raise"}, + task_validation="raise", +).fit(homes, sale_status) +assert search.best_preprocessor_.task == "classification" +``` + +`CrossFittedTransformer` also accepts `task_validation` for its own task, which determines +the splitter. Turning the check off on a wrapper does not turn off its inner estimator's +policy. It also does not disable task-string validation or leakage warnings. A consistency +check answers whether the target fits the task; it does not prevent leakage. Use a pipeline +or cross-fitting to keep target-aware preprocessing within the training data for each split. + ## Resolution and placement are independent Keeping the two axes separate is what makes the system predictable. You choose a width diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index 6298ace..d036d19 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -74,6 +74,11 @@ def isolate_document_state(tmp_path, monkeypatch): "Structured per-feature configuration", id="configuration", ), + pytest.param( + ROOT / "docs" / "core_concepts" / "resolution_and_placement.md", + "Choose a task and validate the target", + id="task-validation", + ), pytest.param( TUTORIALS_DIR / "multivariate_features.md", "Grouped preprocessing with Preprocessor", From 7f69b5a379b557ff5efaf84a25138980253b8ec5 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 23:00:54 +0100 Subject: [PATCH 63/86] test(polars): cover input and output format matrix --- tests/integration/test_polars_input.py | 54 ++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/tests/integration/test_polars_input.py b/tests/integration/test_polars_input.py index f1bf01d..5b8f906 100644 --- a/tests/integration/test_polars_input.py +++ b/tests/integration/test_polars_input.py @@ -197,13 +197,53 @@ def test_grouped_polars_nullable_sources_match_pandas_with_categorical_neighbors assert "missing sources ('visits',)" in str(failure.value) -def test_polars_input_with_polars_output(frames): - _, polars_frame, y = frames - pre = Preprocessor(numerical_method="minmax").set_output(transform="polars").fit(polars_frame, y) - out = pre.transform(polars_frame) - assert isinstance(out, pl.DataFrame) - assert out.columns == list(pre.get_feature_names_out()) - assert out.shape == (polars_frame.height, pre.total_output_dim_) +@pytest.mark.parametrize("container", ["default", "pandas", "polars", "blocks"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_polars_input_output_matrix(frames, container, output_format): + from scipy import sparse + + pandas_frame, polars_frame, y = frames + reference = Preprocessor(numerical_method="minmax", categorical_method="one-hot", output_format="dense") + expected = reference.fit_transform(pandas_frame, y) + assert isinstance(expected, np.ndarray) + names = list(reference.get_feature_names_out()) + + blocks = container == "blocks" + pre = Preprocessor( + numerical_method="minmax", + categorical_method="one-hot", + output_format=output_format, + output_structure="blocks" if blocks else "matrix", + ).set_output(transform="default" if blocks else container) + training = pre.fit_transform(polars_frame, y) + np.testing.assert_array_equal(pre.get_feature_names_out(), names) + reordered = polars_frame.select(polars_frame.columns[::-1]) + for result in (training, pre.transform(reordered)): + if blocks: + assert isinstance(result, dict) + assert list(result) == ["num_income", "num_visits", "cat_rooms", "cat_plan", "cat_city", "cat_flag"] + values = [] + for block, width in zip(result.values(), reference.output_dims_.values(), strict=True): + if output_format == "sparse": + assert isinstance(block, sparse.csr_matrix) + block = block.toarray() + else: + assert isinstance(block, np.ndarray) + assert block.shape == (polars_frame.height, width) + values.append(block) + actual = np.concatenate(values, axis=1) + elif container in ("pandas", "polars"): + assert isinstance(result, pd.DataFrame if container == "pandas" else pl.DataFrame) + assert isinstance(result, _NamedFrame) + assert list(result.columns) == names + actual = np.asarray(result) + elif output_format == "sparse": + assert isinstance(result, sparse.csr_matrix) + actual = result.toarray() + else: + assert isinstance(result, np.ndarray) + actual = result + np.testing.assert_array_equal(actual, expected) @pytest.mark.parametrize("output", ["pandas", "polars"]) From 90c47ae663d0e3708e1020810e9b10957378edea Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 23:19:47 +0100 Subject: [PATCH 64/86] test(polars): cover structured configs and feature groups --- tests/integration/test_polars_input.py | 56 ++++++++++++++++++++------ 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/tests/integration/test_polars_input.py b/tests/integration/test_polars_input.py index 5b8f906..104acfd 100644 --- a/tests/integration/test_polars_input.py +++ b/tests/integration/test_polars_input.py @@ -12,7 +12,7 @@ import pandas as pd import pytest -from pretab import Preprocessor, RepresentationConfig +from pretab import FeatureGroup, Preprocessor, RepresentationConfig from pretab.exceptions import DataWarning, PretabDataError pl = pytest.importorskip("polars") @@ -139,21 +139,34 @@ def test_mixed_structured_inputs_preserve_polars_column_types(frames, typed, out @pytest.mark.parametrize("method", ["tensorspline", "tprs"]) @pytest.mark.parametrize("output_format", ["dense", "sparse", "auto"]) -def test_grouped_polars_nullable_sources_match_pandas_with_categorical_neighbors(frames, method, output_format): +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_structured_and_grouped_polars_inputs_match_pandas(frames, method, output_format, typed): from scipy import sparse pandas_frame, polars_frame, _ = frames - pandas_frame = pandas_frame.astype({"visits": float}) - pandas_frame.loc[7, "visits"] = np.nan - visits = polars_frame["visits"].to_list() - visits[7] = None - polars_frame = polars_frame.with_columns(pl.Series("visits", visits, dtype=pl.Int64)) + pandas_frame = pandas_frame.astype({"visits": float, "flag": object}) + missing_rows = {"visits": 7, "plan": 13, "city": 19, "flag": 23} + nullable_columns = [] + for feature, row in missing_rows.items(): + values = polars_frame[feature].to_list() + values[row] = None + dtype = pl.Enum(["premium", "basic", "unused"]) if feature == "plan" else polars_frame[feature].dtype + nullable_columns.append(pl.Series(feature, values, dtype=dtype)) + pandas_frame.loc[row, feature] = np.nan + polars_frame = polars_frame.with_columns(nullable_columns) original = polars_frame.clone() representation = ( {"method": method, "output_dim": 3, "degree": 2} if method == "tensorspline" else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} ) + group_sources = ["visits", "income"] + groups = ( + [FeatureGroup("location", group_sources, RepresentationConfig.from_dict(representation))] + if typed + else {"location": {"columns": group_sources, "representation": representation}} + ) + overrides = {"method": "one-hot", "params": {"drop": "first"}} options = { "numerical_method": "none", "categorical_method": "one-hot", @@ -162,7 +175,11 @@ def test_grouped_polars_nullable_sources_match_pandas_with_categorical_neighbors "missing_policy": "separate_state", "output_format": output_format, "dtype": np.float32, - "feature_groups": {"location": {"columns": ["visits", "income"], "representation": representation}}, + "feature_groups": groups, + "feature_preprocessing": { + feature: RepresentationConfig.from_dict(overrides) if typed else overrides + for feature in ("flag", "city", "plan") + }, } from_pandas = Preprocessor(**options).fit(pandas_frame) from_polars = Preprocessor(**options).fit(polars_frame) @@ -171,9 +188,21 @@ def test_grouped_polars_nullable_sources_match_pandas_with_categorical_neighbors expected = reference.toarray() if sparse.issparse(reference) else np.asarray(reference) assert from_polars.numerical_features_ == ["income", "visits"] assert from_polars.categorical_features_ == ["rooms", "plan", "city", "flag"] + assert list(from_polars.feature_names_in_) == polars_frame.columns assert from_polars.output_dims_ == from_pandas.output_dims_ assert from_polars.get_feature_lineage() == from_pandas.get_feature_lineage() - np.testing.assert_array_equal(from_polars.get_feature_names_out(), from_pandas.get_feature_names_out()) + names = list(from_polars.get_feature_names_out()) + np.testing.assert_array_equal(names, from_pandas.get_feature_names_out()) + indicators = {} + for feature, width in {"plan": 2, "city": 3, "flag": 2}.items(): + assert from_polars.output_dims_[feature] == width + matches = [ + index + for index, name in enumerate(names) + if name.startswith(f"cat_{feature}__") and name.endswith("__missing") + ] + assert len(matches) == 1 + indicators[feature] = matches[0] for preprocessor, incoming in ( (from_polars, polars_frame.select(polars_frame.columns[::-1])), (from_polars, pandas_frame.iloc[:, ::-1]), @@ -182,15 +211,18 @@ def test_grouped_polars_nullable_sources_match_pandas_with_categorical_neighbors actual = preprocessor.transform(incoming) assert not isinstance(actual, dict) assert sparse.issparse(actual) == (preprocessor.output_format_ == "sparse") - np.testing.assert_array_equal(actual.toarray() if sparse.issparse(actual) else np.asarray(actual), expected) + values = actual.toarray() if sparse.issparse(actual) else np.asarray(actual) + np.testing.assert_array_equal(values, expected) + for feature, index in indicators.items(): + np.testing.assert_array_equal(values[:, index], pandas_frame[feature].isna()) blocks = preprocessor.transform(incoming, return_array=False) assert isinstance(blocks, dict) assert list(blocks) == ["group_location", "cat_rooms", "cat_plan", "cat_city", "cat_flag"] group = blocks["group_location"] values = group.toarray() if sparse.issparse(group) else np.asarray(group) - np.testing.assert_array_equal(values[:, -2:], pandas_frame[["visits", "income"]].isna().astype(np.float32)) + np.testing.assert_array_equal(values[:, -2:], pandas_frame[group_sources].isna().astype(np.float32)) assert polars_frame.equals(original) - assert polars_frame.null_count()["visits"][0] == 1 + assert {feature: polars_frame[feature].null_count() for feature in missing_rows} == dict.fromkeys(missing_rows, 1) with pytest.raises(PretabDataError) as failure: from_polars.transform(polars_frame.drop("visits")) assert "group 'group_location'" in str(failure.value) From 63846dc82c36cfee9484ab6f557942bd09ec9304 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 23:43:38 +0100 Subject: [PATCH 65/86] test(polars): qualify search and cross-fitting --- tests/integration/test_polars_input.py | 80 +++++++++++++++++++++----- 1 file changed, 65 insertions(+), 15 deletions(-) diff --git a/tests/integration/test_polars_input.py b/tests/integration/test_polars_input.py index 104acfd..de09fbe 100644 --- a/tests/integration/test_polars_input.py +++ b/tests/integration/test_polars_input.py @@ -384,17 +384,36 @@ def test_search_converts_a_polars_frame_once(frames_with_one_null_integer): """Rows of a fold without the null would convert to an int column and be detected as categorical, unlike the refit on the whole frame.""" from sklearn.linear_model import Ridge - from sklearn.model_selection import KFold + from sklearn.model_selection import GroupKFold from pretab import RepresentationSearchCV pandas_frame, polars_frame, y = frames_with_one_null_integer + groups = np.arange(len(y)) // 10 + weights = np.linspace(0.25, 2.0, len(y)) + cv = GroupKFold(n_splits=5) def search(X): - params = {"cv": KFold(5, shuffle=True, random_state=0), "random_state": 0} - return RepresentationSearchCV(Ridge(), ["minmax"], **params).fit(X, y) + searcher = RepresentationSearchCV(Ridge(), ["minmax"], random_state=0) + searcher.set_params(cv=cv) + return searcher.fit(X, y, groups=groups, sample_weight=weights) - assert search(polars_frame).cv_results_ == pytest.approx(search(pandas_frame).cv_results_) + from_pandas, from_polars = search(pandas_frame), search(polars_frame) + scores = [] + for train, held_out in cv.split(pandas_frame, y, groups): + pre = Preprocessor(numerical_method="minmax", random_state=0) + training = pre.fit_transform(pandas_frame.iloc[train], y[train], return_array=True) + validation = pre.transform(pandas_frame.iloc[held_out], return_array=True) + model = Ridge().fit(training, y[train], sample_weight=weights[train]) + scores.append(model.score(validation, y[held_out])) + expected_scores = {"minmax": float(np.mean(scores))} + assert from_polars.cv_results_ == pytest.approx(expected_scores) + assert from_pandas.cv_results_ == pytest.approx(expected_scores) + np.testing.assert_array_equal(from_polars.feature_names_in_, ["x", "kids"]) + full = from_pandas.best_preprocessor_.transform(pandas_frame, return_array=True) + expected = Ridge().fit(full, y, sample_weight=weights).predict(full) + reordered = polars_frame.reverse().select(polars_frame.columns[::-1]) + np.testing.assert_allclose(from_polars.predict(reordered), expected[::-1]) @pytest.mark.parametrize("method", ["minmax", "ple", "bspline"]) @@ -436,14 +455,18 @@ def cross_fit(X): from_pandas, expected = cross_fit(pandas_frame) from_polars, actual = cross_fit(polars_frame) np.testing.assert_allclose(actual, expected) - np.testing.assert_allclose(from_polars.transform(polars_frame), from_pandas.transform(pandas_frame)) + reordered = polars_frame.reverse().select(polars_frame.columns[::-1]) + np.testing.assert_allclose(from_polars.transform(reordered), np.asarray(from_pandas.transform(pandas_frame))[::-1]) np.testing.assert_array_equal(from_polars.get_feature_names_out(), from_pandas.get_feature_names_out()) assert from_polars.get_representation_spec().input_features == ("x", "kids") @pytest.mark.parametrize("method", ["ple", "bspline", "rbf"]) @pytest.mark.parametrize("policy", ["impute_with_indicator", "separate_state"]) -def test_cross_fitting_keeps_single_missing_value_indicators_for_polars(method, policy): +@pytest.mark.parametrize("container", ["dense", "sparse", "auto", "pandas", "polars"]) +def test_cross_fitting_keeps_single_missing_value_indicators_for_polars(method, policy, container): + from scipy import sparse + from pretab import CrossFittedTransformer rng = np.random.default_rng(0) @@ -454,17 +477,44 @@ def test_cross_fitting_keeps_single_missing_value_indicators_for_polars(method, y = rng.normal(size=len(X)) def cross_fit(frame): - wrapped = CrossFittedTransformer( - Preprocessor(numerical_method=method, missing_policy=policy, output_format="dense", random_state=0), - n_folds=5, + pre = Preprocessor( + numerical_method=method, + missing_policy=policy, + output_format=container if container in ("sparse", "auto") else "dense", random_state=0, ) + if container in ("pandas", "polars"): + pre.set_output(transform=container) + wrapped = CrossFittedTransformer(pre, n_folds=5, random_state=0) return wrapped, wrapped.fit_transform(frame, y) - reference, expected = cross_fit(pandas_frame) - wrapped, actual = cross_fit(polars_frame) - assert actual.shape == wrapped.transform(polars_frame).shape == (len(X), 8) - np.testing.assert_allclose(actual, expected) - np.testing.assert_array_equal(actual[:, -1], np.isnan(X).astype(float)) - np.testing.assert_array_equal(wrapped.get_feature_names_out(), reference.get_feature_names_out()) + reference, expected_oof = cross_fit(pandas_frame) + wrapped, oof = cross_fit(polars_frame) + expected_full = reference.transform(pandas_frame) + full = wrapped.transform(polars_frame.reverse()) + assert type(oof) is type(full) is type(expected_oof) is type(expected_full) + names = list(wrapped.get_feature_names_out()) + np.testing.assert_array_equal(names, reference.get_feature_names_out()) + + def values(result): + if container in ("pandas", "polars"): + assert isinstance(result, pd.DataFrame if container == "pandas" else pl.DataFrame) + assert isinstance(result, _NamedFrame) + assert list(result.columns) == names + if isinstance(result, pd.DataFrame): + pd.testing.assert_index_equal(result.index, pd.RangeIndex(len(X))) + elif container == "sparse" or sparse.issparse(result): + assert container in ("sparse", "auto") + assert isinstance(result, sparse.csr_matrix) + return result.toarray() + else: + assert isinstance(result, np.ndarray) + return np.asarray(result) + + actual_oof, actual_full = values(oof), values(full) + assert actual_oof.shape == actual_full.shape == (len(X), 8) + np.testing.assert_allclose(actual_oof, values(expected_oof)) + np.testing.assert_allclose(actual_full, values(expected_full)[::-1]) + np.testing.assert_array_equal(actual_oof[:, -1], np.isnan(X)) + np.testing.assert_array_equal(actual_full[:, -1], np.isnan(X)[::-1]) assert polars_frame.null_count()["x"][0] == 1 From 92113d90f8eb4a1ae23e8c08e53b0e261d14e93d Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sat, 21 Nov 2026 23:52:01 +0100 Subject: [PATCH 66/86] fix(compose): check Polars dependency when restoring specs --- pretab/compose/output.py | 19 ++++++---- pretab/compose/serialize.py | 4 ++ pretab/preprocessor.py | 5 +++ tests/integration/test_serialization.py | 49 ++++++++++++++++++++++++- 4 files changed, 69 insertions(+), 8 deletions(-) diff --git a/pretab/compose/output.py b/pretab/compose/output.py index 1868cf5..6974324 100644 --- a/pretab/compose/output.py +++ b/pretab/compose/output.py @@ -137,6 +137,17 @@ def compute_output_report(array, output_format, *, threshold=_SPARSE_AUTO_THRESH return fmt, report +def _require_polars(): + try: + import polars as pl # type: ignore + except ImportError as exc: + raise OptionalDependencyError( + "set_output(transform='polars') requires the optional 'polars' package. " + "Install it with `pip install polars`." + ) from exc + return pl + + def to_dataframe_output(array, columns, container, *, index=None): """Wrap a dense stacked array in a pandas or polars DataFrame. @@ -167,13 +178,7 @@ def to_dataframe_output(array, columns, container, *, index=None): import pandas as pd return pd.DataFrame(array, index=index, columns=pd.Index(columns)) - try: - import polars as pl # type: ignore - except ImportError as exc: # pragma: no cover - exercised only without polars - raise OptionalDependencyError( - "set_output(transform='polars') requires the optional 'polars' package. " - "Install it with `pip install polars`." - ) from exc + pl = _require_polars() return pl.from_numpy(array, schema=columns) diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 0b0a69b..35272c9 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -41,6 +41,7 @@ from ..preprocessing.floats import NoTransformer, ToFloatTransformer from .config import FeatureGroup, RepresentationConfig from .inspection import _iter_fitted_blocks, representation_leaf +from .output import _require_polars from .registry import TransformerSpec SCHEMA_VERSION = 1 @@ -400,5 +401,8 @@ def preprocessor_from_spec(data: dict): obj.__dict__.update(_decode_mapping(data["state"])) obj.__dict__.setdefault("feature_groups", None) obj.__dict__.setdefault("task_validation", "off") + output_config = getattr(obj, "_sklearn_output_config", None) + if isinstance(output_config, dict) and output_config.get("transform") == "polars": + _require_polars() _repair_legacy_sparse_feature_counts(obj) return obj diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 1378c19..c59b3d2 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -1558,6 +1558,11 @@ def from_spec(cls, source) -> "Preprocessor": Preprocessor A fitted preprocessor equivalent to the one that produced the spec; ``transform`` reproduces the original output bit-for-bit. + + Raises + ------ + OptionalDependencyError + If the spec explicitly requests Polars output and Polars is unavailable. """ if isinstance(source, dict): data = source diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index 9435391..d095cab 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -9,18 +9,20 @@ import json import math import pickle +import sys from typing import cast import numpy as np import pandas as pd import pytest +from sklearn import config_context from sklearn.base import clone from pretab import Preprocessor, PretabSerializationError, RepresentationConfig, RepresentationPolicy from pretab.compose.registry import TransformerSpec from pretab.compose.serialize import SCHEMA_VERSION, _decode, _encode, _encode_mapping from pretab.core.parameters import UNSET -from pretab.exceptions import InvalidParamError +from pretab.exceptions import InvalidParamError, OptionalDependencyError from pretab.preprocessing.floats import NoTransformer, ToFloatTransformer @@ -305,6 +307,51 @@ def test_round_trip_preserves_dtype_and_output_format(frame, target): assert restored.output_format == "dense" +@pytest.mark.parametrize("transform", [None, "default", "pandas"], ids=["unset", "default", "pandas"]) +def test_portable_spec_restores_without_polars(frame, monkeypatch, transform): + fitted = Preprocessor(numerical_method="minmax").fit(frame).set_output(transform=transform) + expected = fitted.transform(frame) + spec = fitted.to_spec() + with monkeypatch.context() as missing: + missing.setitem(sys.modules, "polars", None) + with config_context(transform_output="polars"): + restored = Preprocessor.from_spec(spec) + + actual = restored.transform(frame) + assert type(actual) is type(expected) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), fitted.get_feature_names_out()) + + +@pytest.mark.parametrize("as_file", [False, True], ids=["dict", "file"]) +def test_spec_with_polars_output_requires_polars_at_restore(frame, monkeypatch, tmp_path, as_file): + fitted = Preprocessor(numerical_method="minmax").fit(frame).set_output(transform="polars") + path = tmp_path / "preprocessor.json" + spec = fitted.to_spec(path if as_file else None) + monkeypatch.setitem(sys.modules, "polars", None) + + with pytest.raises(OptionalDependencyError, match=r"set_output.*requires.*polars.*pip install polars"): + Preprocessor.from_spec(path if as_file else spec) + + +@pytest.mark.parametrize("transform", ["default", "polars"]) +def test_spec_round_trip_after_fit_on_polars(frame, monkeypatch, transform): + polars = pytest.importorskip("polars") + polars_frame = polars.DataFrame(frame.to_dict(orient="list")) + fitted = Preprocessor(numerical_method="minmax").fit(polars_frame).set_output(transform=transform) + expected = fitted.transform(frame) + spec = fitted.to_spec() + with monkeypatch.context() as missing: + if transform == "default": + missing.setitem(sys.modules, "polars", None) + restored = Preprocessor.from_spec(spec) + + actual = restored.transform(frame) + assert isinstance(actual, polars.DataFrame if transform == "polars" else np.ndarray) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), fitted.get_feature_names_out()) + + def test_round_trip_preserves_policy(frame, target): p = Preprocessor( numerical_method="bspline", From 8037287df24f3f07d0502377250fe5e51dd0e9a3 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 00:12:29 +0100 Subject: [PATCH 67/86] docs(polars): clarify DeepTab support boundary --- docs/tutorials/multivariate_features.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/tutorials/multivariate_features.md b/docs/tutorials/multivariate_features.md index e8002d6..1383855 100644 --- a/docs/tutorials/multivariate_features.md +++ b/docs/tutorials/multivariate_features.md @@ -202,6 +202,10 @@ PreTab's dense block-output boundary. It does not construct or fit a DeepTab model, and `block_widths` is not a DeepTab configuration object. ```{note} +PreTab accepts eager `polars.DataFrame` inputs, but end-to-end DeepTab training +and prediction with Polars are not supported by this integration. Use an input +format documented by your version of DeepTab. + Dictionary output is not supported for out-of-fold assembly by `CrossFittedTransformer`. Use matrix output for that training workflow. An ordinary all-data `fit` followed by a dictionary `transform` is not a substitute From 3f347f335ab2aa0fa546198169bba578d580b63a Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 00:38:04 +0100 Subject: [PATCH 68/86] docs(polars): document input support and pandas parity --- docs/core_concepts/configuration.md | 51 +++++++++++++++++++- tests/doc_snippets/test_tutorial_snippets.py | 7 +++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index 7c0e18a..f58b654 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -23,6 +23,19 @@ pre = Preprocessor( The defaults are `numerical_method="ple"` and `categorical_method="int"`. The full list of strategy strings is in the [representation comparison](../representations/comparison_table.md). +## Supported inputs + +| Input | Column matching | Extra for input | +| ---------------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------- | +| `pandas.DataFrame` | By column label | None | +| `dict` of columns | By dictionary key | None | +| 2D `numpy.ndarray` or list of rows | By position; names such as `feature_0` are generated at fit | None | +| Eager `polars.DataFrame` | By column name | [Polars extra](../getting_started/installation.md); PyArrow is not required | +| `polars.LazyFrame` | Not supported; call `collect()` to get an eager frame | Not applicable | + +Named inputs match by label after fitting on named data. When either training +or inference uses a positional input, keep column order and width consistent. + ## NumPy array input `Preprocessor` also accepts a plain `numpy.ndarray`, not just a `DataFrame`. Columns are @@ -76,17 +89,53 @@ float, as in pandas), and `String` (`Utf8` on older Polars), `Categorical`, `Enu categorical. Polars nulls become missing values, so imputation and `missing_policy` treat them like `NaN` in a pandas frame. The conversion does not need `pyarrow`. +### Check parity with pandas + +Build the equivalent Polars frame from a dictionary of lists rather than using +`pl.from_pandas`, so the example works without PyArrow. The same configuration +produces identical features for this data, even if you reorder named columns at transform time. + +```python +import numpy as np +import pandas as pd +import polars as pl +from pretab import Preprocessor + +X = pd.DataFrame({ + "age": [25.0, None, 47.0, 33.0], + "city": ["Paris", "Rome", "Paris", "Rome"], + "active": [True, False, True, False], +}) +X_polars = pl.DataFrame(X.to_dict(orient="list")) +options = { + "numerical_method": "minmax", + "categorical_method": "one-hot", + "missing_policy": "impute_with_indicator", +} +from_pandas = Preprocessor(**options).fit(X) +from_polars = Preprocessor(**options).fit(X_polars) + +np.testing.assert_array_equal(from_polars.get_feature_names_out(), from_pandas.get_feature_names_out()) +np.testing.assert_array_equal( + from_polars.transform(X_polars.select("active", "city", "age")), + from_pandas.transform(X), +) +``` + +### Pass Polars through a scikit-learn pipeline + ```python import polars as pl from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline +from pretab import Preprocessor X = pl.DataFrame({"age": [25.0, None, 47.0, 33.0], "income": [3.1e4, 5.2e4, None, 4.4e4]}) y = [0.0, 1.0, 1.0, 0.0] pipe = Pipeline([("impute", SimpleImputer()), ("pretab", Preprocessor(numerical_method="minmax"))]) pipe.set_output(transform="polars") -pipe.fit_transform(X, y) # a polars.DataFrame with columns num_age, num_income +assert isinstance(pipe.fit_transform(X, y), pl.DataFrame) ``` ## Per-feature overrides diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index d036d19..6e05ce3 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -9,6 +9,7 @@ import json import re +from importlib.util import find_spec from pathlib import Path import pytest @@ -74,6 +75,12 @@ def isolate_document_state(tmp_path, monkeypatch): "Structured per-feature configuration", id="configuration", ), + pytest.param( + ROOT / "docs" / "core_concepts" / "configuration.md", + "Polars DataFrame input", + id="polars-input", + marks=pytest.mark.skipif(find_spec("polars") is None, reason="polars is not installed"), + ), pytest.param( ROOT / "docs" / "core_concepts" / "resolution_and_placement.md", "Choose a task and validate the target", From b0060c71c64febc7122ff6ae845688777b2fdc86 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 00:50:43 +0100 Subject: [PATCH 69/86] feat(compose): serialize typed penalty values --- pretab/compose/serialize.py | 18 +++++++ tests/integration/test_serialization.py | 72 ++++++++++++++++++++++++- 2 files changed, 89 insertions(+), 1 deletion(-) diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 35272c9..0df3050 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -37,6 +37,7 @@ from ..core.policy import RepresentationPolicy from ..core.representation import FeatureLineage, RepresentationSpec from ..exceptions import PretabSerializationError +from ..expansion.spline.penalty import PenaltySpec, _copy_provenance from ..placement.base import PlacementResult from ..preprocessing.floats import NoTransformer, ToFloatTransformer from .config import FeatureGroup, RepresentationConfig @@ -69,6 +70,7 @@ TransformerSpec, RepresentationConfig, FeatureGroup, + PenaltySpec, } ) @@ -167,6 +169,22 @@ def _encode(obj): if type(obj) is RepresentationConfig: fields = {key: _encode(value) for key, value in obj.to_dict().items()} return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} + if type(obj) is PenaltySpec: + fields = _encode_mapping( + { + "matrix": obj.matrix, + "kind": obj.kind, + "order": obj.order, + "axis": obj.axis, + "coordinate_system": obj.coordinate_system, + "coefficient_names": obj.coefficient_names, + "coefficient_indices": obj.coefficient_indices, + "atol": obj.atol, + "rtol": obj.rtol, + "provenance": _copy_provenance(obj.provenance), + } + ) + return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} if dataclasses.is_dataclass(obj) and not isinstance(obj, type): fields = {f.name: _encode(getattr(obj, f.name)) for f in dataclasses.fields(obj)} return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index d095cab..e063364 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -18,7 +18,14 @@ from sklearn import config_context from sklearn.base import clone -from pretab import Preprocessor, PretabSerializationError, RepresentationConfig, RepresentationPolicy +from pretab import ( + FeatureGroup, + PenaltySpec, + Preprocessor, + PretabSerializationError, + RepresentationConfig, + RepresentationPolicy, +) from pretab.compose.registry import TransformerSpec from pretab.compose.serialize import SCHEMA_VERSION, _decode, _encode, _encode_mapping from pretab.core.parameters import UNSET @@ -609,6 +616,69 @@ def test_representation_config_decoder_runs_value_validation(fields, constraint) _decode(payload) +def test_feature_group_codec_preserves_order_and_nested_config(): + value = FeatureGroup("joint", (10, "first"), RepresentationConfig("tensorspline", output_dim=3)) + + restored = _decode(json.loads(json.dumps(_encode(value), allow_nan=False))) + + assert type(restored) is FeatureGroup + assert restored == value + assert restored.columns == (10, "first") + + +def test_penalty_spec_codec_preserves_exact_immutable_values(): + value = PenaltySpec( + matrix=[[-0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, -1.0, 1.0]], + kind="coefficient_difference", + order=1, + axis=("age",), + coordinate_system="basis_coefficients", + coefficient_names=("bias", "basis_0", "basis_1"), + coefficient_indices=(3, 4, 5), + atol=1e-12, + rtol=1e-9, + provenance={"source": {"details": [{"label": "age", "verified": True}, None]}}, + ) + + payload = json.loads(json.dumps(_encode(value), allow_nan=False)) + fields = payload["__dataclass__"]["fields"] + assert "__ndarray__" in fields["matrix"] + assert {"_matrix_bytes", "rank", "nullity"}.isdisjoint(fields) + restored = _decode(payload) + + assert type(restored) is PenaltySpec + assert restored == value + assert restored.matrix.dtype == np.float64 + assert restored.matrix.tobytes() == value.matrix.tobytes() + assert (restored.rank, restored.nullity) == (1, 2) + with pytest.raises(ValueError, match="WRITEABLE"): + restored.matrix.setflags(write=True) + with pytest.raises(TypeError): + restored.provenance["source"]["details"][0]["label"] = "changed" + + +def test_penalty_spec_decoder_runs_matrix_validation(): + payload = { + "__dataclass__": { + "class": "pretab.expansion.spline.penalty:PenaltySpec", + "fields": _encode_mapping( + { + "matrix": np.array([[-1.0]]), + "kind": "curvature", + "order": None, + "axis": ("age",), + "coordinate_system": "basis_coefficients", + "coefficient_names": ("basis_0",), + "coefficient_indices": (0,), + } + ), + } + } + + with pytest.raises(InvalidParamError, match="positive semidefinite"): + _decode(payload) + + @pytest.mark.parametrize( ("group_fields", "expected"), [ From 98a0d87a777debe053eaf1e560da831dc01e8300 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 01:24:03 +0100 Subject: [PATCH 70/86] feat(compose): include fitted metadata in specs --- pretab/compose/serialize.py | 46 +++++++++-- pretab/expansion/spline/p_spline.py | 6 +- pretab/preprocessor.py | 50 +++++++---- tests/integration/test_serialization.py | 105 +++++++++++++++++++++++- 4 files changed, 182 insertions(+), 25 deletions(-) diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 0df3050..5d5ef59 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -37,13 +37,14 @@ from ..core.policy import RepresentationPolicy from ..core.representation import FeatureLineage, RepresentationSpec from ..exceptions import PretabSerializationError +from ..expansion.spline.p_spline import PSplineTransformer from ..expansion.spline.penalty import PenaltySpec, _copy_provenance from ..placement.base import PlacementResult from ..preprocessing.floats import NoTransformer, ToFloatTransformer from .config import FeatureGroup, RepresentationConfig from .inspection import _iter_fitted_blocks, representation_leaf from .output import _require_polars -from .registry import TransformerSpec +from .registry import TRANSFORMER_REGISTRY, TransformerSpec SCHEMA_VERSION = 1 @@ -321,7 +322,27 @@ def _library_versions() -> dict: } -def _representation_summary(preprocessor) -> list: +def _penalty_summaries(leaf) -> list[dict]: + scope = next( + ( + spec.arity + for spec in TRANSFORMER_REGISTRY.values() + if spec.typed_penalty and spec.transformer_cls is type(leaf) + ), + None, + ) + if scope is None: + return [] + if scope == "multivariate": + penalties = leaf.get_penalty_specs() + else: + if isinstance(leaf, PSplineTransformer) and leaf._has_legacy_only_penalty(): + return [] + penalties = (leaf.get_penalty_spec(feature_index=index) for index in range(leaf.n_features_in_)) + return [penalty.to_summary() for penalty in penalties] + + +def _representation_summary(preprocessor, *, include_penalties: bool = False) -> list: """Declarative per-representation summary (family/columns/locations). One entry per block whose representation ends in a PreTab transformer, built from its @@ -359,22 +380,35 @@ def _representation_summary(preprocessor) -> list: entry["group_id"] = block.group_id entry["dimension"] = span.stop - span.start entry["output_slice"] = [span.start, span.stop] + if include_penalties and (penalties := _penalty_summaries(leaf)): + entry["penalties"] = penalties summary.append(entry) return summary -def preprocessor_to_spec(preprocessor) -> dict: +def preprocessor_to_spec(preprocessor, *, include_fitted_metadata: bool = True) -> dict: """Serialize a fitted preprocessor into a portable, versioned spec dictionary.""" check_is_fitted(preprocessor) - return { + state = vars(preprocessor) + if not include_fitted_metadata: + state = {key: value for key, value in state.items() if key != "_fit_config_"} + has_fit_config = "_fit_config_" in state + spec = { "schema_version": SCHEMA_VERSION, "pretab_version": _PRETAB_VERSION, "library_versions": _library_versions(), "params": _json_safe(preprocessor.get_params(deep=False)), "feature_names_out": [str(name) for name in preprocessor.get_feature_names_out()], - "representations": _representation_summary(preprocessor), - "state": _encode_mapping(vars(preprocessor)), + "representations": _representation_summary(preprocessor, include_penalties=has_fit_config), + "state": _encode_mapping(state), } + if include_fitted_metadata: + if has_fit_config: + spec["resolved_config"] = _json_safe(state["_fit_config_"]) + spec["output_dims"] = _json_safe(preprocessor.output_dims_) + spec["total_output_dim"] = preprocessor.total_output_dim_ + spec["feature_lineage"] = _json_safe([item.to_dict() for item in preprocessor.get_feature_lineage()]) + return spec def check_spec_schema(data: dict) -> None: diff --git a/pretab/expansion/spline/p_spline.py b/pretab/expansion/spline/p_spline.py index 006e7f7..fe521b0 100644 --- a/pretab/expansion/spline/p_spline.py +++ b/pretab/expansion/spline/p_spline.py @@ -248,6 +248,10 @@ def get_penalty_matrix(self, feature_index=0): check_is_fitted(self, "penalty_") return self.penalty_[feature_index] + def _has_legacy_only_penalty(self) -> bool: + fitted = getattr(self, "_penalty_fit_", None) + return fitted is not None and fitted[0] not in (1, 2) + def get_penalty_spec( self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | np.integer[Any] | None = None ) -> PenaltySpec: @@ -273,7 +277,7 @@ def get_penalty_spec( if fitted is None: raise invalid_param_error(estimator, "get_penalty_spec", None, "refit to record the fitted penalty order") order, include_bias = fitted - if order not in (1, 2): + if self._has_legacy_only_penalty(): raise invalid_param_error( estimator, "diff_order", diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index c59b3d2..be0be6f 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -668,6 +668,7 @@ def fit(self, X, y=None, embeddings=None): apply_constant_policy(numeric_values, self.policy_, estimator=self) self._validate_fit_output() + fit_summary = self._resolved_config_summary(resolved, config, numerical_features=numerical_features) # Ask ColumnTransformer to assemble the representation in the requested # container whenever its component outputs permit it. In particular, @@ -679,6 +680,7 @@ def fit(self, X, y=None, embeddings=None): categorical_features, sparse_threshold=sparse_threshold, ) + vars(self).pop("_fit_config_", None) # The Preprocessor wraps its own output (set_output / output_format), so the # internal steps always produce plain arrays. Otherwise a global # ``sklearn.set_config(transform_output="pandas")`` reaches them and the @@ -732,6 +734,7 @@ def fit(self, X, y=None, embeddings=None): if verbose >= 3: self._log_internal_decisions() + self._fit_config_ = fit_summary return self def transform(self, X, embeddings=None, return_array=None): @@ -990,22 +993,29 @@ def get_resolved_config(self): """ resolved = self._resolved_params() if resolved["feature_preprocessing"] or resolved["feature_groups"] is not None: - config = PreprocessorConfig.from_params( - **{field.name: resolved[field.name] for field in fields(PreprocessorConfig)} - ) - if resolved["feature_preprocessing"]: - resolved["feature_preprocessing"] = { - feature: config.representation_for(feature).to_dict() for feature in config.feature_preprocessing + return self._resolved_config_summary(resolved, self._fit_config(resolved)) + return copy.deepcopy(resolved) + + @staticmethod + def _resolved_config_summary(resolved, config: PreprocessorConfig, *, numerical_features=None): + resolved = dict(resolved) + if resolved["feature_preprocessing"]: + numerical = None if numerical_features is None else set(numerical_features) + resolved["feature_preprocessing"] = { + feature: config.representation_for( + feature, is_numerical=None if numerical is None else feature in numerical + ).to_dict() + for feature in config.feature_preprocessing + } + if resolved["feature_groups"] is not None: + resolved["feature_groups"] = [ + { + "name": group.name, + "columns": list(group.columns), + "representation": config.group_representation_for(group).to_dict(), } - if resolved["feature_groups"] is not None: - resolved["feature_groups"] = [ - { - "name": group.name, - "columns": list(group.columns), - "representation": config.group_representation_for(group).to_dict(), - } - for group in config.feature_groups - ] + for group in config.feature_groups + ] return copy.deepcopy(resolved) def get_feature_names_out(self, input_features=None): @@ -1511,6 +1521,12 @@ def to_spec(self, path=None) -> dict: Only load specs from trusted sources. Third-party representations and pretrained language models are not supported by this serializer. + ``params`` describes the current constructor request. When recorded at + fit, ``resolved_config`` describes the settings used for the fitted + graph. Output dimensions and lineage describe fitted output, including + indicator columns. Supported fitted penalties are summarized without + their matrices; the encoded ``state`` remains the source for replay. + Parameters ---------- path : str, os.PathLike, or None, default=None @@ -1579,7 +1595,7 @@ def from_spec(cls, source) -> "Preprocessor": # --- Fingerprint & reproducibility --- def _canonical_spec(self) -> dict: """Deterministic subset of the spec used for fingerprinting.""" - spec = preprocessor_to_spec(self) + spec = preprocessor_to_spec(self, include_fitted_metadata=False) # Runtime reports and advisory lifecycle flags do not change the fitted # representation. Keep them in serialization, but out of its identity. state = { @@ -1632,7 +1648,7 @@ def reproducibility_report(self) -> dict: Group metadata comes from the fitted graph, not current requests. """ check_is_fitted(self) - spec = preprocessor_to_spec(self) + spec = preprocessor_to_spec(self, include_fitted_metadata=False) representations = { entry.get("group_id", entry["columns"][0]): entry.get("family") for entry in spec["representations"] diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index e063364..f23e223 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -59,6 +59,7 @@ def test_legacy_state_restores_constructor_defaults(frame, restore_format): if restore_format == "pickle": del processor.feature_groups del processor.task_validation + del processor._fit_config_ restored = pickle.loads(pickle.dumps(processor)) # noqa: S301 else: spec = processor.to_spec() @@ -66,6 +67,9 @@ def test_legacy_state_restores_constructor_defaults(frame, restore_format): del spec["params"]["feature_groups"] del spec["state"]["task_validation"] del spec["params"]["task_validation"] + del spec["state"]["_fit_config_"] + for key in ("resolved_config", "output_dims", "total_output_dim", "feature_lineage"): + del spec[key] restored = Preprocessor.from_spec(spec) assert restored.get_params(deep=False)["feature_groups"] is None @@ -73,6 +77,7 @@ def test_legacy_state_restores_constructor_defaults(frame, restore_format): assert restored.get_resolved_config()["feature_groups"] is None assert restored.get_resolved_config()["task_validation"] == "off" assert restored.fingerprint_ == fingerprint + assert "resolved_config" not in restored.to_spec() np.testing.assert_array_equal(restored.transform(frame), expected) copied = clone(restored) assert isinstance(copied, Preprocessor) @@ -263,6 +268,102 @@ def test_representation_summary_present(frame, target): assert "rbf" in families +def test_spec_content_describes_the_fit_after_requests_change(frame): + X = frame.assign(extra=np.linspace(-2, 2, len(frame))) + override = {"method": "RBF", "output_dim": 3, "gamma": 0.5} + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="quantile", + feature_preprocessing={"extra": override}, + feature_groups=[FeatureGroup("joint", ("b", "a"), RepresentationConfig("tensorspline", output_dim=4))], + ).fit(X) + override["gamma"] = 1.5 + processor.set_params(numerical_method="none", feature_groups=None) + + spec = json.loads(json.dumps(processor.to_spec(), allow_nan=False)) + + assert spec["params"]["numerical_method"] == "none" + assert spec["params"]["feature_preprocessing"]["extra"]["gamma"] == 1.5 + assert spec["params"]["feature_groups"] is None + resolved = spec["resolved_config"] + assert resolved["numerical_method"] == "minmax" + extra = resolved["feature_preprocessing"]["extra"] + assert (extra["method"], extra["output_dim"], extra["params"]["gamma"]) == ("rbf", 3, 0.5) + group = resolved["feature_groups"][0] + assert (group["name"], group["columns"], group["representation"]["method"]) == ("joint", ["b", "a"], "tensorspline") + assert spec["output_dims"] == processor.output_dims_ + assert spec["total_output_dim"] == processor.total_output_dim_ + assert spec["feature_lineage"] == [item.to_dict() for item in processor.get_feature_lineage()] + assert [item["source_features"] for item in spec["feature_lineage"] if item.get("group_id")] == [["b", "a"]] * spec[ + "output_dims" + ]["group_joint"] + + restored = Preprocessor.from_spec(spec) + assert restored.to_spec()["resolved_config"] == resolved + np.testing.assert_array_equal(restored.transform(X), processor.transform(X)) + + processor.fit(X) + refit_spec = processor.to_spec() + assert refit_spec["resolved_config"]["feature_groups"] is None + assert refit_spec["resolved_config"]["feature_preprocessing"]["extra"]["params"]["gamma"] == 1.5 + assert "group_joint" not in refit_spec["output_dims"] + + +@pytest.mark.parametrize("group_method", ["tensorspline", "tprs"]) +def test_spec_content_includes_only_supported_penalty_summaries(frame, group_method): + X = frame.assign(extra=np.linspace(-2, 2, len(frame))) + X.loc[::7, "b"] = np.nan + width_option = "output_dim" if group_method == "tensorspline" else "n_components" + processor = Preprocessor( + numerical_method="pspline", + output_dim=7, + target_aware=False, + placement_strategy="uniform", + feature_groups={"joint": {"columns": ["b", "a"], "representation": {"method": group_method, width_option: 4}}}, + missing_policy="separate_state", + ).fit(X) + + spec = json.loads(json.dumps(processor.to_spec(), allow_nan=False)) + group = next(entry for entry in spec["representations"] if entry.get("group_id") == "group_joint") + single = next(entry for entry in spec["representations"] if entry["columns"] == ["extra"]) + (penalty,) = single["penalties"] + assert penalty["shape"] == [single["output_dim"]] * 2 + assert penalty["order"] == 2 + assert len(penalty["matrix_sha256"]) == 64 + assert "matrix" not in penalty + if group_method == "tensorspline": + assert [penalty["axis"] for penalty in group["penalties"]] == [["b"], ["a"]] + assert group["dimension"] == group["output_dim"] + 2 + for penalty in group["penalties"]: + assert penalty["shape"] == [group["output_dim"]] * 2 + assert "matrix" not in penalty + else: + assert "penalties" not in group + assert Preprocessor.from_spec(spec).to_spec()["representations"] == spec["representations"] + + del spec["state"]["_fit_config_"] + legacy_spec = Preprocessor.from_spec(spec).to_spec() + assert "resolved_config" not in legacy_spec + assert all("penalties" not in entry for entry in legacy_spec["representations"]) + + +def test_spec_content_keeps_legacy_only_pspline_orders_replayable(frame): + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="uniform", + feature_preprocessing={"a": {"method": "pspline", "output_dim": 7, "diff_order": 3}}, + ).fit(frame) + + spec = json.loads(json.dumps(processor.to_spec(), allow_nan=False)) + entry = next(entry for entry in spec["representations"] if entry["columns"] == ["a"]) + + assert "penalties" not in entry + restored = Preprocessor.from_spec(spec) + np.testing.assert_array_equal(restored.transform(frame), processor.transform(frame)) + + @pytest.mark.parametrize("leaf_input", ["imputed", "frame"]) def test_representation_summary_names_each_block_after_its_column(frame, target, leaf_input): """Without an imputer or scaler each representation is fitted on its DataFrame @@ -875,7 +976,9 @@ def test_failed_save_leaves_an_existing_spec_untouched(tmp_path, monkeypatch, un # already-opened file used to leave a truncated, invalid spec behind. spec = pre.to_spec() monkeypatch.setattr( - preprocessor_module, "preprocessor_to_spec", lambda _: {**spec, "state": {"unsupported_": unsupported}} + preprocessor_module, + "preprocessor_to_spec", + lambda _processor, **_options: {**spec, "state": {"unsupported_": unsupported}}, ) with pytest.raises(PretabSerializationError, match="cannot be written as JSON"): pre.to_spec(path) From 24a347fa3697032bf648e9285dba3b3225f73bc7 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 01:28:19 +0100 Subject: [PATCH 71/86] test(compose): pin schema v1 legacy replay --- tests/integration/test_serialization.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index f23e223..1aa87bb 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -52,7 +52,7 @@ def target(): @pytest.mark.parametrize("restore_format", ["pickle", "spec"]) -def test_legacy_state_restores_constructor_defaults(frame, restore_format): +def test_legacy_state_restores_constructor_defaults(frame, restore_format, tmp_path): processor = Preprocessor(numerical_method="rbf", target_aware=False, placement_strategy="uniform").fit(frame) expected = processor.transform(frame) fingerprint = processor.fingerprint_ @@ -70,14 +70,20 @@ def test_legacy_state_restores_constructor_defaults(frame, restore_format): del spec["state"]["_fit_config_"] for key in ("resolved_config", "output_dims", "total_output_dim", "feature_lineage"): del spec[key] - restored = Preprocessor.from_spec(spec) + spec["schema_version"] = 1 + path = tmp_path / "legacy-v1.json" + path.write_text(json.dumps(spec, allow_nan=False), encoding="utf-8") + restored = Preprocessor.from_spec(path) assert restored.get_params(deep=False)["feature_groups"] is None assert restored.get_params(deep=False)["task_validation"] == "off" assert restored.get_resolved_config()["feature_groups"] is None assert restored.get_resolved_config()["task_validation"] == "off" assert restored.fingerprint_ == fingerprint - assert "resolved_config" not in restored.to_spec() + rewritten = restored.to_spec() + assert rewritten["schema_version"] == 1 + assert "resolved_config" not in rewritten + assert "_fit_config_" not in rewritten["state"] np.testing.assert_array_equal(restored.transform(frame), expected) copied = clone(restored) assert isinstance(copied, Preprocessor) From 11291ed5d2c40f89dcbc010f636d886439104264 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 02:18:06 +0100 Subject: [PATCH 72/86] fix(compose): preserve legacy fingerprints across override syntax --- pretab/compose/serialize.py | 51 ++++++++++++++++++++- pretab/preprocessor.py | 7 +++ tests/integration/test_fingerprint.py | 65 ++++++++++++++++++++++++++- 3 files changed, 121 insertions(+), 2 deletions(-) diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 5d5ef59..d026e00 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -36,7 +36,7 @@ from ..core.parameters import UNSET from ..core.policy import RepresentationPolicy from ..core.representation import FeatureLineage, RepresentationSpec -from ..exceptions import PretabSerializationError +from ..exceptions import PretabConfigError, PretabSerializationError from ..expansion.spline.p_spline import PSplineTransformer from ..expansion.spline.penalty import PenaltySpec, _copy_provenance from ..placement.base import PlacementResult @@ -199,6 +199,55 @@ def _encode_mapping(mapping: dict) -> dict: return {str(k): _encode(v) for k, v in mapping.items()} +def _canonicalize_feature_block(transformer: dict, *, structured: bool) -> None: + """Keep the encoded representation leaf compatible with the legacy fingerprint.""" + pipeline = transformer["__estimator__"]["state"] + if "transformer_list" in pipeline: + branches = dict(item["__tuple__"] for item in pipeline["transformer_list"]) + pipeline = branches["representation"]["__estimator__"]["state"] + method, leaf = pipeline["steps"][-1]["__tuple__"] + state = leaf["__estimator__"]["state"] + if method == "pspline": + fitted = state.get("_penalty_fit_") + if fitted == {"__tuple__": [state.get("diff_order"), state.get("include_bias")]}: + state.pop("_penalty_fit_") + if not structured: + return + spec = TRANSFORMER_REGISTRY.get(method) + if spec is None or not spec.supports_adaptive_resolution: + return + if state.get("adaptive") is False: + for field in ("min_output_dim", "max_output_dim"): + if field in spec.allowed_args and state.get(field) == {"__unset__": True}: + state[field] = None + + +def _canonicalize_feature_fingerprint(state: dict, requests) -> None: + """Normalize single-feature requests and blocks without changing replay state.""" + structured = set() + if isinstance(requests, dict): + for (feature, request), pair in zip(requests.items(), state["feature_preprocessing"]["__dict__"], strict=True): + if isinstance(request, dict): + try: + request = RepresentationConfig.from_dict(request) + except PretabConfigError: + continue + if type(request) is RepresentationConfig: + settings = request.to_dict() + method_only = ( + settings.keys() == {"method", "params", "name"} and not request.params and request.name is None + ) + pair[1] = request.method if method_only else settings + structured.add(str(feature)) + graph = state.get("column_transformer_") + if isinstance(graph, dict): + for field in ("transformers", "transformers_"): + for block in graph["__estimator__"]["state"][field]: + name, transformer, columns = block["__tuple__"] + if name.startswith(("num_", "cat_")) and len(columns) == 1 and isinstance(transformer, dict): + _canonicalize_feature_block(transformer, structured=columns[0] in structured) + + def _json_safe(obj): """Best-effort readable encoding used for the declarative ``params`` block. diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index be0be6f..eb06ee9 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -45,6 +45,7 @@ ) from .compose.serialize import ( SCHEMA_VERSION, + _canonicalize_feature_fingerprint, _repair_legacy_sparse_feature_counts, preprocessor_from_spec, preprocessor_to_spec, @@ -1607,6 +1608,7 @@ def _canonical_spec(self) -> dict: state.pop("feature_groups", None) if state.get("task_validation") == "off": state.pop("task_validation") + _canonicalize_feature_fingerprint(state, self.feature_preprocessing) return { "schema_version": spec["schema_version"], "pretab_version": spec["pretab_version"], @@ -1625,6 +1627,11 @@ def fingerprint_(self) -> str: categories). The digest is deterministic across processes and machines, so the same fitted state and configuration produce the same fingerprint. + A method-only per-feature mapping or :class:`RepresentationConfig` can + match its legacy string when the spelling, override order, and fitted + settings agree. Named fields within a structured override are unordered; + the order of per-feature overrides and of group declarations still matters. + Raises ------ PretabSerializationError diff --git a/tests/integration/test_fingerprint.py b/tests/integration/test_fingerprint.py index 4c7b451..baf54cc 100644 --- a/tests/integration/test_fingerprint.py +++ b/tests/integration/test_fingerprint.py @@ -16,7 +16,7 @@ import pytest from sklearn.base import clone -from pretab import FeatureGroup, Preprocessor +from pretab import FeatureGroup, Preprocessor, RepresentationConfig from pretab.compose.inspection import representation_leaf from pretab.compose.registry import ( CATEGORICAL_ALIASES, @@ -56,6 +56,69 @@ def test_fingerprint_deterministic_same_fit(frame, target): assert _fit(frame, target).fingerprint_ == _fit(frame, target).fingerprint_ +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("order", [("a", "b"), ("b", "a")], ids=["forward", "reversed"]) +@pytest.mark.parametrize(("method", "missing_policy"), [("rbf", None), ("rbf", "separate_state"), ("pspline", None)]) +def test_fingerprint_matches_equivalent_per_feature_syntax(frame, target, typed, order, method, missing_policy): + methods = {"a": method, "b": "minmax"} + legacy = {feature: methods[feature] for feature in order} + structured = { + feature: RepresentationConfig(method) if typed else {"method": method} for feature, method in legacy.items() + } + params = { + "numerical_method": "none", + "placement_strategy": "uniform", + "random_state": 17, + "missing_policy": missing_policy, + } + reference = _fit(frame, target, feature_preprocessing=legacy, **params) + opposite = _fit(frame, target, feature_preprocessing=dict(reversed(legacy.items())), **params) + candidate = _fit(frame, target, feature_preprocessing=structured, **params) + restored = Preprocessor.from_spec(candidate.to_spec()) + expected = np.asarray(reference.transform(frame, return_array=True)) + + assert reference.fingerprint_ != opposite.fingerprint_ + for processor in (candidate, restored): + request = processor.feature_preprocessing + assert request is not None + assert list(request.items()) == list(structured.items()) + assert processor.fingerprint_ == reference.fingerprint_ + np.testing.assert_array_equal(processor.get_feature_names_out(), reference.get_feature_names_out()) + output = np.asarray(processor.transform(frame, return_array=True)) + assert output.tobytes() == expected.tobytes() + + +def test_fingerprint_canonicalizes_structured_setting_order(frame, target): + typed = RepresentationConfig( + "rbf", adaptive=True, min_output_dim=5, max_output_dim=9, params={"gamma": 1.0, "random_state": 17} + ) + mapping = typed.to_dict() + reordered = dict(reversed(mapping.items())) + reordered["params"] = dict(reversed(mapping["params"].items())) + + def fingerprint(request): + return _fit(frame, target, placement_strategy="uniform", feature_preprocessing={"a": request}).fingerprint_ + + expected = fingerprint(typed) + assert fingerprint(mapping) == fingerprint(reordered) == expected + assert fingerprint(mapping | {"max_output_dim": 10}) != expected + assert fingerprint(mapping | {"params": mapping["params"] | {"gamma": 2.0}}) != expected + + +def test_fingerprint_omits_only_redundant_pspline_penalty_snapshot(frame, target): + processor = _fit(frame, target, feature_preprocessing={"a": "pspline"}, placement_strategy="uniform") + restored = Preprocessor.from_spec(processor.to_spec()) + current_leaf = representation_leaf(processor.column_transformer_.named_transformers_["num_a"]) + legacy_leaf = representation_leaf(restored.column_transformer_.named_transformers_["num_a"]) + + del legacy_leaf._penalty_fit_ + assert processor.fingerprint_ == restored.fingerprint_ + assert current_leaf._penalty_fit_ == (2, False) + + current_leaf.diff_order = legacy_leaf.diff_order = 1 + assert processor.fingerprint_ != restored.fingerprint_ + + @pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) @pytest.mark.parametrize("change", ["group_order", "source_order", "family", "width", "params", "seed", "state"]) def test_group_fingerprint_tracks_order_settings_and_fitted_state(frame, typed, change): From 870b367df55e1b32796bdaef1eea4b905050a65a Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 02:30:21 +0100 Subject: [PATCH 73/86] fix(compose): reject inconsistent spec metadata --- pretab/compose/serialize.py | 57 +++++++++++++++++++++++-- pretab/preprocessor.py | 4 ++ tests/integration/test_serialization.py | 50 ++++++++++++++++++++++ 3 files changed, 107 insertions(+), 4 deletions(-) diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index d026e00..59915ec 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -391,6 +391,16 @@ def _penalty_summaries(leaf) -> list[dict]: return [penalty.to_summary() for penalty in penalties] +def _group_layout(block, columns: list[str]) -> dict: + span = block.span + return { + "columns": columns, + "group_id": block.group_id, + "dimension": span.stop - span.start, + "output_slice": [span.start, span.stop], + } + + def _representation_summary(preprocessor, *, include_penalties: bool = False) -> list: """Declarative per-representation summary (family/columns/locations). @@ -425,10 +435,7 @@ def _representation_summary(preprocessor, *, include_penalties: bool = False) -> entry = spec_fn(input_features=block_columns if fits_block else None).to_dict() entry["columns"] = block_columns if block.group_id is not None: - span = block.span - entry["group_id"] = block.group_id - entry["dimension"] = span.stop - span.start - entry["output_slice"] = [span.start, span.stop] + entry.update(_group_layout(block, block_columns)) if include_penalties and (penalties := _penalty_summaries(leaf)): entry["penalties"] = penalties summary.append(entry) @@ -471,6 +478,47 @@ def check_spec_schema(data: dict) -> None: ) +def _validate_group_layout(representations, column_transformer) -> None: + if not isinstance(representations, list) or not all(isinstance(entry, dict) for entry in representations): + raise PretabSerializationError("Spec 'representations' must be a list of mappings.") + fields = ("columns", "group_id", "dimension", "output_slice") + declared = [{field: entry.get(field) for field in fields} for entry in representations if "group_id" in entry] + fitted = [ + _group_layout(block, [str(column) for column in block.columns]) + for block in _iter_fitted_blocks(column_transformer) + if block.group_id is not None + and getattr(representation_leaf(block.transformer), "get_representation_spec", None) is not None + ] + if declared != fitted: + raise PretabSerializationError("Spec 'representations' group layout does not match stored preprocessor state.") + + +def _validate_spec_metadata(data: dict, preprocessor) -> None: + """Check descriptive fields against their source in restored state, when available.""" + state = vars(preprocessor) + has_fit_config = "_fit_config_" in state + has_fitted_metadata = has_fit_config or "output_dims" in data or "total_output_dim" in data + expected = {} + if "params" in data and has_fitted_metadata: + expected["params"] = _json_safe(preprocessor.get_params(deep=False)) + if "resolved_config" in data and has_fit_config: + expected["resolved_config"] = _json_safe(state["_fit_config_"]) + if "output_dims" in data: + expected["output_dims"] = _json_safe(preprocessor.output_dims_) + if "total_output_dim" in data: + names = data.get("feature_names_out") + if isinstance(names, list): + expected["total_output_dim"] = len(names) + else: + spans = preprocessor.column_transformer_.output_indices_.values() + expected["total_output_dim"] = max((span.stop for span in spans), default=0) + for field, value in expected.items(): + if data[field] != value: + raise PretabSerializationError(f"Spec {field!r} does not match stored preprocessor state.") + if "representations" in data and has_fitted_metadata: + _validate_group_layout(data["representations"], preprocessor.column_transformer_) + + def _repair_legacy_sparse_feature_counts(preprocessor) -> None: """Repair the sparse-input helper width stored by PreTab 1.0.0.""" column_transformer = getattr(preprocessor, "column_transformer_", None) @@ -506,4 +554,5 @@ def preprocessor_from_spec(data: dict): if isinstance(output_config, dict) and output_config.get("transform") == "polars": _require_polars() _repair_legacy_sparse_feature_counts(obj) + _validate_spec_metadata(data, obj) return obj diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index eb06ee9..3b33633 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -1578,6 +1578,10 @@ def from_spec(cls, source) -> "Preprocessor": Raises ------ + PretabSerializationError + If recorded widths, configuration, or group layout disagree with + the stored state or feature names. These checks do not authenticate + the spec; only load specs from trusted sources. OptionalDependencyError If the spec explicitly requests Polars output and Polars is unavailable. """ diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index 1aa87bb..2c0db43 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -17,6 +17,7 @@ import pytest from sklearn import config_context from sklearn.base import clone +from sklearn.exceptions import NotFittedError from pretab import ( FeatureGroup, @@ -316,6 +317,55 @@ def test_spec_content_describes_the_fit_after_requests_change(frame): assert "group_joint" not in refit_spec["output_dims"] +@pytest.mark.parametrize("via_file", [False, True], ids=["dict", "file"]) +@pytest.mark.parametrize( + ("path", "value"), + [ + pytest.param(("output_dims", "group_joint"), 1, id="block-width"), + pytest.param(("total_output_dim",), 1, id="total-width"), + pytest.param(("params", "feature_preprocessing", "extra", "output_dim"), 4, id="requested-width"), + pytest.param(("params", "feature_groups", "joint", "columns"), ["a", "b"], id="requested-group-order"), + pytest.param(("resolved_config", "feature_preprocessing", "extra", "output_dim"), 4, id="fitted-width"), + pytest.param(("resolved_config", "feature_groups", 0, "columns"), ["a", "b"], id="fitted-group-order"), + pytest.param(("representations", 1, "dimension"), 1, id="group-summary-width"), + pytest.param(("representations", 1, "columns"), ["a", "b"], id="group-summary-order"), + pytest.param(("representations", 1, "output_slice"), [0, 1], id="group-summary-slice"), + ], +) +def test_from_spec_rejects_inconsistent_metadata(frame, tmp_path, via_file, path, value): + fitting_frame = frame.assign(extra=np.linspace(-2, 2, len(frame))) + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="uniform", + feature_preprocessing={"extra": {"method": "rbf", "output_dim": 3}}, + feature_groups={ + "joint": {"columns": ["b", "a"], "representation": {"method": "tensorspline", "output_dim": 4}} + }, + ).fit(fitting_frame) + spec = processor.to_spec() + assert spec["representations"][1]["group_id"] == "group_joint" + destination = spec + for key in path[:-1]: + destination = destination[key] + assert destination[path[-1]] != value + destination[path[-1]] = value + + source = spec + if via_file: + source = tmp_path / "inconsistent.json" + source.write_text(json.dumps(spec, allow_nan=False), encoding="utf-8") + with pytest.raises(PretabSerializationError, match=path[0]): + Preprocessor.from_spec(source) + + +def test_to_spec_unfitted_does_not_create_file(tmp_path): + path = tmp_path / "unfitted.json" + with pytest.raises(NotFittedError): + Preprocessor().to_spec(path) + assert not path.exists() + + @pytest.mark.parametrize("group_method", ["tensorspline", "tprs"]) def test_spec_content_includes_only_supported_penalty_summaries(frame, group_method): X = frame.assign(extra=np.linspace(-2, 2, len(frame))) From d916dc22e60b9e12b0d3c46f4f36ff5f96475aa8 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 10:52:57 +0100 Subject: [PATCH 74/86] feat(compose): summarize fitted override settings --- docs/core_concepts/outputs_and_inspection.md | 7 ++++ pretab/compose/inspection.py | 27 +++++++++++++ pretab/preprocessor.py | 9 ++++- tests/integration/test_serialization.py | 41 ++++++++++++++++++++ 4 files changed, 82 insertions(+), 2 deletions(-) diff --git a/docs/core_concepts/outputs_and_inspection.md b/docs/core_concepts/outputs_and_inspection.md index f644f13..5c5618d 100644 --- a/docs/core_concepts/outputs_and_inspection.md +++ b/docs/core_concepts/outputs_and_inspection.md @@ -355,6 +355,13 @@ city categorical imputer -> onehot -> to_float 3 3 ) ``` +After the table, `get_feature_info()` logs the effective settings recorded at fit time +for declared feature overrides and groups, with group sources in their declared order. +This section does not enumerate every pipeline step. Its `output_dim`, when present, is +a configuration setting; the table's `dim` is the actual fitted width. Edits after fit +do not change the recorded settings. Use `get_resolved_config()` for current settings. +Older fits without a settings record report that it is unavailable. + ```{tip} `get_feature_info()` is a handy, no-setup way to check exactly what happened to each feature: which pipeline it went through, how many output columns it produced, and (for categoricals) diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index 0bfe761..3866c4c 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -337,6 +337,33 @@ def build_transformer_summary(numerical_info, categorical_info, embedding_info): return lines +def _build_effective_settings_summary(fit_config: dict | None) -> list[str]: + """Render settings recorded for declared overrides and groups at fit time.""" + if fit_config is None: + return ["Fit-time effective settings unavailable (not recorded)."] + + def format_settings(settings): + fields = [ + f"{key}={value!r}" + for key, value in settings.items() + if key != "params" and not (key == "name" and value is None) + ] + fields.extend(f"{key}={value!r}" for key, value in settings.get("params", {}).items()) + return ", ".join(fields) + + rows = [ + f"feature {feature!r}: {format_settings(settings)}" + for feature, settings in (fit_config["feature_preprocessing"] or {}).items() + ] + rows.extend( + f"group_{group['name']} (sources={group['columns']!r}): {format_settings(group['representation'])}" + for group in fit_config["feature_groups"] or [] + ) + if not rows: + return ["Fit-time effective settings: no per-feature overrides or groups recorded."] + return ["Fit-time effective settings (declared overrides and groups; fitted dimensions are shown above):", *rows] + + # Mapping from pipeline step name to (family, component) for representation-bearing # scikit-learn steps that do not expose ``get_representation_spec``. _STEP_FAMILY = { diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index 3b33633..ebd50a2 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -25,6 +25,7 @@ ) from .compose.inspection import ( _block_uses_task, + _build_effective_settings_summary, _iter_fitted_blocks, block_uses_target, build_feature_info, @@ -1452,8 +1453,10 @@ def get_feature_info(self, verbose=True): verbose : bool, default=True If True, renders an aligned per-feature table through the ``pretab`` logger (attaching a stream handler when no host handler receives its - records), without lowering a more verbose level set earlier. If False, - the info dicts are returned silently. + records), without lowering a more verbose level set earlier. The + table is followed by the recorded fit-time settings for declared + feature overrides and groups, or an explicit notice for older fits + without that record. If False, the info dicts are returned silently. Returns ------- @@ -1491,6 +1494,8 @@ def get_feature_info(self, verbose=True): embedding_feature_info, ): logger.info(line) + for line in _build_effective_settings_summary(getattr(self, "_fit_config_", None)): + logger.info(line) return numerical_feature_info, categorical_feature_info, embedding_feature_info diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index 2c0db43..bbdef56 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -317,6 +317,47 @@ def test_spec_content_describes_the_fit_after_requests_change(frame): assert "group_joint" not in refit_spec["output_dims"] +@pytest.mark.parametrize("restore", ["none", "current", "legacy"]) +def test_verbose_feature_info_uses_recorded_fit_settings(frame, caplog, restore): + fitting_frame = frame.assign(extra=np.linspace(-2, 2, len(frame))) + override = {"method": "RBF", "output_dim": 3, "gamma": 0.5} + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="uniform", + feature_preprocessing={"extra": override}, + feature_groups=[FeatureGroup("joint", ("b", "a"), RepresentationConfig("tensorspline", output_dim=4))], + ).fit(fitting_frame) + override["gamma"] = 1.5 + processor.set_params(feature_groups=None) + if restore != "none": + spec = processor.to_spec() + if restore == "legacy": + del spec["state"]["_fit_config_"] + del spec["resolved_config"] + processor = Preprocessor.from_spec(json.loads(json.dumps(spec, allow_nan=False))) + + before = processor.to_spec() + fingerprint = processor.fingerprint_ + with caplog.at_level("INFO", logger="pretab"): + quiet = processor.get_feature_info(verbose=False) + assert not caplog.messages + assert processor.get_feature_info() == quiet + + assert quiet[0]["group_joint"]["dimension"] == 16 + assert "gamma=1.5" not in caplog.text + if restore == "legacy": + assert "Fit-time effective settings unavailable (not recorded)." in caplog.messages + else: + single = next(message for message in caplog.messages if message.startswith("feature 'extra':")) + assert "method='rbf'" in single and "output_dim=3" in single and "gamma=0.5" in single + assert "placement_strategy='uniform'" in single and "target_aware=False" in single + group = next(message for message in caplog.messages if message.startswith("group_joint (sources=['b', 'a']):")) + assert "method='tensorspline'" in group and "output_dim=4" in group + assert processor.fingerprint_ == fingerprint + assert processor.to_spec() == before + + @pytest.mark.parametrize("via_file", [False, True], ids=["dict", "file"]) @pytest.mark.parametrize( ("path", "value"), From 1b3d5939b89f07b050a13353ae2ce6ddf1e7110a Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 11:03:03 +0100 Subject: [PATCH 75/86] docs: explain schema spec compatibility --- docs/api/preprocessor.rst | 6 ++ docs/core_concepts/reproducibility.md | 80 ++++++++++++++++++++------- 2 files changed, 66 insertions(+), 20 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 17150d6..02895ac 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -173,6 +173,12 @@ including adaptive sizing and separate missing indicators. Representation summaries describe the representation itself, excluding separate indicators; output budgets and reported output dimensions include those indicators. +Specs retain schema version 1. ``params`` describes the current constructor +requests; ``resolved_config``, when present, describes the last successful fit. +The reader restores the encoded ``state`` rather than fitting from either set of +settings. See :ref:`portable-serialization` for the field reference, reading +legacy specs, downgrade limits, and when to use pickle instead. + .. warning:: Load specs only from trusted sources. Dependency versions recorded in a diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index 75717ba..abd0c76 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -23,42 +23,82 @@ with no stochastic component ignore the seed. The standalone kernel approximatio directly; they are fit outside `Preprocessor` since they operate on the whole feature block. ``` -## Portable serialization +(portable-serialization)= -`to_spec` writes a fitted `Preprocessor` to a versioned, declarative schema, and `from_spec` -reconstructs it. The spec records the schema and library versions, the resolved parameters, -and the per-representation fitted state (parameters, knots, centers, columns, scaling). +## Portable serialization -The spec is strict JSON, so any standard parser (JavaScript, Go, Rust, JSON schema validators) -reads it. Non-finite floats, such as the imputers' `missing_values=np.nan`, are stored as a -tagged value, `{"__float__": "nan"}` (or `"inf"`, `"-inf"`), instead of a bare `NaN` token. -Specs written by PreTab 1.0.0, which contain bare `NaN` tokens, still load. -The reverse is not supported: older readers cannot decode the new float tags. -Keep the original spec if you may need to roll back to PreTab 1.0.0. -The tagged encoding also changes fingerprints for fitted state containing non-finite -values, including the default imputers; this change does not alter transformed values. +`to_spec()` exports a fitted `Preprocessor` as a JSON-compatible dictionary and can also +write it to a file. `from_spec()` restores it from either form without refitting. ```python +pre.fit(df, y) spec = pre.to_spec() # returns a dict pre.to_spec("representation.json") # or writes JSON to a path restored = Preprocessor.from_spec("representation.json") ``` +### What's in a spec + +- `schema_version`, `pretab_version`, and `library_versions` identify the format and the + environment that wrote the spec. +- `params` holds constructor requests at export time. These can change after fit. +- `resolved_config` holds effective settings recorded at the last successful fit, including + normalized declared feature overrides and groups in declared order. It is absent if the + fit has no settings record. +- `feature_names_out` and `feature_lineage` give the output column order and fitted + provenance, including group identity and ordered sources where applicable. +- `output_dims` and `total_output_dim` give actual per-block and total widths, including + separate missing indicators. These are not requested `output_dim` values. +- `representations` describes blocks that expose representation metadata. Group entries + include `group_id`, ordered `columns`, fitted `dimension`, and a half-open `output_slice`. + Supported typed penalties add compact `penalties` metadata, including coefficient + coordinates and a matrix checksum, not the matrix itself. +- `state` is the encoded fitted object state. This is what the reader restores; the + descriptive fields alone cannot recreate the learned transformation. + +Use `get_resolved_config()` to inspect effective settings for the **current** requests. +It is not a substitute for the recorded fit-time `resolved_config`. Don't edit a spec to +change a fit: the reader checks recorded configuration and layout fields against the +stored state where applicable and raises `PretabSerializationError` on mismatches. +Those checks do not authenticate the artifact. + +### Compatibility + +The current writer still uses `schema_version: 1`. It writes strict JSON, encoding +non-finite floats such as the default imputer's `np.nan` as tagged values, for example +`{"__float__": "nan"}`, instead of bare `NaN`. Standard JSON parsers can inspect new specs; +restoring the fitted object requires PreTab. + +The current reader loads supported PreTab 1.0.0 schema-v1 specs, including legacy bare +`NaN` tokens and specs without the added metadata. It does not invent a missing fit-time +settings record. **Downgrades are not supported:** PreTab 1.0.0 cannot decode the new +float tags, even though the schema number is unchanged. Keep the original artifact and +its environment for rollback. The change to tagged encoding can affect fingerprints for +state containing non-finite values without changing transformed values. + ```{important} Load specs only from trusted sources. Reconstruction restricts imports to `pretab`, `scikit-learn`, `numpy`, and `scipy`, reconstructs dataclasses only from an exact, closed allow-list, and bypasses estimator initialization and pickle hooks. These restrictions are -not a sandbox: importing library modules can still execute code. Use the same PreTab and -dependency versions when restoring; recorded versions are informational, and cross-version -compatibility is not guaranteed. +not a sandbox: importing library modules can still execute code. Recorded versions are +informational, not a guarantee of compatibility. Use the original environment for exact +replay, and verify fitted outputs when upgrading. ``` +### Spec or pickle? + +Use a spec when you need an inspectable JSON artifact for supported fitted PreTab state. Supported built-in representations reproduce `transform` bit-for-bit in the same environment. -Third-party representations and pretrained language models are not supported by the JSON -serializer; unsupported state raises `PretabSerializationError` when the spec is built. The -spec is serialized before `to_spec(path)` opens the file, so a failed save leaves an existing -spec at that path untouched. +The spec covers preprocessing, not a downstream model. Registering a third-party +representation for fitting does not make it restorable from a spec; don't rely on specs +to persist third-party representations or pretrained language models. A serialization +failure occurs before `to_spec(path)` opens the destination. + +Use pickle or joblib when you need to persist a larger Python object, such as a complete +scikit-learn pipeline, and every component supports that mechanism. Neither is a +cross-version guarantee. Unpickling can execute arbitrary code: only load trusted +pickle or joblib artifacts. The same trusted-source requirement applies to specs. ```{note} Restoring a PreTab 1.0.0 `Preprocessor` from a spec or trusted pickle repairs @@ -69,7 +109,7 @@ fingerprints. Feature information reports the fitted layout; previously incorrec dimension metadata can change. Standalone helper validation is unchanged. Fingerprints can differ from 1.0.0 because the fitted metadata and JSON encoding have been corrected. This targeted repair is not a general guarantee of -cross-version compatibility. Only unpickle artifacts from trusted sources. +cross-version compatibility. ``` When refitting after an upgrade, check output names and widths before reusing a From 48574ac4949ff1e66fa748fc505ce40d35b649b1 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 12:05:45 +0100 Subject: [PATCH 76/86] fix(compose): reject unsupported estimators in specs --- docs/api/preprocessor.rst | 9 ++++- docs/core_concepts/reproducibility.md | 20 +++++++--- pretab/compose/serialize.py | 7 ++++ .../extension/test_registration_discovery.py | 14 ++++++- tests/integration/test_serialization.py | 40 +++++++++++++++++++ 5 files changed, 82 insertions(+), 8 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 02895ac..12d5a50 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -164,7 +164,7 @@ configuration needs no syntax change, and can be mixed with structured entries. Configuration, output, and reproducibility ------------------------------------------ -Fitted preprocessors using string, mapping, or +Fitted preprocessors with supported state using string, mapping, or :class:`~pretab.RepresentationConfig` entries can be saved with :meth:`~pretab.Preprocessor.to_spec` and restored with :meth:`~pretab.Preprocessor.from_spec` in the same environment. Restored names, @@ -179,6 +179,13 @@ The reader restores the encoded ``state`` rather than fitting from either set of settings. See :ref:`portable-serialization` for the field reference, reading legacy specs, downgrade limits, and when to use pickle instead. +Registration does not enable spec persistence. ``to_spec()``, ``fingerprint_``, +and ``reproducibility_report()`` raise ``PretabSerializationError`` on unsupported +estimator state, including nested estimators. File export raises before opening +the destination. Use supported built-in representations for JSON replay, or a +trusted pickle or joblib checkpoint in a matching environment if all components +support it. + .. warning:: Load specs only from trusted sources. Dependency versions recorded in a diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index abd0c76..4c89a65 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -91,14 +91,18 @@ replay, and verify fitted outputs when upgrading. Use a spec when you need an inspectable JSON artifact for supported fitted PreTab state. Supported built-in representations reproduce `transform` bit-for-bit in the same environment. The spec covers preprocessing, not a downstream model. Registering a third-party -representation for fitting does not make it restorable from a spec; don't rely on specs -to persist third-party representations or pretrained language models. A serialization -failure occurs before `to_spec(path)` opens the destination. +representation enables fitting and transforming, not spec persistence. `to_spec()` raises +`PretabSerializationError` and names the unsupported estimator if its module is outside +the spec's allowed modules, even when it is nested in an otherwise supported pipeline. +The fitted object is unchanged, and `to_spec(path)` raises before opening the destination. +Use supported built-in representations when you need JSON replay; don't rely on specs +to persist third-party representations or pretrained language models. Use pickle or joblib when you need to persist a larger Python object, such as a complete -scikit-learn pipeline, and every component supports that mechanism. Neither is a -cross-version guarantee. Unpickling can execute arbitrary code: only load trusted -pickle or joblib artifacts. The same trusted-source requirement applies to specs. +scikit-learn pipeline, and every component supports that mechanism. Use a matching +environment to restore the checkpoint; neither format guarantees cross-version replay. +Unpickling can execute arbitrary code: only load trusted pickle or joblib artifacts. +The same trusted-source requirement applies to specs. ```{note} Restoring a PreTab 1.0.0 `Preprocessor` from a spec or trusted pickle repairs @@ -145,6 +149,10 @@ versions, seed, output dtype and format, output widths, and the per-feature fami pre.reproducibility_report() ``` +`fingerprint_` and `reproducibility_report()` require supported spec state. Both raise +`PretabSerializationError` on unsupported estimator state rather than returning a digest +or partial report. + ## Immutable lifecycle A fitted representation moves through a small set of explicit states, which prevents diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 59915ec..796a068 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -166,6 +166,13 @@ def _encode(obj): if isinstance(obj, list): return [_encode(v) for v in obj] if isinstance(obj, BaseEstimator): + cls = type(obj) + if not _module_allowed(cls.__module__): + raise PretabSerializationError( + f"Cannot serialize estimator {cls.__module__}.{cls.__qualname__} in a schema-v1 spec. " + "Registration does not enable spec persistence. Use a supported built-in representation for JSON " + "replay, or a trusted pickle or joblib checkpoint in a matching environment if all components support it." + ) return {"__estimator__": {"class": _qualname(obj), "state": _encode_mapping(vars(obj))}} if type(obj) is RepresentationConfig: fields = {key: _encode(value) for key, value in obj.to_dict().items()} diff --git a/tests/extension/test_registration_discovery.py b/tests/extension/test_registration_discovery.py index 272c3c7..a740df0 100644 --- a/tests/extension/test_registration_discovery.py +++ b/tests/extension/test_registration_discovery.py @@ -22,7 +22,7 @@ from pretab.compose import registry from pretab.compose.config import PreprocessorConfig from pretab.compose.factory import create_transformer -from pretab.exceptions import ConfigWarning +from pretab.exceptions import ConfigWarning, PretabSerializationError class _Square(BaseRepresentation): @@ -152,6 +152,18 @@ def test_register_end_to_end_through_preprocessor(): assert out.max() <= 1 + 1e-9 +def test_registered_external_estimator_is_rejected_at_save_time(): + register_representation("square_reg", _Square) + frame = pd.DataFrame({"value": np.linspace(0.0, 1.0, 12)}) + processor = Preprocessor(numerical_method="square_reg", target_aware=False, placement_strategy="uniform").fit(frame) + expected = processor.transform(frame, return_array=True) + + with pytest.raises(PretabSerializationError, match=r"_Square.*Registration does not enable spec persistence"): + processor.to_spec() + + np.testing.assert_array_equal(processor.transform(frame, return_array=True), expected) + + def test_registered_positive_only_feature_info_matches_fitted_layout(monkeypatch): register_representation("positive_only_reg", _PositiveOnly) frame = pd.DataFrame({"value": [1.0, 2.0, 4.0, 8.0]}) diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index bbdef56..a4d1c0d 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -1091,6 +1091,46 @@ def test_types_a_spec_cannot_load_are_rejected_at_save_time(): _encode(list) +class _ExternalEstimator(NoTransformer): + pass + + +def test_nested_external_estimator_is_rejected_by_spec_callers(frame, tmp_path): + processor = Preprocessor(numerical_method="minmax").fit(frame) + expected = processor.transform(frame) + path = tmp_path / "spec.json" + spec = processor.to_spec(path) + saved = path.read_bytes() + fingerprint = processor.fingerprint_ + assert processor.reproducibility_report()["fingerprint"] == fingerprint + restored = Preprocessor.from_spec(path) + assert restored.to_spec() == spec + assert restored.fingerprint_ == fingerprint + np.testing.assert_array_equal(restored.transform(frame), expected) + + fitted_pipeline = processor.column_transformer_.named_transformers_["num_a"] + nested = {"estimators": [_ExternalEstimator()]} + fitted_pipeline.extension_state_ = nested + missing_path = tmp_path / "not-created.json" + message = r"_ExternalEstimator.*Registration does not enable spec persistence.*built-in" + + with pytest.raises(PretabSerializationError, match=message): + processor.to_spec() + with pytest.raises(PretabSerializationError, match=message): + processor.to_spec(path) + with pytest.raises(PretabSerializationError, match=message): + processor.to_spec(missing_path) + with pytest.raises(PretabSerializationError, match=message): + _ = processor.fingerprint_ + with pytest.raises(PretabSerializationError, match=message): + processor.reproducibility_report() + + assert path.read_bytes() == saved + assert not missing_path.exists() + assert fitted_pipeline.extension_state_ is nested + np.testing.assert_array_equal(processor.transform(frame), expected) + + def test_object_arrays_written_before_element_encoding_still_load(): from pretab.compose.serialize import _decode From d7e3310681501cf01b38ed9785d141e8cb23d4d2 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 12:33:49 +0100 Subject: [PATCH 77/86] docs: document PreTab architecture boundaries --- docs/developer_guide/architecture.md | 154 +++++++++++++++++++ docs/developer_guide/contributing.md | 3 + docs/index.rst | 1 + docs/tutorials/custom_representation.md | 2 + tests/doc_snippets/test_tutorial_snippets.py | 6 +- 5 files changed, 163 insertions(+), 3 deletions(-) create mode 100644 docs/developer_guide/architecture.md diff --git a/docs/developer_guide/architecture.md b/docs/developer_guide/architecture.md new file mode 100644 index 0000000..2509feb --- /dev/null +++ b/docs/developer_guide/architecture.md @@ -0,0 +1,154 @@ +# Architecture contract + +PreTab separates representation algorithms, the composition that selects and wires +them, and the public `Preprocessor` that owns the fitting lifecycle. Use these +boundaries when adding a representation or a consumer of fitted state. + +## Dependency directions + +- `pretab.core` owns shared estimator, validation, and representation primitives. + It depends on core peers and shared exceptions, not on registered methods or + the facade. `pretab.placement` uses core and placement peers, not concrete + representations. +- Expansion, encoding, kernel approximation, embedding, and preprocessing modules + use their own implementations and lower-level core, placement, or exception + facilities as needed. They do not import composition, the facade, extension + registration, or the public reexport modules. +- `pretab.compose` selects and assembles concrete implementations. The registry is + the source of method capabilities; config resolves requests and the factory builds + pipelines from the resolved settings. Add a method capability there rather than + duplicating it in the facade or an output consumer. +- `Preprocessor` orchestrates fitting, inference, and lifecycle operations through + composition and core. The extension API registers through the same registry and + uses the core representation contract. + +Two composition modules intentionally refer to the facade: `pretab.compose.search` +constructs candidates and `pretab.compose.serialize` imports `Preprocessor` locally +to restore one. These are upper-layer exceptions, not a dependency for a representation +implementation. The codec's controlled class resolution is separate from static imports. + +Use the documented public imports in application and plugin code. `pretab` exports +the facade, configuration values, and extension functions. `pretab.transformers` +reexports concrete transformers from their implementation families. Inside PreTab, +import from the owner rather than routing implementation dependencies through these +convenience exports. See the [API reference](../api/preprocessor.rst) and +[extensibility API](../api/extension.rst) for the supported entry points. + +## Requests, resolution, and fitted state + +Keep these views distinct: + +- `get_params()` exposes the current constructor requests, preserving spellings and + caller-owned raw mappings. Typed requests such as `RepresentationConfig` detach + their input data at construction. +- `get_resolved_config()` normalizes current requests and applies defaults and + inheritance. It does not fit, inspect the input, or recover learned state. +- The last successful fit records its effective settings separately. Supported specs + expose them as `resolved_config` when available; legacy specs need not have that + record. The fitted estimators and their actual layout are authoritative for inference. + +Changing a request with `set_params()` does not replace the fitted representation. +This example checks the live and recorded methods before the next fit: + +```python +import numpy as np +import pandas as pd + +from pretab import Preprocessor, RepresentationConfig + +frame = pd.DataFrame({"value": np.linspace(0.0, 1.0, 32)}) +pre = Preprocessor( + feature_preprocessing={"value": RepresentationConfig(method="rbf", output_dim=3)}, + target_aware=False, + placement_strategy="uniform", +).fit(frame) +fitted_output = pre.transform(frame, return_array=True) + +pre.set_params(feature_preprocessing={"value": "minmax"}) +assert pre.get_params(deep=False)["feature_preprocessing"] == {"value": "minmax"} +current = pre.get_resolved_config()["feature_preprocessing"] +recorded = pre.to_spec()["resolved_config"]["feature_preprocessing"] +assert current["value"]["method"] == "minmax" +assert recorded["value"]["method"] == "rbf" +np.testing.assert_array_equal(pre.transform(frame, return_array=True), fitted_output) +``` + +## Fitted layout and lineage + +The fitted `ColumnTransformer` owns the ordered blocks and their output spans. +Composition inspection reads the fitted entries and `output_indices_`; output +formatting consumes those spans. Do not infer the number or order of columns from +a request, refit a block for inspection, or use a leaf estimator's basis width as +the width of its whole pipeline. Adaptive sizing, joint bases, and missing-state +columns can all make the actual width differ from the request. + +Use `output_dims_` and `total_output_dim_` when sizing a consumer, and +`get_feature_names_out()` and `get_feature_lineage()` when labeling it. A group +owns its sources and contributes one block. Joint basis columns record all of the +group's sources in declared order; each raw missing-state column records only its +own source but retains the same group ID. The example requests three basis +functions per axis, yielding nine joint columns and two missing-state columns. + +```python +from pretab import FeatureGroup + +group_frame = frame.assign(other=np.sin(4.0 * frame["value"])) +group_frame.loc[0, "value"] = np.nan +group = FeatureGroup( + name="pair", + columns=("other", "value"), + representation=RepresentationConfig(method="tensorspline", output_dim=3, params={"degree": 2}), +) +grouped = Preprocessor( + feature_groups=[group], + target_aware=False, + placement_strategy="uniform", + missing_policy="separate_state", + output_structure="blocks", + output_format="dense", +) +blocks = grouped.fit_transform(group_frame) +lineage = grouped.get_feature_lineage() + +assert list(blocks) == ["group_pair"] +assert blocks["group_pair"].shape[1] == grouped.output_dims_["group_pair"] == 11 +assert len(lineage) == len(grouped.get_feature_names_out()) == grouped.total_output_dim_ == 11 +assert all(item.group_id == "group_pair" for item in lineage) +assert [item.source_features for item in lineage if item.component != "indicator"] == [group.columns] * 9 +assert [item.source_features for item in lineage if item.component == "indicator"] == [("other",), ("value",)] +``` + +## Input-only state and supervised refitting + +When `CrossFittedTransformer` wraps a `Preprocessor`, it uses the fitted block's +actual target use to decide what to refit. A target-consuming representation and +any steps after it are refit on the fold's training rows. Input-only state from +the full input to the wrapper stays fitted: column routing, target-free blocks +and their vocabularies, imputers, scalers, and separate missing branches. A group +still uses its ordered sources as one block. This keeps category identities and +indicator columns aligned across folds without letting a representation use the +held-out row's target. The refitted block must retain its fitted width. + +```{note} +Cross-fitting produces a matrix, not a dictionary of blocks. It protects the +held-out targets within the data passed to the wrapper. For evaluation, still +fit the whole pipeline within each outer training split. +``` + +## Optional dependencies and persistence + +Keep optional packages at the feature boundary. LightGBM placement and language +embeddings use the lazy dependency helpers in `pretab.core.dependencies`; Polars +input and output are handled at the input and output boundaries. Do not make a +base import or an unrelated method require an extra. Preserve an actionable +`OptionalDependencyError` for the path that needs the missing package. + +Registration makes a representation selectable for fitting and inference. It does +not register a persistence codec or extend the schema-v1 import policy. If a +fitted estimator's module is outside that policy, `to_spec()` rejects it with +`PretabSerializationError` before opening a destination, even if it is nested +inside a supported pipeline. `fingerprint_` and `reproducibility_report()` raise +the same error rather than dropping state. Use supported built-in representations +for JSON replay, or a trusted pickle or joblib checkpoint in a matching environment +if all components support it. See [Reproducibility](../core_concepts/reproducibility.md) +for the artifact and trusted-source limits. diff --git a/docs/developer_guide/contributing.md b/docs/developer_guide/contributing.md index d09e0b4..b2f1008 100644 --- a/docs/developer_guide/contributing.md +++ b/docs/developer_guide/contributing.md @@ -3,6 +3,9 @@ Thanks for contributing to pretab. This page covers environment setup, the local workflow, and what a pull request needs to pass review. +Read the [architecture contract](architecture.md) before changing how methods are +registered, how fitted state is interpreted, or how modules depend on one another. + ## Code of Conduct All contributors are expected to follow the project diff --git a/docs/index.rst b/docs/index.rst index 43e660c..17f0992 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -68,4 +68,5 @@ :hidden: developer_guide/contributing + developer_guide/architecture developer_guide/release diff --git a/docs/tutorials/custom_representation.md b/docs/tutorials/custom_representation.md index d7b65b5..b00a0e4 100644 --- a/docs/tutorials/custom_representation.md +++ b/docs/tutorials/custom_representation.md @@ -160,4 +160,6 @@ the others. - [Representations overview](../representations/overview.md) to see the built-in families your method joins. - [Extensibility API](../api/extension.rst) for the full signatures. +- [Architecture contract](../developer_guide/architecture.md) for dependency boundaries, + fitted state, and why registration does not enable spec persistence. - The `examples/pretab-chebyshev/` package for a complete, tested template. diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index 6e05ce3..f575da4 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -1,7 +1,6 @@ -"""Executes the python code fences in the tutorial pages so API drift breaks CI -instead of the docs quietly going stale. +"""Executes the Python code fences in tutorials and selected documentation pages. -Each tutorial's ```python blocks run in one shared namespace, in source order, +Each page's ```python blocks run in one shared namespace, in source order, exactly as written on the page. Blocks that only show expected console output (```text fences) are not touched. The companion notebook is kept in sync with its executed tutorial section without notebook-rendering dependencies in CI. @@ -47,6 +46,7 @@ def _code_blocks(path: Path, section: str | None = None) -> list[tuple[int, str] ROOT / "README.md", ROOT / "docs" / "homepage.md", ROOT / "docs" / "getting_started" / "quickstart.md", + ROOT / "docs" / "developer_guide" / "architecture.md", ] From 29b18c1e0c49424e631e15a216cc70a4dd4cb9fc Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 14:55:24 +0100 Subject: [PATCH 78/86] docs: feature in 1.1 release --- docs/getting_started/overview.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/getting_started/overview.md b/docs/getting_started/overview.md index 7473d05..63b5fd9 100644 --- a/docs/getting_started/overview.md +++ b/docs/getting_started/overview.md @@ -176,6 +176,28 @@ try to be an everything-library. The [failure modes](../representations/choosing_a_method.md#when-basis-expansion-does-not-help) section is explicit about where it does not help. +## What's new in PreTab 1.1 + +- **More control per feature.** Set a [width or method options](../core_concepts/configuration.md) + for individual columns, or use a [`FeatureGroup`](../tutorials/multivariate_features.md) + to fit a joint spline across numerical columns. +- **Inspect what was fitted.** Read [actual widths and output lineage](../core_concepts/outputs_and_inspection.md) + and use [`PenaltySpec`](../representations/spline_expansions.md) to align supported + spline penalties with fitted basis coefficients. +- **Use Polars directly.** Pass an [eager `polars.DataFrame`](../core_concepts/configuration.md#polars-dataframe-input) + to `Preprocessor` without PyArrow. +- **Export strict JSON.** [Schema-v1 specs](../core_concepts/reproducibility.md) can + record fit-time settings and output layout. Supported 1.0.0 specs still load in 1.1. + +**Upgrading:** PreTab 1.1 supports Python 3.11 through 3.13. On Python 3.10, +stay on PreTab 1.0.0 or [upgrade Python](installation.md#python-310-migration). + +```{note} +Use fitted attributes and methods in code rather than parsing verbose inspection +text, which may change. Only the thin-plate spline's legacy penalty matrix is +experimental, not its transform. The matrix is not guaranteed positive semidefinite. +``` + ## Where to go next - [Installation](installation.md) sets up PreTab and its optional extras. From 42f0a2dccd45231959e874ded4fefab6101637cc Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 16:08:41 +0100 Subject: [PATCH 79/86] test: define DeepTab contract fixture schema --- .../_fixtures/deeptab_contract/schema-v1.json | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 tests/integration/_fixtures/deeptab_contract/schema-v1.json diff --git a/tests/integration/_fixtures/deeptab_contract/schema-v1.json b/tests/integration/_fixtures/deeptab_contract/schema-v1.json new file mode 100644 index 0000000..319d70c --- /dev/null +++ b/tests/integration/_fixtures/deeptab_contract/schema-v1.json @@ -0,0 +1,171 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "PreTab DeepTab compatibility fixture v1", + "description": "One reproducible, small synthetic case. The case ID identifies the recipe for fit and probe data; the fixture contains no training rows, estimator state, or checkpoint.", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "case_id", + "input_schema", + "constructor_config", + "resolved_config", + "output_feature_names", + "block_widths", + "feature_info_dimensions", + "fingerprint", + "transformed_rows", + "tolerances", + "library_versions" + ], + "properties": { + "schema_version": { "const": 1 }, + "case_id": { "type": "string", "pattern": "^[a-z][a-z0-9_]*$" }, + "input_schema": { + "type": "object", + "description": "Input container and ordered columns used for fit. Names and dtype strings describe the synthetic input before preprocessing.", + "additionalProperties": false, + "required": ["container", "columns"], + "properties": { + "container": { "enum": ["pandas", "polars", "numpy"] }, + "columns": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "dtype"], + "properties": { + "name": { "type": "string" }, + "dtype": { "$ref": "#/$defs/nonempty_string" } + } + } + } + } + }, + "constructor_config": { + "$ref": "#/$defs/config", + "description": "Explicit arguments used to construct PreTab, retaining the requested values and omitted defaults. Decode ordered feature overrides before passing the arguments to PreTab." + }, + "resolved_config": { + "$ref": "#/$defs/config", + "description": "Public get_resolved_config() for the unmodified constructor request, with tuples represented as arrays and ordered feature overrides encoded as entries. This is not fitted state." + }, + "output_feature_names": { + "description": "Exact fitted get_feature_names_out() sequence, also the column order for transformed row values.", + "type": "array", + "items": { "type": "string" } + }, + "block_widths": { + "description": "Block keys and realized column counts from transform(..., return_array=False), in returned order, even for a matrix-output case. Keys are block names, not source labels. Their widths sum to the number of output feature names. Cases do not supply external embeddings.", + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "width"], + "properties": { + "name": { "type": "string" }, + "width": { "$ref": "#/$defs/dimension" } + } + } + }, + "feature_info_dimensions": { + "description": "Only the dimension entries of the three get_feature_info(verbose=False) mappings, keyed by public feature or group name. Display text is not a contract.", + "type": "object", + "additionalProperties": false, + "required": ["numerical", "categorical", "embedding"], + "properties": { + "numerical": { "$ref": "#/$defs/dimensions" }, + "categorical": { "$ref": "#/$defs/dimensions" }, + "embedding": { "$ref": "#/$defs/dimensions" } + } + }, + "fingerprint": { + "description": "Fitted fingerprint_. Compare exactly only when reproducing the recorded qualification environment, including the PreTab revision and library versions; do not require equality across environments.", + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "transformed_rows": { + "description": "Samples from transform on synthetic probe inputs. Row indices are zero-based, unique, and ascending. Flatten blocks in output order and materialize only sampled sparse rows. Each values array has one finite number per output feature name in that order.", + "type": "array", + "minItems": 1, + "maxItems": 8, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["row_index", "values"], + "properties": { + "row_index": { "$ref": "#/$defs/dimension" }, + "values": { "type": "array", "items": { "type": "number" } } + } + } + }, + "tolerances": { + "description": "Metadata and ordering are exact. Only transformed values use abs(actual - expected) <= atol + rtol * abs(expected), with fixture values as expected and both sides finite.", + "type": "object", + "additionalProperties": false, + "required": ["atol", "rtol"], + "properties": { + "atol": { "type": "number", "minimum": 0 }, + "rtol": { "type": "number", "minimum": 0 } + } + }, + "library_versions": { + "description": "Exact generating versions, not supported ranges. Record optional packages as null when absent. The qualification record identifies the tested code revisions and platform.", + "type": "object", + "required": [ + "python", + "pretab", + "numpy", + "pandas", + "scipy", + "scikit_learn", + "polars", + "pyarrow" + ], + "properties": { + "python": { "$ref": "#/$defs/nonempty_string" }, + "pretab": { "$ref": "#/$defs/nonempty_string" }, + "numpy": { "$ref": "#/$defs/nonempty_string" }, + "pandas": { "$ref": "#/$defs/nonempty_string" }, + "scipy": { "$ref": "#/$defs/nonempty_string" }, + "scikit_learn": { "$ref": "#/$defs/nonempty_string" }, + "polars": { "$ref": "#/$defs/optional_version" }, + "pyarrow": { "$ref": "#/$defs/optional_version" } + }, + "additionalProperties": { "$ref": "#/$defs/optional_version" } + } + }, + "$defs": { + "config": { + "type": "object", + "description": "JSON-native settings only. Object member order is not significant. Feature group and source arrays retain their declared order.", + "properties": { + "feature_preprocessing": { + "description": "Encode a non-null label-to-override mapping as ordered entries so JSON member order cannot change reconstruction or the fingerprint.", + "type": ["array", "null"], + "items": { + "type": "object", + "additionalProperties": false, + "required": ["feature", "settings"], + "properties": { + "feature": { "type": "string" }, + "settings": { "type": ["string", "object"] } + } + } + }, + "feature_groups": { + "type": ["array", "null"], + "items": { "type": "object" } + } + } + }, + "dimension": { "type": "integer", "minimum": 0 }, + "dimensions": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/dimension" } + }, + "nonempty_string": { "type": "string", "minLength": 1 }, + "optional_version": { "type": ["string", "null"], "minLength": 1 } + } +} From 6e8412db499e715fd6746ffc776edc9b7c82db54 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Sun, 22 Nov 2026 22:20:00 +0100 Subject: [PATCH 80/86] test: add DeepTab compatibility fixtures and validator --- .github/workflows/ci.yml | 2 +- poetry.lock | 206 +++++++++++++++++- pyproject.toml | 1 + scripts/make_deeptab_contract.py | 148 +++++++++++++ .../v1/dense_blocks_adaptive.json | 150 +++++++++++++ .../v1/dense_numeric_boolean.json | 102 +++++++++ .../v1/sparse_unknown_missing.json | 113 ++++++++++ tests/integration/test_deeptab_contract.py | 84 +++++++ 8 files changed, 804 insertions(+), 2 deletions(-) create mode 100644 scripts/make_deeptab_contract.py create mode 100644 tests/integration/_fixtures/deeptab_contract/v1/dense_blocks_adaptive.json create mode 100644 tests/integration/_fixtures/deeptab_contract/v1/dense_numeric_boolean.json create mode 100644 tests/integration/_fixtures/deeptab_contract/v1/sparse_unknown_missing.json create mode 100644 tests/integration/test_deeptab_contract.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b0def5..45baa10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -167,7 +167,7 @@ jobs: python-version: "3.11" - name: Install with minimum supported dependency series run: >- - python -m pip install . pytest pytest-cov + python -m pip install . pytest pytest-cov 'jsonschema>=4.26,<5' "numpy==1.24.4" "pandas==2.0.3" "scipy==1.10.1" "scikit-learn==1.6.0" - name: Run tests run: python -m pytest tests/ -q diff --git a/poetry.lock b/poetry.lock index 5aa55be..9816bbf 100644 --- a/poetry.lock +++ b/poetry.lock @@ -108,6 +108,18 @@ files = [ astroid = ["astroid (>=2,<5)"] test = ["astroid (>=2,<5)", "pytest (<9.0)", "pytest-cov", "pytest-xdist"] +[[package]] +name = "attrs" +version = "26.1.0" +description = "Classes Without Boilerplate" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309"}, + {file = "attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"}, +] + [[package]] name = "babel" version = "2.18.0" @@ -1429,6 +1441,43 @@ files = [ {file = "joblib-1.5.3.tar.gz", hash = "sha256:8561a3269e6801106863fd0d6d84bb737be9e7631e33aaed3fb9ce5953688da3"}, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +description = "An implementation of JSON Schema validation for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce"}, + {file = "jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326"}, +] + +[package.dependencies] +attrs = ">=22.2.0" +jsonschema-specifications = ">=2023.03.6" +referencing = ">=0.28.4" +rpds-py = ">=0.25.0" + +[package.extras] +format = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3987", "uri-template", "webcolors (>=1.11)"] +format-nongpl = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3986-validator (>0.1.0)", "rfc3987-syntax (>=1.1.0)", "uri-template", "webcolors (>=24.6.0)"] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +description = "The JSON Schema meta-schemas and vocabularies, exposed as a Registry" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe"}, + {file = "jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d"}, +] + +[package.dependencies] +referencing = ">=0.31.0" + [[package]] name = "jupyter-client" version = "8.9.1" @@ -3217,6 +3266,23 @@ Pygments = ">=2.5.1" [package.extras] md = ["comrak (>=0.0.11)"] +[[package]] +name = "referencing" +version = "0.37.0" +description = "JSON Referencing + Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231"}, + {file = "referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8"}, +] + +[package.dependencies] +attrs = ">=22.2.0" +rpds-py = ">=0.7.0" +typing-extensions = {version = ">=4.4.0", markers = "python_version < \"3.13\""} + [[package]] name = "regex" version = "2026.7.10" @@ -3426,6 +3492,144 @@ files = [ {file = "roman_numerals-4.1.0.tar.gz", hash = "sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2"}, ] +[[package]] +name = "rpds-py" +version = "2026.9.1" +description = "Python bindings to Rust's persistent data structures (rpds)" +optional = false +python-versions = ">=3.11" +groups = ["dev"] +files = [ + {file = "rpds_py-2026.9.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:2711d29b653b3bce48a63d18b9c6b53274669e6d6c4094dddeb4d9a0e45128b2"}, + {file = "rpds_py-2026.9.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3231c4c0e521dafa5be0c9f114ee2c2ad46650836f2d72caa86801950c3e7044"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e01b3c878c8641913e688edd1b3f08658c6783d29cf6b826bd3c0d1ae7a1ffaa"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3e524c7874ac72884d28e16dd5b8d839fd09e0fe76b020d3fbca23212a7b8c52"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:761fdae6728ceb99ab182fad2f0cc1e262f610834dc891aea1d1a2a2e634776f"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b723eb406dec5bc9ec516c73ab9c3239a3284e017f7eb89ee2b3258bd504fb7"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:136a1c3fe4402b7008bc81cb62ee538481795b61a7e83df88dff3b3f02b726ff"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:839dde845559254f34885267c6878f60d61d5205180226d976fe488d45fa128e"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:56cd8b3f77d7b6812f533b662186a1f28316931166ddc00fb893b1b0db7e9888"}, + {file = "rpds_py-2026.9.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:074a4d198bc34d9a8ea425114fc3ded6d11ec01f6a314a8db67454a5152d8834"}, + {file = "rpds_py-2026.9.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6beb738155fe8ab8091afdfa5a3226b21c2b1593f1e50ebb90eb25b44dbc0391"}, + {file = "rpds_py-2026.9.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:57492a550a1d88d29d003247e5f78dd8cf04a701fac0e4c8db8745a6d2504e0a"}, + {file = "rpds_py-2026.9.1-cp311-cp311-win32.whl", hash = "sha256:d95a354e02393eada6d7351184671aced9d4cce109dabf927cb7aa99624352a1"}, + {file = "rpds_py-2026.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:ce4d4f52e2a4324396caddbd45a97d8d7be5f42edd25d2355282a9c34f9b2f7f"}, + {file = "rpds_py-2026.9.1-cp311-cp311-win_arm64.whl", hash = "sha256:fdcd198979b4ecffcc1beba366a7fbcf4eb41243691a82fe52ceb0b902f09c12"}, + {file = "rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af"}, + {file = "rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237"}, + {file = "rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3"}, + {file = "rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc"}, + {file = "rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6"}, + {file = "rpds_py-2026.9.1-cp312-cp312-win32.whl", hash = "sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3"}, + {file = "rpds_py-2026.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f"}, + {file = "rpds_py-2026.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02"}, + {file = "rpds_py-2026.9.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9"}, + {file = "rpds_py-2026.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83"}, + {file = "rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c"}, + {file = "rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36"}, + {file = "rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d"}, + {file = "rpds_py-2026.9.1-cp313-cp313-win32.whl", hash = "sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c"}, + {file = "rpds_py-2026.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9"}, + {file = "rpds_py-2026.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f"}, + {file = "rpds_py-2026.9.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b"}, + {file = "rpds_py-2026.9.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86"}, + {file = "rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e"}, + {file = "rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785"}, + {file = "rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118"}, + {file = "rpds_py-2026.9.1-cp314-cp314-win32.whl", hash = "sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc"}, + {file = "rpds_py-2026.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c"}, + {file = "rpds_py-2026.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-win32.whl", hash = "sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e"}, + {file = "rpds_py-2026.9.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9"}, + {file = "rpds_py-2026.9.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0"}, + {file = "rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9"}, + {file = "rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6"}, + {file = "rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7"}, + {file = "rpds_py-2026.9.1-cp315-cp315-win32.whl", hash = "sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429"}, + {file = "rpds_py-2026.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15"}, + {file = "rpds_py-2026.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-win32.whl", hash = "sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4c0d2cb595a420b34d5086db0add011e26e2c09d6a024afbac4228bf8f863a30"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f3d6ed6a98cfd19155996605474982cc470d7601746a6439078f1a5a3fa8b050"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8171b44a054e5c67fd748ada04187f1250bf35b95f85e52ab64bcf3331a923bb"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fda1d96e542c37b6c804547dbf489c129fe7c97183a76a5ec275909ba1a063df"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:270bdcdaac5d5b6f73c5e22e7e135c7f2a50e789f71d9e241d5be8d90026e19a"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:84a6ecc0c940169190d2c23bd969debd48c94dbc855acd60188a68d71d421608"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ab4b2fda7c2b542f7f9d886cc6a838c5079d2b76f72e6081411faba11adde2c9"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:44b32a7c4f0da3d28af31c259e38ddcff096f855e205ed0671d02fcf44f1ea1c"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:a3dbc5ed9514908d5046107d7b1346bde71eea61de6e0e4919c19354f97e769f"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6eae33003518fd4cb4f83a218d5371469dd3001aa3b87128c005b07762f7fe5e"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:0483515261947e4e8b8e1375bf7463e7eb6ccfb3d86e7b554d90cd5285f20f32"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4cfaf02209061880210819934de2f4f6aa83dc04dafe6770276acc240a56da31"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_i686.whl", hash = "sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37"}, + {file = "rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12"}, +] + [[package]] name = "ruff" version = "0.15.12" @@ -4587,4 +4791,4 @@ polars = ["polars"] [metadata] lock-version = "2.1" python-versions = ">=3.11,<3.14" -content-hash = "66f68d8b87c38e61d51fa9863dd71043b7b38764338b8c94d3f78fc4007ce217" +content-hash = "e0214dbfddf78e19d25b36663c3cd5b05fce6b1caf04619fbc65a47cb1c7f39f" diff --git a/pyproject.toml b/pyproject.toml index a980a19..a4a77a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,6 +41,7 @@ scipy = ">=1.10,<2.0" [tool.poetry.group.dev.dependencies] pytest = "^9.0" pytest-cov = "^4.1" +jsonschema = "^4.26" ruff = "0.15.12" # keep in sync with .pre-commit-config.yaml ruff rev pre-commit = "^3.6" commitizen = "^3.29.1" diff --git a/scripts/make_deeptab_contract.py b/scripts/make_deeptab_contract.py new file mode 100644 index 0000000..a0b06e2 --- /dev/null +++ b/scripts/make_deeptab_contract.py @@ -0,0 +1,148 @@ +"""Generate synthetic DeepTab contract fixtures: python -m scripts.make_deeptab_contract.""" + +import argparse +import hashlib +import json +import platform +from dataclasses import dataclass +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +from scipy import sparse + +import pretab + +FIXTURE_DIR = Path(__file__).resolve().parents[1] / "tests/integration/_fixtures/deeptab_contract/v1" +TOLERANCES = {"atol": 1e-9, "rtol": 1e-7} + + +@dataclass(frozen=True) +class ContractCase: + fit_data: pd.DataFrame + probe_data: pd.DataFrame + config: dict[str, Any] + target: np.ndarray | None = None + + +def contract_cases() -> dict[str, ContractCase]: + base = {"numerical_method": "minmax", "categorical_method": "one-hot", "output_structure": "matrix"} + reading = np.arange(32, dtype=np.float64) + target = reading / 100 + (reading >= 8) + 3 * (reading >= 16) + 2 * (reading >= 24) + return { + "dense_numeric_boolean": ContractCase( + pd.DataFrame({"level": [0.0, 2.0, 4.0, 6.0], "flag": [True, False, True, False]}), + pd.DataFrame({"level": [1.0, 5.0], "flag": [False, True]}), + {**base, "output_format": "dense"}, + ), + "sparse_unknown_missing": ContractCase( + pd.DataFrame({"level": [0.0, 2.0, 4.0, 6.0], "city": pd.Series(["a", "b", None, "a"], dtype=object)}), + pd.DataFrame({"level": [1.0, np.nan, 5.0], "city": pd.Series(["new", None, "a"], dtype=object)}), + {**base, "output_format": "sparse", "missing_policy": "separate_state"}, + ), + "dense_blocks_adaptive": ContractCase( + pd.DataFrame({"reading": reading, "city": pd.Series(["a", "b"] * 16, dtype=object)}), + pd.DataFrame({"reading": [2.0, 15.0, 29.0], "city": pd.Series(["a", "b", "a"], dtype=object)}), + { + "output_structure": "blocks", + "output_format": "dense", + "categorical_method": "one-hot", + "feature_preprocessing": {"reading": {"method": "rbf", "output_dim": 12, "adaptive": True}}, + "min_output_dim": 3, + "max_output_dim": 4, + "target_aware": True, + "placement_strategy": "cart", + "random_state": 17, + }, + target, + ), + } + + +def _encode_config(config: dict[str, Any]) -> dict[str, Any]: + encoded = config.copy() + if encoded.get("feature_preprocessing") is not None: + encoded["feature_preprocessing"] = [ + {"feature": feature, "settings": settings} for feature, settings in encoded["feature_preprocessing"].items() + ] + return encoded + + +def _source_digest() -> str: + root = Path(pretab.__file__).resolve().parent + digest = hashlib.sha256() + for source in sorted(root.rglob("*.py")): + digest.update(source.relative_to(root).as_posix().encode("utf-8") + b"\0") + digest.update(source.read_bytes() + b"\0") + return digest.hexdigest() + + +def _optional_version(distribution: str) -> str | None: + try: + return version(distribution) + except PackageNotFoundError: + return None + + +def fixture_environment() -> dict[str, str | None]: + return { + "python": platform.python_version(), + "pretab": pretab.__version__, + "numpy": version("numpy"), + "pandas": version("pandas"), + "scipy": version("scipy"), + "scikit_learn": version("scikit-learn"), + "polars": _optional_version("polars"), + "pyarrow": _optional_version("pyarrow"), + "platform": platform.platform(), + "pretab_source_sha256": _source_digest(), + } + + +def capture_fixture(case_id: str, case: ContractCase, environment: dict[str, str | None]) -> dict[str, Any]: + estimator = pretab.Preprocessor(**case.config).fit(case.fit_data, case.target) + blocks = estimator.transform(case.probe_data, return_array=False) + if not isinstance(blocks, dict): + raise TypeError(f"{case_id}: expected a mapping of transformed blocks") + samples = np.concatenate( + [block.toarray() if sparse.issparse(block) else np.asarray(block) for block in blocks.values()], axis=1 + ) + feature_info = estimator.get_feature_info(verbose=False) + return { + "schema_version": 1, + "case_id": case_id, + "input_schema": { + "container": "pandas", + "columns": [{"name": label, "dtype": str(dtype)} for label, dtype in case.fit_data.dtypes.items()], + }, + "constructor_config": _encode_config(case.config), + "resolved_config": _encode_config(estimator.get_resolved_config()), + "output_feature_names": estimator.get_feature_names_out().tolist(), + "block_widths": [{"name": name, "width": block.shape[1]} for name, block in blocks.items()], + "feature_info_dimensions": { + kind: {name: info["dimension"] for name, info in entries.items()} + for kind, entries in zip(("numerical", "categorical", "embedding"), feature_info, strict=True) + }, + "fingerprint": estimator.fingerprint_, + "transformed_rows": [{"row_index": index, "values": row} for index, row in enumerate(samples.tolist())], + "tolerances": TOLERANCES.copy(), + "library_versions": environment.copy(), + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, default=FIXTURE_DIR) + output_dir = parser.parse_args().output_dir + environment = fixture_environment() + output_dir.mkdir(parents=True, exist_ok=True) + for case_id, case in contract_cases().items(): + fixture = capture_fixture(case_id, case, environment) + path = output_dir / f"{case_id}.json" + path.write_text(json.dumps(fixture, allow_nan=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tests/integration/_fixtures/deeptab_contract/v1/dense_blocks_adaptive.json b/tests/integration/_fixtures/deeptab_contract/v1/dense_blocks_adaptive.json new file mode 100644 index 0000000..c933244 --- /dev/null +++ b/tests/integration/_fixtures/deeptab_contract/v1/dense_blocks_adaptive.json @@ -0,0 +1,150 @@ +{ + "block_widths": [ + { + "name": "num_reading", + "width": 3 + }, + { + "name": "cat_city", + "width": 2 + } + ], + "case_id": "dense_blocks_adaptive", + "constructor_config": { + "categorical_method": "one-hot", + "feature_preprocessing": [ + { + "feature": "reading", + "settings": { + "adaptive": true, + "method": "rbf", + "output_dim": 12 + } + } + ], + "max_output_dim": 4, + "min_output_dim": 3, + "output_format": "dense", + "output_structure": "blocks", + "placement_strategy": "cart", + "random_state": 17, + "target_aware": true + }, + "feature_info_dimensions": { + "categorical": { + "city": 2 + }, + "embedding": {}, + "numerical": { + "reading": 3 + } + }, + "fingerprint": "c9d6212a01ed8375c19b83ac1987d83c246953208cbc22963cb7fb29dbdb51f9", + "input_schema": { + "columns": [ + { + "dtype": "float64", + "name": "reading" + }, + { + "dtype": "object", + "name": "city" + } + ], + "container": "pandas" + }, + "library_versions": { + "numpy": "2.5.3", + "pandas": "2.3.3", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "polars": "1.44.1", + "pretab": "0+unknown", + "pretab_source_sha256": "c6f97dedd6c7a00097198a9b94b5c3bcfebcbe4e5d9657896c3d265733e39642", + "pyarrow": null, + "python": "3.13.2", + "scikit_learn": "1.9.1", + "scipy": "1.18.1" + }, + "output_feature_names": [ + "num_reading_rbf0", + "num_reading_rbf1", + "num_reading_rbf2", + "cat_city_a", + "cat_city_b" + ], + "resolved_config": { + "adaptive": false, + "add_missing_indicator": false, + "cat_cutoff": 0.03, + "categorical_imputation": "most_frequent", + "categorical_method": "one-hot", + "degree": 3, + "dtype": null, + "feature_groups": null, + "feature_preprocessing": [ + { + "feature": "reading", + "settings": { + "adaptive": true, + "max_output_dim": 4, + "method": "rbf", + "min_output_dim": 3, + "name": null, + "output_dim": 12, + "params": { + "random_state": 17, + "task": "regression" + }, + "placement_strategy": "cart", + "target_aware": true + } + } + ], + "max_dense_memory": null, + "max_features_per_input": null, + "max_output_dim": 4, + "max_output_features": null, + "min_output_dim": 3, + "missing_policy": null, + "numerical_imputation": "median", + "numerical_method": "ple", + "output_dim": 7, + "output_format": "dense", + "output_structure": "blocks", + "overflow_policy": "error", + "placement_strategy": "cart", + "policy": null, + "random_state": 17, + "scaling": "minmax", + "target_aware": true, + "task": "regression", + "task_validation": "off", + "treat_all_integers_as_numerical": false, + "verbose": 0 + }, + "schema_version": 1, + "tolerances": { + "atol": 1e-9, + "rtol": 1e-7 + }, + "transformed_rows": [ + { + "row_index": 0, + "values": [ + 0.8714323293149525, 0.46832873356866794, 0.15265839756449998, 1.0, 0.0 + ] + }, + { + "row_index": 1, + "values": [ + 0.8034964449979424, 0.9989599584921346, 0.7532947848528733, 0.0, 1.0 + ] + }, + { + "row_index": 2, + "values": [ + 0.15265839756450006, 0.468328733568668, 0.8714323293149526, 1.0, 0.0 + ] + } + ] +} diff --git a/tests/integration/_fixtures/deeptab_contract/v1/dense_numeric_boolean.json b/tests/integration/_fixtures/deeptab_contract/v1/dense_numeric_boolean.json new file mode 100644 index 0000000..2a154bc --- /dev/null +++ b/tests/integration/_fixtures/deeptab_contract/v1/dense_numeric_boolean.json @@ -0,0 +1,102 @@ +{ + "block_widths": [ + { + "name": "num_level", + "width": 1 + }, + { + "name": "cat_flag", + "width": 2 + } + ], + "case_id": "dense_numeric_boolean", + "constructor_config": { + "categorical_method": "one-hot", + "numerical_method": "minmax", + "output_format": "dense", + "output_structure": "matrix" + }, + "feature_info_dimensions": { + "categorical": { + "flag": 2 + }, + "embedding": {}, + "numerical": { + "level": 1 + } + }, + "fingerprint": "839863e13e2b2b8a5da62c73fc1f6e9e78ef4fb24d5cf9922eb81eed9c75efc2", + "input_schema": { + "columns": [ + { + "dtype": "float64", + "name": "level" + }, + { + "dtype": "bool", + "name": "flag" + } + ], + "container": "pandas" + }, + "library_versions": { + "numpy": "2.5.3", + "pandas": "2.3.3", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "polars": "1.44.1", + "pretab": "0+unknown", + "pretab_source_sha256": "c6f97dedd6c7a00097198a9b94b5c3bcfebcbe4e5d9657896c3d265733e39642", + "pyarrow": null, + "python": "3.13.2", + "scikit_learn": "1.9.1", + "scipy": "1.18.1" + }, + "output_feature_names": ["num_level", "cat_flag_False", "cat_flag_True"], + "resolved_config": { + "adaptive": false, + "add_missing_indicator": false, + "cat_cutoff": 0.03, + "categorical_imputation": "most_frequent", + "categorical_method": "one-hot", + "degree": 3, + "dtype": null, + "feature_groups": null, + "feature_preprocessing": null, + "max_dense_memory": null, + "max_features_per_input": null, + "max_output_dim": 10, + "max_output_features": null, + "min_output_dim": 7, + "missing_policy": null, + "numerical_imputation": "median", + "numerical_method": "minmax", + "output_dim": 7, + "output_format": "dense", + "output_structure": "matrix", + "overflow_policy": "error", + "placement_strategy": "cart", + "policy": null, + "random_state": null, + "scaling": "minmax", + "target_aware": true, + "task": "regression", + "task_validation": "off", + "treat_all_integers_as_numerical": false, + "verbose": 0 + }, + "schema_version": 1, + "tolerances": { + "atol": 1e-9, + "rtol": 1e-7 + }, + "transformed_rows": [ + { + "row_index": 0, + "values": [0.16666666666666666, 1.0, 0.0] + }, + { + "row_index": 1, + "values": [0.8333333333333333, 0.0, 1.0] + } + ] +} diff --git a/tests/integration/_fixtures/deeptab_contract/v1/sparse_unknown_missing.json b/tests/integration/_fixtures/deeptab_contract/v1/sparse_unknown_missing.json new file mode 100644 index 0000000..f909082 --- /dev/null +++ b/tests/integration/_fixtures/deeptab_contract/v1/sparse_unknown_missing.json @@ -0,0 +1,113 @@ +{ + "block_widths": [ + { + "name": "num_level", + "width": 2 + }, + { + "name": "cat_city", + "width": 3 + } + ], + "case_id": "sparse_unknown_missing", + "constructor_config": { + "categorical_method": "one-hot", + "missing_policy": "separate_state", + "numerical_method": "minmax", + "output_format": "sparse", + "output_structure": "matrix" + }, + "feature_info_dimensions": { + "categorical": { + "city": 3 + }, + "embedding": {}, + "numerical": { + "level": 2 + } + }, + "fingerprint": "14164e900a40b231002e29d6d2e583ce831149c4d1869b58a780bc732d6e406d", + "input_schema": { + "columns": [ + { + "dtype": "float64", + "name": "level" + }, + { + "dtype": "object", + "name": "city" + } + ], + "container": "pandas" + }, + "library_versions": { + "numpy": "2.5.3", + "pandas": "2.3.3", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "polars": "1.44.1", + "pretab": "0+unknown", + "pretab_source_sha256": "c6f97dedd6c7a00097198a9b94b5c3bcfebcbe4e5d9657896c3d265733e39642", + "pyarrow": null, + "python": "3.13.2", + "scikit_learn": "1.9.1", + "scipy": "1.18.1" + }, + "output_feature_names": [ + "num_level__representation__level", + "num_level__missing__level__missing", + "cat_city__representation__city_a", + "cat_city__representation__city_b", + "cat_city__missing__city__missing" + ], + "resolved_config": { + "adaptive": false, + "add_missing_indicator": false, + "cat_cutoff": 0.03, + "categorical_imputation": "most_frequent", + "categorical_method": "one-hot", + "degree": 3, + "dtype": null, + "feature_groups": null, + "feature_preprocessing": null, + "max_dense_memory": null, + "max_features_per_input": null, + "max_output_dim": 10, + "max_output_features": null, + "min_output_dim": 7, + "missing_policy": "separate_state", + "numerical_imputation": "median", + "numerical_method": "minmax", + "output_dim": 7, + "output_format": "sparse", + "output_structure": "matrix", + "overflow_policy": "error", + "placement_strategy": "cart", + "policy": null, + "random_state": null, + "scaling": "minmax", + "target_aware": true, + "task": "regression", + "task_validation": "off", + "treat_all_integers_as_numerical": false, + "verbose": 0 + }, + "schema_version": 1, + "tolerances": { + "atol": 1e-9, + "rtol": 1e-7 + }, + "transformed_rows": [ + { + "row_index": 0, + "values": [0.16666666666666666, 0.0, 0.0, 0.0, 0.0] + }, + { + "row_index": 1, + "values": [0.5, 1.0, 1.0, 0.0, 1.0] + }, + { + "row_index": 2, + "values": [0.8333333333333333, 0.0, 1.0, 0.0, 0.0] + } + ] +} diff --git a/tests/integration/test_deeptab_contract.py b/tests/integration/test_deeptab_contract.py new file mode 100644 index 0000000..f37ea01 --- /dev/null +++ b/tests/integration/test_deeptab_contract.py @@ -0,0 +1,84 @@ +"""Validate the synthetic fixtures consumed by the DeepTab compatibility harness.""" + +import json + +import numpy as np +import pytest +from jsonschema import Draft202012Validator +from scipy import sparse + +from pretab import Preprocessor +from scripts.make_deeptab_contract import FIXTURE_DIR, capture_fixture, contract_cases, fixture_environment + +CASES = contract_cases() + + +@pytest.fixture(scope="module") +def schema_validator(): + schema = json.loads((FIXTURE_DIR.parent / "schema-v1.json").read_bytes()) + Draft202012Validator.check_schema(schema) + return Draft202012Validator(schema) + + +def test_fixture_catalog_matches_case_recipes(): + assert {path.stem for path in FIXTURE_DIR.glob("*.json")} == set(CASES) + + +@pytest.mark.parametrize("case_id", CASES) +def test_fitted_deeptab_contract(case_id, schema_validator): + expected = json.loads((FIXTURE_DIR / f"{case_id}.json").read_bytes()) + json.dumps(expected, allow_nan=False) + schema_validator.validate(expected) + + actual = capture_fixture(case_id, CASES[case_id], fixture_environment()) + actual = json.loads(json.dumps(actual, allow_nan=False)) + for field in expected.keys() - {"fingerprint", "transformed_rows", "library_versions"}: + assert actual[field] == expected[field], field + + if actual["library_versions"] == expected["library_versions"]: + assert actual["fingerprint"] == expected["fingerprint"] + + width = len(expected["output_feature_names"]) + assert sum(block["width"] for block in expected["block_widths"]) == width + for expected_row, actual_row in zip(expected["transformed_rows"], actual["transformed_rows"], strict=True): + assert actual_row["row_index"] == expected_row["row_index"] + assert len(expected_row["values"]) == len(actual_row["values"]) == width + np.testing.assert_allclose( + actual_row["values"], expected_row["values"], equal_nan=False, **expected["tolerances"] + ) + + +@pytest.mark.parametrize("case_id", CASES) +def test_deeptab_case_preserves_output_mode_and_column_order(case_id): + case = CASES[case_id] + estimator = Preprocessor(**case.config).fit(case.fit_data, case.target) + result = estimator.transform(case.probe_data) + blocks = estimator.transform(case.probe_data, return_array=False) + matrix = estimator.transform(case.probe_data, return_array=True) + + def dense(values): + return values.toarray() if sparse.issparse(values) else np.asarray(values) + + assert isinstance(blocks, dict) + np.testing.assert_array_equal(np.concatenate([dense(block) for block in blocks.values()], axis=1), dense(matrix)) + assert dense(matrix).shape[1] == len(estimator.get_feature_names_out()) + + if case_id == "dense_numeric_boolean": + assert isinstance(result, np.ndarray) + assert estimator.get_feature_names_out().tolist() == ["num_level", "cat_flag_False", "cat_flag_True"] + np.testing.assert_allclose(result, [[1 / 6, 1, 0], [5 / 6, 0, 1]], equal_nan=False) + elif case_id == "sparse_unknown_missing": + assert sparse.issparse(result) + np.testing.assert_array_equal(dense(blocks["num_level"])[:, -1], [0, 1, 0]) + city = dense(blocks["cat_city"]) + assert not city[0].any() + np.testing.assert_array_equal(city[:, -1], [0, 1, 0]) + assert city[2, :-1].sum() == 1 + else: + assert isinstance(result, dict) + assert list(result) == ["num_reading", "cat_city"] + assert all(isinstance(block, np.ndarray) for block in result.values()) + numerical, categorical, embeddings = estimator.get_feature_info(verbose=False) + assert 3 <= result["num_reading"].shape[1] == numerical["reading"]["dimension"] <= 4 + assert result["cat_city"].shape[1] == categorical["city"]["dimension"] == 2 + assert not embeddings From 975787aef47ed3d19483255fea594bc8d04a8a51 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 23 Nov 2026 12:12:59 +0100 Subject: [PATCH 81/86] docs: refresh README and homepage for PreTab 1.1 --- README.md | 50 ++++++++++++++++++++--------------------- docs/homepage.md | 58 ++++++++++++++++++++++-------------------------- 2 files changed, 51 insertions(+), 57 deletions(-) diff --git a/README.md b/README.md index 914f217..5e54a46 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,13 @@ embeddings) is also available as a standalone transformer. Because it speaks the API, PreTab drops straight into `Pipeline` and `ColumnTransformer` workflows and accepts any sklearn transformer alongside its own. -Beyond the transformers themselves, every fitted representation is self-describing: it -reports per-output-column lineage, guards supervised methods against leakage, serializes to -a portable versioned spec, and can be extended with your own representations through a -public, discoverable protocol. +Fitted preprocessors report which inputs produced each output column. PreTab warns when +supervised transformers are fitted outside a pipeline or cross-validation context. Supported +fitted state can be exported to a versioned JSON spec for restoration in the same environment. +Load specs only from trusted sources. You can also register your own representations. + +See [What's new in PreTab 1.1](https://pretab.readthedocs.io/en/latest/getting_started/overview.html#whats-new-in-pretab-1-1) +for release highlights and upgrade guidance. ## Why PreTab? @@ -63,16 +66,17 @@ import pandas as pd from pretab import Preprocessor +rng = np.random.default_rng(0) df = pd.DataFrame({ - "age": np.random.randint(18, 65, size=100), - "income": np.random.normal(60_000, 15_000, size=100).astype(int), - "city": np.random.choice(["Berlin", "Munich", "Hamburg"], size=100), - "experience": np.random.randint(0, 40, size=100), + "age": rng.integers(18, 65, size=100), + "income": rng.normal(60_000, 15_000, size=100).astype(int), + "city": rng.choice(["Berlin", "Munich", "Hamburg"], size=100), + "experience": rng.integers(0, 40, size=100), }) -y = np.random.randn(100) +y = rng.standard_normal(100) # Global strategies: PLE for numerics, integer codes for categoricals -preprocessor = Preprocessor(numerical_method="ple", categorical_method="int") +preprocessor = Preprocessor(numerical_method="ple", categorical_method="int", task="regression") X = preprocessor.fit_transform(df, y) # single stacked array, one row per sample @@ -175,7 +179,8 @@ pip install pretab ```bash pip install "pretab[embeddings]" # adds sentence-transformers, for the `pretrained` strategy pip install "pretab[lightgbm]" # adds lightgbm, for placement_strategy="lightgbm" -pip install "pretab[all]" # both of the above +pip install "pretab[polars]" # adds Polars for eager DataFrame input +pip install "pretab[all]" # all three extras ``` > **Note:** The core install has no heavy dependencies. Each extra is opt-in and only @@ -206,29 +211,22 @@ preprocessor = Preprocessor( feature_preprocessing={ "age": "ple", "income": "rbf", - "experience": "quantile", + "experience": {"method": "quantile", "params": {"n_quantiles": len(df)}}, "city": "one-hot", }, task="regression", ) -X_array = preprocessor.fit_transform(df, y) # single stacked ndarray -X_dict = preprocessor.transform(df, return_array=False) # {"num_age": ..., "cat_city": ...} +X_array = preprocessor.fit_transform(df, y) +X_dict = preprocessor.transform(df, return_array=False) -preprocessor.get_feature_info(verbose=True) # inspect resolved strategies +assert X_array.shape == (100, 18) +assert X_dict["cat_city"].shape == (100, 3) +assert len(preprocessor.get_feature_lineage()) == X_array.shape[1] ``` -`get_feature_info(verbose=True)` prints the resolved layout so you can confirm every column -at a glance: - -```text -feature kind pipeline dim cats -------------------------------------------------------------------- -age numerical imputer -> minmax -> ple 7 - -income numerical imputer -> minmax -> rbf 7 - -experience numerical imputer -> minmax -> quantile 1 - -city categorical imputer -> onehot -> to_float 3 3 -``` +The three cities produce three one-hot columns. `get_feature_lineage()` maps each output +column back to its source feature and representation. > **Note:** `transform` returns a single stacked array by default, so a `Preprocessor` drops > straight into a plain `sklearn.pipeline.Pipeline`. Pass `output_structure="blocks"` (or diff --git a/docs/homepage.md b/docs/homepage.md index 4112bd8..fd1e12b 100644 --- a/docs/homepage.md +++ b/docs/homepage.md @@ -35,7 +35,7 @@ compose standalone representations with scikit-learn transformers and estimators :::{grid-item-card} 🧠 Smart defaults Automatic feature-type detection (numerical vs. categorical) with support for -`pandas.DataFrame`, `polars.DataFrame` and `numpy.ndarray` inputs. +`pandas.DataFrame`, eager `polars.DataFrame` and `numpy.ndarray` inputs. ::: :::: @@ -47,50 +47,46 @@ import numpy as np import pandas as pd from pretab import Preprocessor +rng = np.random.default_rng(0) df = pd.DataFrame({ - "age": np.random.randint(18, 65, size=100), - "income": np.random.normal(60_000, 15_000, size=100).astype(int), - "city": np.random.choice(["Berlin", "Munich", "Hamburg"], size=100), + "age": rng.integers(18, 65, size=100), + "income": rng.normal(60_000, 15_000, size=100).astype(int), + "city": rng.choice(["Berlin", "Munich", "Hamburg"], size=100), }) -y = np.random.randn(100) +y = rng.standard_normal(100) # One strategy per feature type: PLE for numerics, integer codes for categoricals -pre = Preprocessor(numerical_method="ple", categorical_method="int") -X = pre.fit_transform(df, y) # single stacked, model-ready array -X.shape -# (100, 15) +pre = Preprocessor(numerical_method="ple", categorical_method="int", task="regression") +X = pre.fit_transform(df, y) +assert X.shape == (100, 15) +assert len(pre.get_feature_lineage()) == X.shape[1] ``` -`Preprocessor` detects the column types, fits a strategy per column, and returns a single -stacked, model-ready array by default, so it drops straight into a plain -`sklearn.pipeline.Pipeline`; pass `output_structure="blocks"` for a dict of per-feature blocks -instead. Inspect the resolved layout at any time with `get_feature_info(verbose=True)`: - -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> ple 7 - -income numerical imputer -> minmax -> ple 7 - -city categorical imputer -> continuous_ordinal 1 4 -``` +`Preprocessor` detects column types and returns one array by default. Pass +`output_structure="blocks"` to get a dictionary of feature blocks instead. After fitting, +`get_feature_lineage()` traces each output column back to its input. ### Mix strategies per column -Columns rarely want the same treatment. Pass a `feature_preprocessing` map to give each -column its own strategy, and a single `fit` still returns one coherent feature set: +Use `feature_preprocessing` to choose a different strategy for each column. The output +still has one row per input sample: ```python -pre = Preprocessor(feature_preprocessing={ - "age": "ple", # piecewise-linear encoding - "income": "rbf", # radial-basis expansion - "city": "one-hot", # one-hot categorical -}) +pre = Preprocessor( + feature_preprocessing={ + "age": "ple", + "income": "rbf", + "city": "one-hot", + }, + task="regression", +) X = pre.fit_transform(df, y) - -X.shape -# (100, 17) +assert X.shape == (100, 17) ``` +See [What's new in PreTab 1.1](getting_started/overview.md#whats-new-in-pretab-11) +for per-feature widths, grouped splines, and other 1.1 changes. + ## Get started ::::{grid} 1 1 3 3 From 5ddca1f7e1b48fd12de8fab2f6db9f372bdc7dd1 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 23 Nov 2026 12:13:07 +0100 Subject: [PATCH 82/86] docs(api): clarify contracts and fix runnable examples --- docs/api/preprocessor.rst | 7 ++++--- docs/api/search_and_cross_fitting.rst | 5 +++++ pretab/embedding/language.py | 5 +++-- pretab/encoding/numerical/ple.py | 9 ++++++++- pretab/expansion/functional/rbf.py | 5 ++--- pretab/expansion/functional/relu.py | 5 ++--- pretab/expansion/functional/sigmoid.py | 5 ++--- pretab/expansion/functional/tanh.py | 5 ++--- 8 files changed, 28 insertions(+), 18 deletions(-) diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index 12d5a50..d5f951d 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -1,9 +1,10 @@ Preprocessor ============ -The high-level entry point. :class:`~pretab.Preprocessor` reads a ``DataFrame``, -detects feature types, resolves per-column and grouped representations from a single -configuration, and produces model-ready output with full lineage. +The high-level entry point. :class:`~pretab.Preprocessor` accepts a pandas +DataFrame, an eager Polars DataFrame, a NumPy array, or a dictionary of columns. +It detects feature types, resolves per-column and grouped representations from a +single configuration, and produces model-ready output with full lineage. .. currentmodule:: pretab diff --git a/docs/api/search_and_cross_fitting.rst b/docs/api/search_and_cross_fitting.rst index 7758e67..d094078 100644 --- a/docs/api/search_and_cross_fitting.rst +++ b/docs/api/search_and_cross_fitting.rst @@ -31,6 +31,11 @@ Cross-fitting Produce out-of-fold training features from a supervised transformer while transforming new data with an all-data model. +A wrapped :class:`~pretab.Preprocessor` must use ``output_structure="matrix"``. +Cross-fitting accepts dense arrays, sparse matrices, and DataFrames as output, +but not dictionaries of feature blocks. Each fold must match the all-data +model's output width and, for DataFrames, its column names and order. + The wrapper's keyword-only ``task_validation`` checks its splitter's configured task. It does not replace the wrapped estimator's policy. If a later pipeline step needs transformed inputs to determine target use, it checks when those diff --git a/pretab/embedding/language.py b/pretab/embedding/language.py index 71c0479..b27bbc7 100644 --- a/pretab/embedding/language.py +++ b/pretab/embedding/language.py @@ -38,8 +38,9 @@ class LanguageEmbeddingTransformer(TransformerMixin, BaseEstimator): Notes ----- - Requires the optional ``sentence-transformers`` dependency. Install it with - ``pip install sentence-transformers`` or pass a preloaded ``model``. + Install ``pretab[embeddings]`` to use the default model. The first call to + ``fit`` may download the model weights if they are not cached. Pass a + preloaded ``model`` to skip model loading. Examples -------- diff --git a/pretab/encoding/numerical/ple.py b/pretab/encoding/numerical/ple.py index c09a07c..d0b6c74 100644 --- a/pretab/encoding/numerical/ple.py +++ b/pretab/encoding/numerical/ple.py @@ -107,10 +107,17 @@ class PLETransformer( Examples -------- + Inspect the encoding on the data used to fit it. Because PLE uses the target + to place breakpoints, this emits :class:`~pretab.LeakageWarning`. Use + :class:`~pretab.CrossFittedTransformer` to produce out-of-fold training + features for a downstream model. + >>> from sklearn.datasets import make_regression + >>> from pretab.transformers import PLETransformer >>> X, y = make_regression(n_samples=100, n_features=5, noise=10, random_state=51) >>> ple = PLETransformer(output_dim=10, task="regression") - >>> X_transformed = ple.fit_transform(X, y) + >>> ple.fit_transform(X, y).shape + (100, 50) """ _param_aliases: ClassVar[dict[str, str]] = {} diff --git a/pretab/expansion/functional/rbf.py b/pretab/expansion/functional/rbf.py index a35e229..bdacdd2 100644 --- a/pretab/expansion/functional/rbf.py +++ b/pretab/expansion/functional/rbf.py @@ -75,9 +75,8 @@ class RBFExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import RBFExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = RBFExpansionTransformer(output_dim=3, gamma=0.5, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - RBFExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/functional/relu.py b/pretab/expansion/functional/relu.py index 624ffda..16cf126 100644 --- a/pretab/expansion/functional/relu.py +++ b/pretab/expansion/functional/relu.py @@ -77,9 +77,8 @@ class ReLUExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import ReLUExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = ReLUExpansionTransformer(output_dim=3, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - ReLUExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/functional/sigmoid.py b/pretab/expansion/functional/sigmoid.py index 31fe989..fb8fed3 100644 --- a/pretab/expansion/functional/sigmoid.py +++ b/pretab/expansion/functional/sigmoid.py @@ -75,9 +75,8 @@ class SigmoidExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import SigmoidExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = SigmoidExpansionTransformer(output_dim=3, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - SigmoidExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/functional/tanh.py b/pretab/expansion/functional/tanh.py index 5b4a195..c308e6f 100644 --- a/pretab/expansion/functional/tanh.py +++ b/pretab/expansion/functional/tanh.py @@ -75,9 +75,8 @@ class TanhExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import TanhExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = TanhExpansionTransformer(output_dim=3, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - TanhExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ From 181f68343e261968bfb186736b4014b08a6b6b41 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 23 Nov 2026 12:22:55 +0100 Subject: [PATCH 83/86] docs: fix core concepts examples and expand snippet coverage --- docs/core_concepts/configuration.md | 16 ++ docs/core_concepts/missing_values.md | 14 +- docs/core_concepts/outputs_and_inspection.md | 167 ++++++++---------- docs/core_concepts/reproducibility.md | 32 ++-- .../core_concepts/resolution_and_placement.md | 16 +- docs/core_concepts/target_awareness.md | 38 ++-- tests/doc_snippets/test_tutorial_snippets.py | 25 +-- 7 files changed, 157 insertions(+), 151 deletions(-) diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index f58b654..a22feb3 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -170,6 +170,16 @@ left out falls back to `numerical_method`, and any categorical column left out f column is fit with the global default's transformer, exactly as if you had listed it yourself. ```python +import pandas as pd + +df = pd.DataFrame({ + "age": np.linspace(25.0, 63.0, 20), + "income": np.linspace(25_000.0, 90_000.0, 20), + "city": ["Oslo", "Lima"] * 10, + "region": ["north", "south"] * 10, +}) +y = 0.4 * df["age"] + 0.0002 * df["income"] + pre = Preprocessor( numerical_method="bspline", # applies to every numerical column not listed below feature_preprocessing={ @@ -177,6 +187,12 @@ pre = Preprocessor( "city": "one-hot", }, ).fit(df, y) + +numerical, categorical, _ = pre.get_feature_info(verbose=False) +assert numerical["age"]["preprocessing"].endswith("bspline") +assert numerical["income"]["preprocessing"].endswith("rbf") +assert categorical["city"]["dimension"] == 2 +assert categorical["region"]["dimension"] == 1 ``` | Column | Kind | Listed in `feature_preprocessing`? | Resolved method | diff --git a/docs/core_concepts/missing_values.md b/docs/core_concepts/missing_values.md index 5a2ddbb..249f8ab 100644 --- a/docs/core_concepts/missing_values.md +++ b/docs/core_concepts/missing_values.md @@ -61,13 +61,13 @@ that cannot be fitted on a constant column. For finer control, `missing_policy` selects one of five behaviours for the whole preprocessor. -| Policy | Behaviour | -| ------------------------- | --------------------------------------------------------------------------------------------------- | -| `"error"` | Reject any missing value at `fit` and `transform`. | -| `"propagate"` | Pass missing values through to the transformer unchanged. | -| `"impute"` | Fill using the imputation parameters above. | -| `"impute_with_indicator"` | Impute and add a missing indicator column. | -| `"separate_state"` | Impute the basis, and add a dedicated `__missing` column that does not activate the ordinary basis. | +| Policy | Behaviour | +| ------------------------- | -------------------------------------------------------------------------------------- | +| `"error"` | Reject any missing value at `fit` and `transform`. | +| `"propagate"` | Pass missing values through to the transformer unchanged. | +| `"impute"` | Fill using the imputation parameters above. | +| `"impute_with_indicator"` | Impute and add a missing indicator column. | +| `"separate_state"` | Transform the imputed value as usual and add a dedicated `__missing` indicator column. | ```python pre = Preprocessor(missing_policy="separate_state") diff --git a/docs/core_concepts/outputs_and_inspection.md b/docs/core_concepts/outputs_and_inspection.md index 5c5618d..acbc352 100644 --- a/docs/core_concepts/outputs_and_inspection.md +++ b/docs/core_concepts/outputs_and_inspection.md @@ -10,11 +10,23 @@ feature names, lineage, and the output budget. `fit_transform` and `transform` return a single stacked `numpy.ndarray` by default. Pass `output_structure="blocks"` (or `return_array=False` for a single call) to receive a dictionary that maps each feature to its transformed block instead, with keys prefixed -`num_` or `cat_`. +`num_` or `cat_`. A [feature group](configuration.md#feature-groups) has one block +with a `group_` prefix. ```python -X_array = pre.fit_transform(df, y) # one stacked ndarray -X_dict = Preprocessor(output_structure="blocks").fit_transform(df, y) # {"num_age": ..., "cat_city": ...} +import numpy as np +import pandas as pd +from pretab import Preprocessor + +df = pd.DataFrame({"age": [25, 40, 63], "city": ["A", "B", "A"]}) +y = [0.1, 0.9, 0.3] + +pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot") +X_array = pre.fit_transform(df) +X_dict = pre.transform(df, return_array=False) + +assert X_array.shape == (3, 3) +assert set(X_dict) == {"num_age", "cat_city"} ``` ```{note} @@ -26,19 +38,20 @@ for feeding blocks to different model heads; pass `return_array` explicitly to o ### Example: one column expands into several -A single input column rarely maps to a single output column. Most numerical methods (splines, -feature maps, PLE) expand one feature into `output_dim` basis columns, so the matrix width -grows well beyond the number of input columns. A B-spline makes this concrete: `output_dim=6` -turns the one `age` column into 6 local basis functions, each capturing a different region of -its range. +Many numerical representations expand one input into several columns. A B-spline with +`output_dim=6` turns the `age` column into six local basis functions, each covering a +different part of its range. ```python -df = pd.DataFrame({"age": [25, 40, 63, 51]}) -y = [0.1, 0.9, 0.3, 0.6] - -pre = Preprocessor(numerical_method="bspline", output_dim=6, - target_aware=False, placement_strategy="quantile").fit(df, y) -out = pre.transform(df) +ages = pd.DataFrame({"age": [25, 40, 63, 51]}) + +pre_spline = Preprocessor( + numerical_method="bspline", output_dim=6, + target_aware=False, placement_strategy="quantile", +).fit(ages) +out = pre_spline.transform(ages) +assert out.shape == (4, 6) +np.testing.assert_allclose(out.sum(axis=1), 1.0) out.shape ``` @@ -46,6 +59,10 @@ out.shape (4, 6) ``` +```python +out.round(3) +``` + ```text array([[1. , 0. , 0. , 0. , 0. , 0. ], [0. , 0.179, 0.593, 0.228, 0. , 0. ], @@ -59,22 +76,18 @@ basis is a partition of unity). `get_feature_names_out()` shows exactly where ea from: ```python -list(pre.get_feature_names_out()) +list(pre_spline.get_feature_names_out()) ``` ```text ['num_age_bs0', 'num_age_bs1', 'num_age_bs2', 'num_age_bs3', 'num_age_bs4', 'num_age_bs5'] ``` -All six still trace back to the single `age` input, which is exactly what `output_structure= -"blocks"` reflects: one dict entry per **input** feature, holding its full expanded block, not -one entry per output column. +All six still trace back to the single `age` input. In block output, `num_age` holds all +six columns together. ```python -pre_blocks = Preprocessor(numerical_method="bspline", output_dim=6, - target_aware=False, placement_strategy="quantile", - output_structure="blocks").fit(df, y) -pre_blocks.transform(df)["num_age"].shape +pre_spline.transform(ages, return_array=False)["num_age"].shape ``` ```text @@ -82,10 +95,8 @@ pre_blocks.transform(df)["num_age"].shape ``` ```{tip} -This is why a wide expansion (a spline or feature map with a large `output_dim`, or several -expanded columns) can produce a much wider matrix than the input `DataFrame` had columns. -Use `get_feature_info(verbose=True)` (below) or `estimate_output_shape(df)` to see the total -width before committing, especially with several expanded columns at once. +After fitting, use `get_feature_info(verbose=True)` to see the width of each block or +`estimate_output_shape(X)` to estimate the shape for a new batch without transforming it. ``` ## Output format and dtype @@ -102,14 +113,16 @@ even for a single row. Default `"dense"`. : The floating-point precision of the output, for example `numpy.float32` to halve memory. ```python -pre = Preprocessor(output_format="auto", dtype="float32") +pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot", + output_format="auto", dtype="float32").fit(df) ``` -After fitting, `output_report_` summarizes what was produced: the chosen format, dimensions, -density, and memory saved. +After a call to `transform`, `output_report_` summarizes that batch's format, dimensions, +density, and memory use. Calling `fit_transform` also populates the report. ```python -pre.fit(df, y) +out = pre.transform(df) +assert out.dtype == np.float32 pre.output_report_ ``` @@ -140,17 +153,7 @@ sparse), and `set_output` (scikit-learn's own DataFrame protocol). This section decision guide: what each one controls, how they interact, and which combination fits a given use case, with the literal output shown for each rather than just a description of it. -The examples below all share the same tiny, fixed input so the printed output is directly -comparable: - -```python -import numpy as np -import pandas as pd -from pretab import Preprocessor - -df = pd.DataFrame({"age": [25, 40, 63], "city": ["A", "B", "A"]}) -y = [0.1, 0.9, 0.3] -``` +The examples below reuse the three-row `df` from [Output shapes](#output-shapes). ### Parameter impact at a glance @@ -239,14 +242,18 @@ independently of `output_structure`: a sparse `"matrix"` is a single stacked `scipy.sparse.csr_matrix`, and a sparse `"blocks"` dict holds a CSR matrix per feature. ```python +from scipy.sparse import isspmatrix_csr + pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot", output_format="sparse").fit(df, y) -pre.transform(df) +out = pre.transform(df) +assert isspmatrix_csr(out) +assert (out.shape, out.nnz) == ((3, 3), 5) +out.shape, out.nnz ``` ```text - +((3, 3), 5) ``` Halving memory on a large dataset @@ -320,39 +327,17 @@ list(pipe.fit(X, [0.0, 1.0, 1.0, 0.0]).get_feature_names_out()) ['num_age', 'num_income'] ``` -Use `get_feature_info(verbose=True)` for a human-readable table of the resolved per-feature -pipeline, output width, and category count. - -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> bspline 13 - -income numerical imputer -> minmax -> ple 12 - -city categorical imputer -> onehot -> to_float 4 4 -``` - -`verbose=True` is the default, so `get_feature_info()` both logs that table and returns the -same data as a tuple of dicts, one per feature kind, keyed by input column name: +`get_feature_info()` logs a table with the fitted pipelines, widths, and category counts. +It also returns three dictionaries for numerical, categorical, and embedding blocks. +Pass `verbose=False` to return the same data without logging the table. ```python -pre.get_feature_info() -``` +numerical, categorical, embeddings = pre.get_feature_info() -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> bspline 7 - -income numerical imputer -> minmax -> rbf 7 - -city categorical imputer -> onehot -> to_float 3 3 -``` - -```python -( - {"age": {"preprocessing": "imputer -> minmax -> bspline", "dimension": 7, "categories": None}, - "income": {"preprocessing": "imputer -> minmax -> rbf", "dimension": 7, "categories": None}}, - {"city": {"preprocessing": "imputer -> onehot -> to_float", "dimension": 3, "categories": 3}}, - {}, -) +assert numerical["age"]["dimension"] == 1 +assert categorical["city"]["dimension"] == 2 +assert categorical["city"]["categories"] == 2 +assert embeddings == {} ``` After the table, `get_feature_info()` logs the effective settings recorded at fit time @@ -363,11 +348,8 @@ do not change the recorded settings. Use `get_resolved_config()` for current set Older fits without a settings record report that it is unavailable. ```{tip} -`get_feature_info()` is a handy, no-setup way to check exactly what happened to each feature: -which pipeline it went through, how many output columns it produced, and (for categoricals) -how many categories were seen. Pass `verbose=False` to get just the returned dicts, silently. -For other fitted details (total output width, per-feature output counts, the last -`transform`'s memory report), see the `Preprocessor` **Attributes** in the +For programmatic checks, compare the returned dimensions with `output_dims_` or use +`total_output_dim_` to size a downstream model. See the `Preprocessor` attributes in the [API reference](../api/preprocessor.rst). ``` @@ -393,12 +375,12 @@ running PreTab inside a larger training script or notebook. | `3` | Also logs internal fitted decisions (bins, knots, centers). | ```python -Preprocessor(numerical_method="ple", verbose=1).fit(df, y) +logged = Preprocessor(numerical_method="ple", task="regression", verbose=1).fit(df, y) +assert logged.total_output_dim_ == 8 ``` -```text -fit complete: 2 numerical (ple) + 1 categorical (int) feature(s) -> 15 output columns in 0.02s -``` +This fit logs one numerical feature (`ple`), one categorical feature (`int`), eight output +columns, and the elapsed time. Each fit applies its own level, so a later `verbose=2` fit in the same process or notebook logs the table even after a `verbose=1` fit. PreTab attaches its own stream handler only when no host @@ -447,8 +429,8 @@ model fit on top of the expansion. ## Output budget -Expansions can multiply columns quickly, especially wide splines or high-cardinality one-hot. -The output budget lets you cap the blast radius and estimate cost before committing. +Wide splines and high-cardinality one-hot encodings can produce many columns. Set a budget +before fitting, then use the fitted width to estimate the size of future batches. | Parameter | Effect | | ------------------------ | ---------------------------------------------- | @@ -458,16 +440,19 @@ The output budget lets you cap the blast radius and estimate cost before committ | `overflow_policy` | What to do on overflow, default `"error"`. | ```python -pre = Preprocessor(max_output_features=500, overflow_policy="error") +budgeted = Preprocessor( + numerical_method="minmax", categorical_method="one-hot", dtype="float32", + max_output_features=500, overflow_policy="error", +).fit(df) -pre.estimate_output_shape(df) # predicted (n_rows, n_cols) without transforming -pre.estimate_memory(df) # predicted dense memory in bytes +assert budgeted.estimate_output_shape(df) == (3, 3) +assert budgeted.estimate_memory(df) == 36 # 3 rows * 3 columns * 4 bytes ``` ```{warning} -With `overflow_policy="error"`, exceeding a budget raises `OutputBudgetError` at `fit`. Use -`estimate_output_shape` and `estimate_memory` first when you work with wide expansions or -large data. +With `overflow_policy="error"`, exceeding a budget at fit time raises `OutputBudgetError`. +`estimate_output_shape` and `estimate_memory` require a fitted preprocessor. They do not +materialize transformed output or predict what an unfitted configuration will learn. ``` ## Where to go next diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index 4c89a65..4b70ef4 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -11,14 +11,17 @@ placement, and the randomized feature maps. Set it to an integer whenever you ne output, for example in tests or published experiments. ```python +import numpy as np from pretab import Preprocessor +X = np.linspace(0.0, 1.0, 50).reshape(-1, 1) +y = np.sin(2 * np.pi * X[:, 0]) pre = Preprocessor(numerical_method="rbf", random_state=0) ``` ```{note} -With a fixed `random_state`, repeated fits on the same data produce identical output. Methods -with no stochastic component ignore the seed. The standalone kernel approximations +In the same environment, a fixed `random_state` lets you repeat a fit on the same data. +Methods with no stochastic component ignore the seed. The standalone kernel approximations (`RandomFourierFeaturesTransformer`, `NystroemFeaturesTransformer`) accept `random_state` directly; they are fit outside `Preprocessor` since they operate on the whole feature block. ``` @@ -31,11 +34,12 @@ directly; they are fit outside `Preprocessor` since they operate on the whole fe write it to a file. `from_spec()` restores it from either form without refitting. ```python -pre.fit(df, y) +pre.fit(X, y) spec = pre.to_spec() # returns a dict pre.to_spec("representation.json") # or writes JSON to a path restored = Preprocessor.from_spec("representation.json") +np.testing.assert_array_equal(pre.transform(X), restored.transform(X)) ``` ### What's in a spec @@ -127,14 +131,14 @@ resolved config, the schema, the fitted parameters, the output-column order, the library versions, and the output precision. ```python -pre.fit(df, y) -pre.fingerprint_ +fingerprint = pre.fingerprint_ +assert fingerprint == restored.fingerprint_ ``` Inference reports and advisory lifecycle flags are excluded from the fingerprint. -The fingerprint is deterministic within a process and across processes, and it survives a -`to_spec` / `from_spec` round-trip. Two preprocessors with the same fingerprint will produce -the same output; a change to config, data, seed, or version changes the fingerprint. +It identifies the fitted state and configuration, not the raw training data. For example, +changing the target of an unsupervised fit can leave the fingerprint unchanged. A spec +round-trip in the same environment preserves the fingerprint. ```{tip} Log the fingerprint alongside model metrics. If it changes unexpectedly between runs, your @@ -167,8 +171,16 @@ accidental mutation of something you intend to deploy. ```python pre.freeze() # lock it -pre.is_frozen() # True -pre.set_params(...) # raises FrozenRepresentationError while frozen +assert pre.is_frozen() + +from pretab import FrozenRepresentationError + +try: + pre.set_params(output_dim=9) +except FrozenRepresentationError: + pass +else: + raise AssertionError("Expected a frozen preprocessor to reject parameter changes") ``` Freezing is useful when a representation is validated and about to ship. To make a fresh, diff --git a/docs/core_concepts/resolution_and_placement.md b/docs/core_concepts/resolution_and_placement.md index 7746f64..54fba1c 100644 --- a/docs/core_concepts/resolution_and_placement.md +++ b/docs/core_concepts/resolution_and_placement.md @@ -7,19 +7,19 @@ they combine. ## Resolution: the `output_dim` width -`output_dim` is the main capacity control. It sets the number of non-bias output columns per -input feature: basis functions for the splines, centers for the feature maps, and bins for -PLE. A larger value captures finer structure at the cost of more columns and a higher chance -of overfitting. A smaller value is more compact and regularizes the representation. +`output_dim` controls capacity for methods that support it. With fixed sizing it requests +the number of basis functions or centers per input feature, excluding any optional bias +column. For PLE it sets a maximum number of bins; the fitted width can be smaller. A wider +representation can capture finer structure but uses more columns and can increase overfitting. ```{note} -When you configure through the `Preprocessor`, its single `output_dim` (default `7`) is -forwarded to **every** numerical method. Per-transformer defaults only apply when you build a -transformer directly, for example `RBFExpansionTransformer()`. +`Preprocessor` inherits its global `output_dim` (default `7`) for methods that accept it, +unless a per-feature request supplies a width. Methods without a width parameter, such as +`minmax`, ignore it. A standalone transformer uses its own default when no width is supplied. ``` ```{warning} -Numeric binning (`custombin`) is the one exception: `output_dim` sets the number of *bins*, +For numeric binning (`custombin`), `output_dim` sets the number of *bins*, but with the default `encode="ordinal"` each input feature still emits a single output column holding the bin index. Pass `encode="onehot"` or `encode="soft"` if you want `output_dim` to also control the output width. diff --git a/docs/core_concepts/target_awareness.md b/docs/core_concepts/target_awareness.md index da711ab..482b0c4 100644 --- a/docs/core_concepts/target_awareness.md +++ b/docs/core_concepts/target_awareness.md @@ -19,8 +19,8 @@ Every method declares how it uses `y` through three levels. from pretab.transformers import PLETransformer t = PLETransformer() -t.requires_y # True: PLE always needs y -t.is_supervised # True +assert t.requires_y +assert t.is_supervised ``` ```{warning} @@ -44,8 +44,10 @@ After fitting, a transformer reports whether it actually consumed the target thr whether it was supervised. ```python -t = PLETransformer().fit(x, y) -t.uses_target_ # True +X = [[0.0], [1.0], [2.0]] +y = [0.1, 0.4, 1.2] +t = PLETransformer().fit(X, y) # Emits LeakageWarning when run directly. +assert t.uses_target_ ``` ## Leakage safety @@ -54,10 +56,11 @@ Fitting a supervised transformer on your full dataset and then evaluating on par target information and inflates scores. PreTab warns when it detects this pattern. ```{important} -A supervised transformer emits a `LeakageWarning` when it is fit with a target **outside** a -cross-validation or `Pipeline` context. Inside a scikit-learn `Pipeline`, `ColumnTransformer`, -`Preprocessor`, or a cross-fitting wrapper, the warning is suppressed because those contexts -already keep the fit confined to the training fold. +`LeakageWarning` is a reminder, not a check of your data split. A supervised transformer +can warn when fitted directly with `y`. PreTab suppresses the warning inside a scikit-learn +`Pipeline`, `ColumnTransformer`, `Preprocessor`, or cross-fitting wrapper. That suppression +does not mean rows were held out: a pipeline fitted on the full dataset still sees the full +dataset. Split before fitting, or pass the entire pipeline to cross-validation. ``` The safe patterns are: @@ -141,10 +144,10 @@ predict. ```{tip} Use `CrossFittedTransformer` when you need the **training features themselves** to be -leakage-free, for example to feed a second-stage model or to report an honest training-set -metric. A supervised transformer inside a plain `Pipeline` already keeps cross-validation -honest for `cross_val_score` / `GridSearchCV`, since each fold refits from scratch; you only -need cross-fitting when you build the training features once and reuse them directly. +computed without each row's own target, for example to feed a second-stage model. To evaluate +that model, still use a separate validation or test set, or put the entire workflow inside +cross-validation. A supervised transformer inside a `Pipeline` passed to `cross_val_score` +or `GridSearchCV` is refit on each training fold before the held-out fold is scored. ``` The fitted spec records `cross_fitted=True` and the number of folds, so the choice is @@ -191,18 +194,19 @@ search = RepresentationSearchCV( random_state=0, ) search.fit(X, y) -search.cv_results_ +assert search.best_method_ == max(search.cv_results_, key=search.cv_results_.get) +{method: round(score, 3) for method, score in search.cv_results_.items()} search.best_method_ ``` ```text -{'minmax': 0.636, 'ple': 0.949, 'bspline': 0.973, 'rbf': 0.841} +{'minmax': 0.636, 'ple': 0.949, 'bspline': 0.976, 'rbf': 0.841} 'bspline' ``` -`bspline` scored highest across the 5 folds for this sine-shaped signal, so `search. -best_preprocessor_` and `search.best_estimator_` are refit on all the data with `bspline` and -ready to call `.predict(X_new)`. +`bspline` had the highest mean validation score for this sine-shaped signal. The selected +preprocessor and estimator are refit on all the training data, so you can call +`search.predict(X_new)` on new rows. When several rows belong to the same unit, such as repeated measurements of one patient, a row-level split validates each candidate on units it has already seen in training. Pass a diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index f575da4..39502ab 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -17,6 +17,7 @@ ROOT = Path(__file__).parents[2] TUTORIALS_DIR = ROOT / "docs" / "tutorials" +CORE_CONCEPTS_DIR = ROOT / "docs" / "core_concepts" _FENCE = re.compile(r"^```python\n(.*?)^```\s*$", re.DOTALL | re.MULTILINE) @@ -41,8 +42,9 @@ def _code_blocks(path: Path, section: str | None = None) -> list[tuple[int, str] return blocks -_TUTORIALS = [ +_PAGES = [ *sorted(TUTORIALS_DIR.glob("*.md")), + *sorted(CORE_CONCEPTS_DIR.glob("*.md")), ROOT / "README.md", ROOT / "docs" / "homepage.md", ROOT / "docs" / "getting_started" / "quickstart.md", @@ -68,24 +70,8 @@ def isolate_document_state(tmp_path, monkeypatch): @pytest.mark.parametrize( ("tutorial", "section"), - [pytest.param(page, None, id=page.stem) for page in _TUTORIALS] + [pytest.param(page, None, id=page.stem) for page in _PAGES] + [ - pytest.param( - ROOT / "docs" / "core_concepts" / "configuration.md", - "Structured per-feature configuration", - id="configuration", - ), - pytest.param( - ROOT / "docs" / "core_concepts" / "configuration.md", - "Polars DataFrame input", - id="polars-input", - marks=pytest.mark.skipif(find_spec("polars") is None, reason="polars is not installed"), - ), - pytest.param( - ROOT / "docs" / "core_concepts" / "resolution_and_placement.md", - "Choose a task and validate the target", - id="task-validation", - ), pytest.param( TUTORIALS_DIR / "multivariate_features.md", "Grouped preprocessing with Preprocessor", @@ -102,6 +88,9 @@ def isolate_document_state(tmp_path, monkeypatch): def test_tutorial_code_runs(tutorial, section): namespace: dict = {"__name__": "__main__"} blocks = _code_blocks(tutorial, section) + if tutorial == CORE_CONCEPTS_DIR / "configuration.md" and find_spec("polars") is None: + polars_lines = {line for line, _ in _code_blocks(tutorial, "Polars DataFrame input")} + blocks = [(line, source) for line, source in blocks if line not in polars_lines] assert blocks, f"No Python examples found in {tutorial.name}: {section}" for start_line, source in blocks: try: From efbde3868dd34cf4f8e56a9050075bec4f830add Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 23 Nov 2026 12:31:17 +0100 Subject: [PATCH 84/86] docs: update developer guidance and release verification --- docs/developer_guide/architecture.md | 14 +++-- docs/developer_guide/contributing.md | 44 +++++++------- docs/developer_guide/release.md | 87 ++++++++++++++++++++-------- 3 files changed, 94 insertions(+), 51 deletions(-) diff --git a/docs/developer_guide/architecture.md b/docs/developer_guide/architecture.md index 2509feb..0e67fc5 100644 --- a/docs/developer_guide/architecture.md +++ b/docs/developer_guide/architecture.md @@ -124,8 +124,9 @@ When `CrossFittedTransformer` wraps a `Preprocessor`, it uses the fitted block's actual target use to decide what to refit. A target-consuming representation and any steps after it are refit on the fold's training rows. Input-only state from the full input to the wrapper stays fitted: column routing, target-free blocks -and their vocabularies, imputers, scalers, and separate missing branches. A group -still uses its ordered sources as one block. This keeps category identities and +and their vocabularies, imputers and scalers before the representation, and +separate missing branches. A group still uses its ordered sources as one block. +This keeps category identities and indicator columns aligned across folds without letting a representation use the held-out row's target. The refitted block must retain its fitted width. @@ -137,10 +138,11 @@ fit the whole pipeline within each outer training split. ## Optional dependencies and persistence -Keep optional packages at the feature boundary. LightGBM placement and language -embeddings use the lazy dependency helpers in `pretab.core.dependencies`; Polars -input and output are handled at the input and output boundaries. Do not make a -base import or an unrelated method require an extra. Preserve an actionable +Keep optional packages at the feature boundary. Composition checks availability +through `pretab.core.dependencies`, without importing the selected model package. +The LightGBM selector and language embedding transformer import their dependencies +only when needed. Polars is handled at the input and output boundaries. Do not make +a base import or an unrelated method require an extra. Preserve an actionable `OptionalDependencyError` for the path that needs the missing package. Registration makes a representation selectable for fitting and inference. It does diff --git a/docs/developer_guide/contributing.md b/docs/developer_guide/contributing.md index b2f1008..9c19ca0 100644 --- a/docs/developer_guide/contributing.md +++ b/docs/developer_guide/contributing.md @@ -25,8 +25,8 @@ git clone https://github.com/OpenTabular/PreTab cd PreTab ``` -2. Install the prerequisites: `pip install poetry` and `just` (see the - [just install guide](https://just.systems/man/en/packages.html), e.g. `brew install just`). +2. Use Python 3.11, 3.12, or 3.13. Install Poetry (`pip install poetry`) and `just` + (see the [just install guide](https://just.systems/man/en/packages.html), e.g. `brew install just`). 3. Install dependencies and register the pre-commit hooks: @@ -66,29 +66,28 @@ This project uses [pre-commit](https://pre-commit.com/) to enforce code quality automatically. `just install` registers all three hook types so each fires at the right time: -| Stage | Hook | -| ------------ | ----------------------------------------------------------------------- | -| `commit-msg` | Validates the message against Conventional Commits. | -| `pre-commit` | `ruff` format and lint, plus file hygiene (whitespace, EOF, conflicts). | -| `pre-push` | `pyright` type checking (slower, so deferred to push). Also runs in CI. | +| Stage | Hook | +| ------------ | ------------------------------------------------------------------------------- | +| `commit-msg` | Validates the message against Conventional Commits. | +| `pre-commit` | Ruff format and lint, Prettier for Markdown, YAML, and JSON, plus file hygiene. | +| `pre-push` | The same checks, plus Pyright type checking. Pyright also runs in CI. | ```{important} -Run `just check` before opening a PR. It runs every `pre-commit`- and `pre-push`-stage hook -(ruff format, ruff lint, pyright, and file hygiene checks) against every file. It does not -validate the commit message itself, that is the `commit-msg` hook, checked when you actually -run `git commit` or `just commit`. +Run `just check` before opening a PR. It runs the `pre-push` stage against all tracked files, +including the checks shared with `pre-commit`. The `commit-msg` hook checks the message +separately when you run `git commit` or `just commit`. ``` Individual recipes are available when you want to run one step: -| Command | Action | -| ------------- | ----------------------------------------------- | -| `just lint` | Lint and auto-fix with ruff. | -| `just format` | Run the ruff formatter. | -| `just types` | Run the pyright type checker. | -| `just test` | Run the test suite with coverage. | -| `just docs` | Build the HTML documentation. | -| `just check` | Run all hooks across all files (commit + push). | +| Command | Action | +| ------------- | ------------------------------------------------ | +| `just lint` | Lint and auto-fix with ruff. | +| `just format` | Run the ruff formatter. | +| `just types` | Run the pyright type checker. | +| `just test` | Run the test suite with coverage. | +| `just docs` | Build the HTML documentation. | +| `just check` | Run the pre-push hooks across all tracked files. | ## Testing @@ -125,7 +124,7 @@ directory. | `tests/extension/` | The public extensibility surface and conformance. | | `tests/integration/` | End-to-end `Preprocessor` and pipeline behaviour. | | `tests/regression/` | Pinned outputs that guard against silent numerical drift. | -| `tests/doc_snippets/` | Executes the `docs/tutorials/*.md` code fences, so the tutorials cannot silently rot. | +| `tests/doc_snippets/` | Runs Python examples in the tutorials, core concepts pages, and selected other guides. | ```{note} Regression tests pin known-good output. If one fails after a deliberate change to a @@ -190,6 +189,9 @@ poetry run pytest --cov=pretab --cov-report=term-missing tests/ If you extend PreTab, run the conformance suite in your own tests. It verifies your class obeys the representation contract, the same one the built-ins satisfy. +Adapt this template to import your own class. For an example you can run as written, see the +[custom representation tutorial](../tutorials/custom_representation.md). + ```python from pretab import check_representation from my_package import MyRepresentation @@ -392,7 +394,7 @@ commits format and rejects non-conforming messages. Version bumps are driven by commitizen, wrapped in `just` recipes. Preview first with the `-preview` (dry-run) variant, then apply. Each apply recipe updates `version` in -`pyproject.toml`, appends to `CHANGELOG.md`, and creates the bump commit and tag. +`pyproject.toml` and updates `CHANGELOG.md` before creating the bump commit and tag. | Goal | Preview | Apply | | ----------------- | ---------------------- | -------------- | diff --git a/docs/developer_guide/release.md b/docs/developer_guide/release.md index cca20ec..9691b72 100644 --- a/docs/developer_guide/release.md +++ b/docs/developer_guide/release.md @@ -4,8 +4,8 @@ pretab is published to [PyPI](https://pypi.org/project/pretab/) with a release-c step on [TestPyPI](https://test.pypi.org/project/pretab/) first. The whole flow is driven by [commitizen](https://commitizen-tools.github.io/commitizen/) version bumps and Git tags; publishing itself runs on GitHub Actions using -[PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC), so no API -tokens are stored anywhere. +[PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC), so neither +publish workflow needs a stored PyPI API token. For the SemVer rules and commit conventions that decide the next version, see [Versioning](contributing.md#versioning). @@ -20,20 +20,22 @@ For the SemVer rules and commit conventions that decide the next version, see ## What runs when -`ci.yml` and `docs.yml` trigger on both `main` and `release/**` branches, so a commit -pushed straight to a release branch (step 4 below) gets the same feedback as a commit on -`main`, without waiting for the next RC tag. +Both `ci.yml` and `docs.yml` run on pushes to `main` and `release/**`, without waiting +for a release tag. On pull requests, CI checks the target branch and the docs workflow +checks the changed paths independently. -| Event | `ci.yml` | `docs.yml` | Publish workflow | -| -------------------- | :-----------: | :------------------: | ---------------------- | -| PR into `main` | ✅ | ✅ (docs paths only) | - | -| Push to `main` | ✅ | ✅ | - | -| Push to `release/**` | ✅ | ✅ | - | -| Push tag `vX.Y.ZrcN` | ✅ (via `qa`) | ✅ (via `docs`) | `publish-testpypi.yml` | -| Push tag `vX.Y.Z` | ✅ (via `qa`) | ✅ (via `docs`) | `publish-pypi.yml` | +| Event | `ci.yml` | `docs.yml` | Publish workflow | +| ---------------------- | -------- | ----------------- | ---------------------- | +| PR into `main` | Yes | On matching paths | None | +| PR into another branch | No | On matching paths | None | +| Push to `main` | Yes | Yes | None | +| Push to `release/**` | Yes | Yes | None | +| Push tag `vX.Y.ZrcN` | Via `qa` | Yes | `publish-testpypi.yml` | +| Push tag `vX.Y.Z` | Via `qa` | Yes | `publish-pypi.yml` | -Every publish workflow re-runs the full `ci.yml`/`docs.yml` gate on the exact tagged -commit before anything is uploaded, rather than trusting whatever last passed on `main`. +Matching tags trigger a standalone docs build. Each publish workflow also calls both +`ci.yml` and `docs.yml` and waits for those jobs to pass on the exact tagged commit +before uploading. ## QA gate checks @@ -48,11 +50,11 @@ commit before anything is uploaded, rather than trusting whatever last passed on | Coverage (fails under 90%) | `coverage` | | Optional extras (`embeddings`, `lightgbm`, `polars`) | `optional-deps` | | Docs build (`sphinx-build -W --keep-going`) | `docs.yml` (separate workflow) | -| Wheel install + import smoke test | publish workflow's own steps | +| Tag/version match and clean-wheel quickstart | publish workflow's own steps | ## Prerequisites -- You are a maintainer with permission to push tags to `main`. +- You are a maintainer with permission to push release tags. - The `pypi-publish` and `testpypi-publish` GitHub Environments are configured with tag-based protection and trusted publishing enabled. - Your working tree is clean and `main` is up to date. @@ -96,13 +98,32 @@ GitHub pre-release. ### 4. Verify the release candidate -Install the candidate from TestPyPI in a clean environment and smoke-test it: +Download the exact candidate wheel from TestPyPI, then install it in a fresh virtual +environment with dependencies from PyPI. The check verifies both the installed version +and that the import came from that environment rather than from the checkout. ```bash -pip install --index-url https://test.pypi.org/simple/ \ - --extra-index-url https://pypi.org/simple/ \ - "pretab==X.Y.ZrcN" -python -c "import pretab; print(pretab.__version__)" +version=X.Y.ZrcN # Replace with your tag version, without the leading v. +verify_dir=$(mktemp -d) +python3 -m venv "$verify_dir/venv" +verify_python="$verify_dir/venv/bin/python" + +"$verify_python" -m pip download --no-deps --only-binary=:all: \ + --index-url https://test.pypi.org/simple/ \ + --dest "$verify_dir" "pretab==$version" && +"$verify_python" -m pip install --index-url https://pypi.org/simple/ \ + "$verify_dir"/pretab-*.whl && +"$verify_python" -I - "$version" <<'PY' +import sys +from pathlib import Path + +import pretab + +path = Path(pretab.__file__).resolve() +assert path.is_relative_to(Path(sys.prefix).resolve()), path +assert pretab.__version__ == sys.argv[1], pretab.__version__ +print(pretab.__version__, path) +PY ``` If the candidate has problems, fix them on the branch and produce the next RC: @@ -141,9 +162,27 @@ exactly what both publishing workflows wait on before uploading. ### 7. Confirm +Confirm that the exact stable version can be installed from PyPI. Use a new virtual +environment, not the one used to verify the candidate. + ```bash -pip install --upgrade pretab -python -c "import pretab; print(pretab.__version__)" +version=X.Y.Z # Replace with your tag version, without the leading v. +verify_dir=$(mktemp -d) +python3 -m venv "$verify_dir/venv" +verify_python="$verify_dir/venv/bin/python" + +"$verify_python" -m pip install --index-url https://pypi.org/simple/ "pretab==$version" && +"$verify_python" -I - "$version" <<'PY' +import sys +from pathlib import Path + +import pretab + +path = Path(pretab.__file__).resolve() +assert path.is_relative_to(Path(sys.prefix).resolve()), path +assert pretab.__version__ == sys.argv[1], pretab.__version__ +print(pretab.__version__, path) +PY ``` Check the release on [PyPI](https://pypi.org/project/pretab/) and the auto-generated @@ -152,5 +191,5 @@ GitHub Release notes. ```{tip} Need a build artifact without publishing? Run the `build-check.yml` workflow manually from the GitHub Actions tab. It builds the wheel and sdist, runs `twine check`, and performs an -import smoke test. +import and quickstart check against the installed wheel. ``` From 68ace019b08a046d02deb78fa48444f28b20bf29 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Mon, 23 Nov 2026 17:49:49 +0100 Subject: [PATCH 85/86] docs: refresh tutorials, core concepts, representations, examples --- .../core_concepts/resolution_and_placement.md | 31 +++--- docs/getting_started/installation.md | 30 ++--- docs/getting_started/overview.md | 100 +++++++++++------ docs/getting_started/quickstart.md | 104 ++++++++++-------- docs/representations/choosing_a_method.md | 34 +++--- docs/representations/embeddings.md | 20 ++-- docs/representations/functional_expansions.md | 29 +++-- docs/representations/kernel_approximation.md | 24 ++-- docs/representations/numerical_encoding.md | 76 ++++++------- docs/representations/spline_expansions.md | 48 ++++---- docs/tutorials/adaptive_resolution.md | 99 ++++++++--------- docs/tutorials/comparing_representations.md | 41 +++---- docs/tutorials/custom_representation.md | 24 ++-- docs/tutorials/multivariate_features.md | 7 +- docs/tutorials/nonlinear_regression.md | 37 +++---- docs/tutorials/sklearn_pipeline.md | 4 +- docs/tutorials/target_aware_classification.md | 10 +- .../src/pretab_chebyshev/__init__.py | 6 +- .../pretab-chebyshev/tests/test_chebyshev.py | 37 +++++++ tests/doc_snippets/test_tutorial_snippets.py | 11 +- 20 files changed, 439 insertions(+), 333 deletions(-) diff --git a/docs/core_concepts/resolution_and_placement.md b/docs/core_concepts/resolution_and_placement.md index 54fba1c..d1a4323 100644 --- a/docs/core_concepts/resolution_and_placement.md +++ b/docs/core_concepts/resolution_and_placement.md @@ -46,23 +46,22 @@ steps and watch the total column count. ## Adaptive sizing -Some features are simple and some are complex, and one fixed width rarely suits all of them. -PLE, the feature maps, and the freely-placed knot splines can size each feature from the data -instead. - -`adaptive` -: When `True`, the width for each feature is chosen from the data and kept inside -`[min_output_dim, max_output_dim]`. Fixed-width methods such as the plain scalers ignore -this flag. - -`min_output_dim`, `max_output_dim` -: The lower and upper bounds that apply only when `adaptive=True` (defaults `5` and `10`). -They are ignored otherwise. +For supported methods, `adaptive=True` lets fitting adjust the per-feature width. The +`min_output_dim` and `max_output_dim` settings specify the requested bounds. How they are used +depends on the method and placement path: + +- **Supervised search.** Two explicit bounds define the search window. An unset bound can + fall back to `output_dim`, which must still be valid for the method even when both bounds + are set. PLE always uses the target and does not take a `target_aware` flag. +- **Target-free placement.** B-, M-, and I-splines start from `output_dim` and adjust the + unsupervised knots toward the bounds. With bounds `[4, 6]`, a target-free B-spline can + keep a requested width of 5 or reduce a requested width of 12 to 6. Other methods, such + as RBF and natural cubic splines, keep their ordinary sizing on the target-free path. ```{note} -When `adaptive=True` and both `min_output_dim` and `max_output_dim` are set, `output_dim` has -no effect at all: the window comes entirely from the two bounds. `output_dim` only matters in -adaptive mode when one of the bounds is left unset, where it fills in for the missing one. +B-, M-, and I-splines can fit fewer columns than `min_output_dim` when there are too few +distinct input values for the requested knots. Use `output_dims_` or `total_output_dim_` +after fitting a `Preprocessor` to size a downstream model. ``` ```python @@ -70,6 +69,8 @@ from pretab import Preprocessor pre = Preprocessor( numerical_method="rbf", + target_aware=True, + placement_strategy="cart", adaptive=True, min_output_dim=4, max_output_dim=12, diff --git a/docs/getting_started/installation.md b/docs/getting_started/installation.md index fb21ee9..3d3a2b1 100644 --- a/docs/getting_started/installation.md +++ b/docs/getting_started/installation.md @@ -1,23 +1,21 @@ # Installation -PreTab 1.1 supports Python 3.11 to 3.13, with the following minimum core dependency versions: +PreTab 1.1 supports Python 3.11 to 3.13. The table distinguishes the declared minimum +dependency versions from the pinned versions tested in the Python 3.11 CI job. -| Dependency | Minimum | -| -------------- | ------- | -| `numpy` | 1.24 | -| `pandas` | 2.0 | -| `scipy` | 1.10 | -| `scikit-learn` | 1.6 | +| Dependency | Declared minimum | Tested CI pin | +| -------------- | ---------------- | ------------- | +| `numpy` | 1.24 | 1.24.4 | +| `pandas` | 2.0 | 2.0.3 | +| `scipy` | 1.10 | 1.10.1 | +| `scikit-learn` | 1.6 | 1.6.0 | ```{note} -`scikit-learn>=1.6` is required for the `__sklearn_tags__` tag-dispatch API pretab's -transformers use. A dedicated CI job installs exactly these minimum versions and runs the -test suite against them, so this floor is verified, not just declared. +PreTab's transformers require `scikit-learn>=1.6` for the `__sklearn_tags__` API. ``` The core dependencies are NumPy >=1.24,<3, pandas >=2,<3, SciPy >=1.10,<2, -and scikit-learn >=1.6,<2. The scikit-learn minimum matches the validation and -estimator-tag APIs used by PreTab. +and scikit-learn >=1.6,<2. ## From PyPI @@ -119,7 +117,13 @@ preprocessing, feature lineage, leakage-safe cross-fitting, serialization, and m seconds, and doubles as the reviewer smoke test: ```bash -just quickstart # or: python scripts/quickstart.py +just quickstart +``` + +Without `just`, run the script in the Poetry environment: + +```bash +poetry run python scripts/quickstart.py ``` To work on the documentation, also install the docs group: diff --git a/docs/getting_started/overview.md b/docs/getting_started/overview.md index 63b5fd9..c69aff0 100644 --- a/docs/getting_started/overview.md +++ b/docs/getting_started/overview.md @@ -20,22 +20,45 @@ declare intent once, for example "expand `age` with a spline, encode `income` wi piecewise-linear bins, treat `hour` as periodic", and PreTab fits the corresponding basis per column, tracks where every output column came from, and hands back a clean matrix. +The examples on this page use the same small regression dataset. + ```python +import numpy as np +import pandas as pd + from pretab import Preprocessor -pre = Preprocessor(feature_preprocessing={ - "age": "naturalspline", # smooth non-linear effect - "income": "ple", # supervised piecewise-linear encoding - "hour": "fourier", # periodic representation - "city": "one-hot", # categorical -}) +rng = np.random.default_rng(0) +n_rows = 64 +df = pd.DataFrame( + { + "age": rng.uniform(18, 65, size=n_rows), + "income": rng.uniform(25_000, 90_000, size=n_rows), + "hour": rng.integers(0, 24, size=n_rows), + "city": rng.choice(["Oslo", "Rome"], size=n_rows), + } +) +y = np.sin(df["age"] / 10) + np.log(df["income"]) + np.cos(2 * np.pi * df["hour"] / 24) + +pre = Preprocessor( + task="regression", + random_state=0, + feature_preprocessing={ + "age": "naturalspline", + "income": "ple", + "hour": "fourier", + "city": "one-hot", + }, +) X = pre.fit_transform(df, y) +assert X.shape == (len(df), len(pre.get_feature_names_out())) ``` ## Two ways to use it -PreTab exposes the same capabilities through two surfaces. They share the same underlying -code, so the choice is about ergonomics, not capability. +`Preprocessor` and standalone transformers share many of the same representations. Use +`Preprocessor` to configure a whole table, or compose standalone transformers when you need +to control each pipeline step or use a standalone-only method. ::::{grid} 1 1 2 2 :gutter: 3 @@ -47,8 +70,8 @@ strategies from one config. ::: :::{grid-item-card} Standalone transformers -Every strategy is also a plain scikit-learn transformer you can import and compose inside a -`Pipeline` or `ColumnTransformer`. Reach for them when you want a single estimator object. +Import a transformer from `pretab.transformers` and use it on its own or inside a +`Pipeline` or `ColumnTransformer`. ::: :::: @@ -60,15 +83,12 @@ map), or want the framework services that live at this level: feature lineage, output-format control, missing-value policy, output budgets, serialization, and a reproducibility fingerprint. -```python -from pretab import Preprocessor +The fitted `Preprocessor` above can also return the same four features as separate blocks. -pre = Preprocessor(feature_preprocessing={ - "age": "naturalspline", - "income": "ple", - "city": "one-hot", -}) -X = pre.fit_transform(df, y) # one stacked array, or output_structure="blocks" for a dict +```python +blocks = pre.transform(df, return_array=False) +assert set(blocks) == {"num_age", "num_income", "num_hour", "cat_city"} +assert sum(block.shape[1] for block in blocks.values()) == X.shape[1] ``` **Reach for standalone transformers** when you want a single estimator object that composes @@ -76,18 +96,25 @@ cleanly inside one `Pipeline`, rely on scikit-learn model selection (`cross_val_ `GridSearchCV`, `step__param` hyperparameter addressing), or need fine control over one column's transformer and its parameters. +This pipeline uses just `age` and `income`. It fits their representations and Ridge on the +training split, then transforms and predicts on held-out rows. + ```python from sklearn.compose import ColumnTransformer -from sklearn.pipeline import Pipeline from sklearn.linear_model import Ridge +from sklearn.model_selection import train_test_split +from sklearn.pipeline import Pipeline from pretab.transformers import NaturalCubicSplineTransformer, PLETransformer features = ColumnTransformer([ ("age", NaturalCubicSplineTransformer(output_dim=10), ["age"]), - ("income", PLETransformer(output_dim=12), ["income"]), + ("income", PLETransformer(output_dim=12, task="regression", random_state=0), ["income"]), ]) model = Pipeline([("features", features), ("ridge", Ridge())]) +df_train, df_test, y_train, _ = train_test_split(df, y, random_state=0) +model.fit(df_train, y_train) +assert model.predict(df_test).shape == (len(df_test),) ``` ```{note} @@ -117,21 +144,27 @@ PreTab is not a competitor to scikit-learn. Every transformer subclasses `BaseEs The real question is what PreTab adds where scope overlaps with scikit-learn's own `SplineTransformer`, `KBinsDiscretizer`, `PolynomialFeatures`, and `TargetEncoder`. -| Capability | scikit-learn | PreTab | -| -------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Knot / threshold placement | Fixed `n_knots`, placed `"uniform"` or `"quantile"` before fitting | Configured via `output_dim` (how many basis functions you want); PreTab derives the knot count from it and places them with `placement_strategy`, optionally target-aware (a CART or LightGBM model places them where the target changes fastest) | -| How many basis functions | You pick a fixed count | `adaptive=True` searches a width in `[min_output_dim, max_output_dim]` from the data | -| Leakage safety | `TargetEncoder` cross-fits internally; nothing else does, and nothing warns you | Every supervised representation emits a `LeakageWarning` outside a `Pipeline`, and any of them can be wrapped in `CrossFittedTransformer` | -| Feature provenance | `get_feature_names_out()` returns names only | A typed `RepresentationSpec` per transformer plus a `FeatureLineage` record per output column (family, component, target usage) | -| Persistence | `pickle` / `joblib`, which execute arbitrary code on load | `to_spec()` / `from_spec()`: a versioned JSON spec for supported fitted state, plus a stable `fingerprint_`; restore trusted specs in the same environment | -| Choosing per column | Hand-assemble a `ColumnTransformer` yourself | One `Preprocessor(feature_preprocessing={...})`, validated against a capability registry so incompatible combinations (a required-target method without `y`, for example) raise a typed error at fit time | +| Capability | scikit-learn | PreTab | +| ------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Knot placement | `SplineTransformer` places `"uniform"` or `"quantile"` knots during `fit` | Configured via `output_dim` (how many basis functions you want); PreTab derives the knot count from it and places them with `placement_strategy`, optionally target-aware (a CART or LightGBM model places them where the target changes fastest) | +| How many basis functions | You pick a fixed count | `adaptive=True` searches a width in `[min_output_dim, max_output_dim]` from the data | +| Target-aware fitting | `TargetEncoder.fit_transform` cross-fits; `fit` followed by `transform` does not | `CrossFittedTransformer` makes out-of-fold training features when the output width is consistent across folds. Direct standalone fits that use `y` can emit `LeakageWarning`. | +| Feature provenance | `get_feature_names_out()` returns names only | A typed `RepresentationSpec` per transformer plus a `FeatureLineage` record per output column (family, component, target usage) | +| Persistence | `pickle` / `joblib`, which execute arbitrary code on load | `to_spec()` / `from_spec()`: a versioned JSON spec for supported fitted state, plus a stable `fingerprint_`; restore trusted specs in the same environment | +| Choosing per column | Hand-assemble a `ColumnTransformer` yourself | One `Preprocessor(feature_preprocessing={...})`, validated against a capability registry so incompatible combinations (a required-target method without `y`, for example) raise a typed error at fit time | + +```{warning} +A fit inside `Preprocessor` or a scikit-learn `Pipeline` does not emit the standalone +`LeakageWarning`. That does not make the fit leakage-safe by itself. For evaluation, fit +the whole pipeline on training rows only, or cross-validate the unfitted pipeline. See +[Target awareness](../core_concepts/target_awareness.md). +``` ```{note} Piecewise-linear encoding (`ple`) and the neural-style basis maps (`rbf`, `relu`, `sigmoid`, `tanh`, deterministic `fourier`) have no scikit-learn equivalent. `rff` and `nystroem` are thin -wrappers around scikit-learn's own `RBFSampler` and `Nystroem`; unlike the other methods on -this page, they operate on the whole feature block at once, so they are standalone -transformers rather than a per-column `Preprocessor` choice. +wrappers around scikit-learn's own `RBFSampler` and `Nystroem`. Both operate on whole +feature blocks and are available as standalone transformers only. ``` ## When to reach for PreTab @@ -163,8 +196,9 @@ full breakdown. Knowing the boundaries is as useful as knowing the features. PreTab deliberately does not try to be an everything-library. -- **Not a modelling library.** PreTab produces features. It does not fit predictors, tune - models, or select features for you. It sits _in front of_ an estimator. +- **Not a modelling library.** PreTab supplies representations, not predictors. Use your own + estimator downstream. [`RepresentationSearchCV`](../api/search_and_cross_fitting.rst) + fits that estimator while comparing candidate representations by cross-validation. - **Not a time-series toolkit.** Generic lag and rolling-window utilities were removed on purpose. PreTab keeps the periodic encoding that expresses cyclic structure (hour, day, month) but leaves sequence modelling to dedicated libraries. diff --git a/docs/getting_started/quickstart.md b/docs/getting_started/quickstart.md index 010660a..38515cb 100644 --- a/docs/getting_started/quickstart.md +++ b/docs/getting_started/quickstart.md @@ -46,7 +46,8 @@ pre = Preprocessor(feature_preprocessing=config, task="regression", random_state # Fit and transform into a single stacked array X = pre.fit_transform(df, y) -X.shape +assert X.shape == (200, 26) +print(X.shape) ``` ```text @@ -62,90 +63,98 @@ When no per-feature config is given, the `Preprocessor` falls back to its global Ask for a dict of per-feature blocks instead, for inspection or per-block downstream heads: ```python -X_dict = pre.transform(df, return_array=False) # {"num_age": ..., "cat_city": ...} +blocks = pre.transform(df, return_array=False) +assert sum(block.shape[1] for block in blocks.values()) == X.shape[1] +for name, block in blocks.items(): + print(name, block.shape) ``` ```text -{'num_age': (200, 7), 'num_income': (200, 7), 'num_experience': (200, 7), - 'cat_job': (200, 4), 'cat_city': (200, 1)} +num_age (200, 7) +num_income (200, 7) +num_experience (200, 7) +cat_job (200, 4) +cat_city (200, 1) ``` ## Inspect what was built -Every fitted representation is self-describing. Read the resolved layout, or trace each -output column back to its source. +Call `pre.get_feature_info(verbose=True)` for a table of fitted pipelines and widths. +Use `verbose=False` to read the numerical, categorical, and grouped feature information +in code. The lineage records trace output columns back to their inputs. ```python -pre.get_feature_info(verbose=True) # human-readable table of per-feature pipelines +_, categorical_info, _ = pre.get_feature_info(verbose=False) +print(categorical_info["job"]["preprocessing"]) -lineage = pre.get_feature_lineage() # one record per output column -lineage[0] +lineage = pre.get_feature_lineage() +first = lineage[0] +print(first.output_feature, first.source_features, first.uses_target) +assert [record.output_feature for record in lineage] == list(pre.get_feature_names_out()) ``` ```text -feature kind pipeline dim cats ------------------------------------------------------------------------ -age numerical imputer -> minmax -> ple 7 - -income numerical imputer -> minmax -> rbf 7 - -experience numerical imputer -> minmax -> naturalspline 7 - -job categorical imputer -> onehot -> to_float 4 4 -city categorical imputer -> continuous_ordinal 1 5 +normalize_missing -> imputer -> onehot -> to_float +num_age_ple0 ('age',) True ``` -```text -FeatureLineage(output_feature='num_age_ple0', output_index=0, source_features=('age',), - family='piecewise_linear', component='interval', component_index=0, - uses_target=True, is_interaction=False) -``` - -The lineage covers every output column, and the names line up with `get_feature_names_out`. +The first output column comes from `age` and was fitted using the target. The lineage +covers every output column, in the same order as `get_feature_names_out()`. See [Outputs and inspection](../core_concepts/outputs_and_inspection.md) for the full contract. ## Use a transformer on its own -Every strategy is also importable from `pretab.transformers` and follows the scikit-learn -API, so it drops into a `Pipeline` or `ColumnTransformer`. +Import individual transformers from `pretab.transformers`. They follow the scikit-learn +API and work inside a `Pipeline` or `ColumnTransformer`. ```python import numpy as np from pretab.transformers import PLETransformer -x = np.random.randn(200, 1) -y = np.random.randn(200) +rng = np.random.default_rng(0) +values = rng.normal(size=(200, 1)) +target = values[:, 0] ** 2 -x_ple = PLETransformer(output_dim=15, task="regression").fit_transform(x, y) -x_ple.shape[1] # number of piecewise-linear bins +ple = PLETransformer(output_dim=15, task="regression", random_state=0) +features = ple.fit_transform(values, target) +assert features.shape == (len(values), 15) +print(features.shape[1]) ``` ```text 15 ``` -```{note} -`PLETransformer` is supervised: it reads the target `y` during `fit` to place its bin edges. -Always pass `y` when fitting it, or any pipeline that contains it. See -[Target awareness](../core_concepts/target_awareness.md). +```{warning} +`PLETransformer` uses the target to place its bin edges. The direct fit above emits a +`LeakageWarning`: do not fit on all rows before splitting them to evaluate a model. Put the +transformer and predictor in one pipeline and fit them on the training split only, or +cross-validate the unfitted pipeline. See [Target awareness](../core_concepts/target_awareness.md) +for out-of-fold training features. ``` -Spline families that carry a smoothness penalty expose it through `get_penalty_matrix()`: +Spline families with a smoothness penalty expose it through `get_penalty_matrix()`. +For natural cubic splines, the matrix penalizes the integrated squared curvature. ```python import numpy as np from pretab.transformers import NaturalCubicSplineTransformer -x = np.random.randn(200, 1) +rng = np.random.default_rng(0) +values = rng.normal(size=(200, 1)) spline = NaturalCubicSplineTransformer(output_dim=8) -spline.fit_transform(x) - -penalty = spline.get_penalty_matrix() # integrated-curvature penalty for GAM-style fitting +features = spline.fit_transform(values) +penalty = spline.get_penalty_matrix() +assert features.shape == (len(values), 8) +assert penalty.shape == (features.shape[1], features.shape[1]) +print(features.shape, penalty.shape) ``` ```text -(200, 8) # spline.fit_transform(x).shape -(8, 8) # penalty.shape +(200, 8) (8, 8) ``` The multivariate thin-plate spline models several columns jointly and is sized by @@ -156,15 +165,18 @@ import numpy as np from pretab.transformers import ThinPlateSplineTransformer -x = np.random.randn(200, 2) # two input columns, modelled together -tp = ThinPlateSplineTransformer(n_components=10) -features = tp.fit_transform(x) -penalty = tp.get_penalty_matrix() +rng = np.random.default_rng(0) +values = rng.normal(size=(200, 2)) +thin_plate = ThinPlateSplineTransformer(n_components=10, random_state=0) +features = thin_plate.fit_transform(values) +penalty = thin_plate.get_penalty_matrix() +assert features.shape == (len(values), 10) +assert penalty.shape == (features.shape[1], features.shape[1]) +print(features.shape, penalty.shape) ``` ```text -(200, 10) # features.shape -(10, 10) # penalty.shape +(200, 10) (10, 10) ``` ```{warning} diff --git a/docs/representations/choosing_a_method.md b/docs/representations/choosing_a_method.md index 7524f36..158df00 100644 --- a/docs/representations/choosing_a_method.md +++ b/docs/representations/choosing_a_method.md @@ -15,15 +15,16 @@ The right representation depends on what sits downstream. ## Match the method to the signal -| If the relationship is... | Reach for... | -| --------------------------------- | ---------------------------------------- | -| Smooth and curved | B-spline, natural cubic spline, P-spline | -| Monotone (must not reverse) | I-spline | -| Sharp, threshold-like | PLE, numeric binning, ReLU expansion | -| Local bumps around centers | RBF expansion | -| Periodic (known period) | Periodic encoding, Fourier features | -| A smooth surface over two inputs | Tensor-product or thin-plate spline | -| A general kernel over many inputs | Random Fourier features, Nyström | +| If the relationship is... | Reach for... | +| ---------------------------------- | ----------------------------------------- | +| Smooth and curved | B-spline, natural cubic spline, P-spline | +| Monotone (must not reverse) | I-spline | +| Sharp, threshold-like | PLE, numeric binning, ReLU expansion | +| Local bumps around centers | RBF expansion | +| Periodic (known period) | Periodic encoding with an explicit period | +| Oscillations over the fitted range | Fourier features | +| A smooth surface over two inputs | Tensor-product or thin-plate spline | +| A general kernel over many inputs | Random Fourier features, Nyström | ```{tip} When unsure, start with the `"standard"` preset (min-max scaling, integer categoricals, and @@ -45,8 +46,10 @@ measure the difference instead of guessing. ## Control the width More columns means more flexibility and more overfitting risk. Start narrow and widen only if -validation improves. Turn on `adaptive=True` to let the data choose a width between -`min_output_dim` and `max_output_dim`. See +validation improves. For [methods that support adaptive sizing](comparison_table.md), +`adaptive=True` lets the data choose a width between `min_output_dim` and `max_output_dim`. +Inspect the fitted width before sizing a downstream model. Use a fixed width for cross-fitting +if adaptive sizing changes the width across folds. See [Resolution and placement](../core_concepts/resolution_and_placement.md). ## When basis expansion does not help @@ -87,11 +90,10 @@ PreTab is explicit about degenerate inputs rather than failing silently. tensor-product) raise a typed error rather than fitting a meaningless basis. Numeric binning falls back to a single bin instead of raising, and PLE and the feature maps place all their bins or centers at the same value, a degenerate but still valid basis. -- **Discrete or heavily tied column**: target-aware PLE and feature maps still get the - requested number of distinct bin edges or centers strictly inside the observed range. When - the tree finds fewer splits than requested, the shortfall is filled with spaced quantile - points and then evenly spaced points, so the output width does not depend on the data (or - on the cross-fitting fold). +- **Discrete or heavily tied column**: in fixed-width mode, PLE and target-aware feature maps + fill in missing tree splits with additional points inside the observed range of a nonconstant + feature to keep the requested width. Adaptive mode can choose a narrower width. Unsupervised + quantile binning instead merges duplicate edges, so it can produce fewer bins than requested. - **Out-of-range input at transform**: B/M/I-spline, P-spline, and tensor-product clip values beyond the fitted range by default; natural-cubic and cubic-regression extrapolate smoothly by default. Pass `policy=RepresentationPolicy(out_of_range=...)` directly to any diff --git a/docs/representations/embeddings.md b/docs/representations/embeddings.md index b4e48d9..80f8598 100644 --- a/docs/representations/embeddings.md +++ b/docs/representations/embeddings.md @@ -17,18 +17,18 @@ t.fit_transform(X).shape # model's own dimensionality once fitted, e.g. via t.embedding_dim_ ``` -Constructor highlights: `model_name="paraphrase-MiniLM-L3-v2"`, or pass a preloaded `model` -(useful for tests or a custom embedding backend without pulling in `sentence-transformers`). -Any object with a `.encode(X)` method works for the `transform` step; `embedding_dim_` is -read from `get_sentence_embedding_dimension()` when the model exposes it (as a real -`SentenceTransformer` does), falling back to a `dim` attribute, or, if neither is present, -probed by calling `.encode()` once on a placeholder input during `fit`. The registry key is -`pretrained`. +Use `model_name` to load a pretrained model, or pass a preloaded `model` to the standalone +transformer. A custom model must accept `encode(texts, convert_to_numpy=True)`, where `texts` +is a list of strings, and return a two-dimensional numeric array with one row per string. +During `fit`, PreTab obtains `embedding_dim_` from `get_sentence_embedding_dimension()` or +the model's `dim` attribute. If neither is available, it calls `encode` with the same keyword +on a placeholder string to determine the width. ```{important} -Language embeddings require the optional `embeddings` extra, which pulls in -`sentence-transformers`. Install it with `pip install "pretab[embeddings]"`. Without it, -requesting `pretrained` raises a clear `OptionalDependencyError`. +Loading a model by name or selecting the `pretrained` registry method requires the optional +`embeddings` extra. Install it with `pip install "pretab[embeddings]"`; otherwise these paths +raise `OptionalDependencyError`. A preloaded `model` passed to the standalone transformer +does not require `sentence-transformers`. ``` ```{note} diff --git a/docs/representations/functional_expansions.md b/docs/representations/functional_expansions.md index 98fa2bc..5a02ee9 100644 --- a/docs/representations/functional_expansions.md +++ b/docs/representations/functional_expansions.md @@ -6,9 +6,10 @@ ramps, sigmoids) or project it onto a deterministic Fourier basis. Together they threshold, and periodic structure with a per-column, `Preprocessor`-selectable transformer. ```{important} -As with splines, `output_dim` (or `n_frequencies` for the Fourier map) is the number of output -columns **per input feature**. A `(n_samples, 3)` input with `output_dim=10` produces -`(n_samples, 30)` output. +For fixed-width RBF, ReLU, sigmoid, and tanh expansions, `output_dim` counts output columns +**per input feature**: three inputs with `output_dim=10` produce 30 columns. Fourier counts +frequencies instead: three inputs with `n_frequencies=10` produce 60 sine and cosine columns, +or 63 columns when `include_original=True`. ``` ## Radial basis functions @@ -42,10 +43,12 @@ Constructor highlights: `output_dim`, `gamma=1.0` (bump width; larger is narrowe ``` ```{warning} -`target_aware=True` places centers using a supervised tree over `(X, y)`. Fitting it directly -on your full training set (outside a `Pipeline` or `pretab.CrossFittedTransformer`) raises a -`LeakageWarning`, because the center placement has already seen the labels you would then train -on. The same applies to ReLU, sigmoid, and tanh below whenever `target_aware=True`. +`target_aware=True` places centers using a supervised tree over `(X, y)`. A standalone fit with +`y` emits `LeakageWarning`. For evaluation, split before fitting or cross-validate the whole +pipeline. A plain pipeline still uses the training rows' targets to place their centers; +wrap the expansion in `pretab.CrossFittedTransformer` for out-of-fold training features. +This also applies to ReLU, sigmoid, and tanh whenever `target_aware=True`. See +[Target awareness](../core_concepts/target_awareness.md). ``` ## ReLU, sigmoid, and tanh expansions @@ -107,8 +110,9 @@ from pretab.transformers import FourierFeatureTransformer X = np.linspace(0, 1, 50).reshape(-1, 1) t = FourierFeatureTransformer(n_frequencies=5, frequency_strategy="harmonic") -t.fit_transform(X).shape -# (50, 10): 2 columns (sin, cos) per frequency +encoded = t.fit_transform(X) +assert encoded.shape == (50, 10) +np.testing.assert_allclose(encoded[0], encoded[-1], atol=1e-12) ``` Constructor highlights: `n_frequencies=5`, `frequency_strategy="harmonic"`, @@ -121,9 +125,10 @@ the base frequency (1x, 2x, 3x, ...); the alternative spacing is useful when the a clean harmonic series. ```{tip} -Use `FourierFeatureTransformer` when you want the model to work across a set of frequencies -without committing to a single known period. If the period is known (hour of day, month of -year), the direct [periodic encoder](numerical_encoding.md#periodic-encoding) is usually simpler. +Use `FourierFeatureTransformer` for a range-based frequency basis. The fitted range sets the +base frequency; it is not an estimate of the signal's period. For example, the harmonic map +repeats every 23 units if fitted on hours 0 through 23. To encode a 24-hour cycle, use +the [periodic encoder](numerical_encoding.md#periodic-encoding) with `period=24`. ``` ## Where to go next diff --git a/docs/representations/kernel_approximation.md b/docs/representations/kernel_approximation.md index bf155aa..10ef2a5 100644 --- a/docs/representations/kernel_approximation.md +++ b/docs/representations/kernel_approximation.md @@ -47,15 +47,16 @@ them, following Williams and Seeger. It supports several kernels through `kernel more accurate than random Fourier features at a given output width because the landmarks adapt to the data rather than being drawn at random. For landmarks $z_1, \dots, z_m$ (the sampled training rows) and kernel function $K$, let $k_m(x) = \big(K(x, z_1), \dots, K(x, z_m)\big)$ be -the vector of kernel evaluations between $x$ and every landmark. The output is +the vector of kernel evaluations between $x$ and every landmark. For a positive-semidefinite +landmark kernel matrix, the map takes the form $$ \phi(x) = K_{mm}^{-1/2}\ k_m(x), $$ -where $K_{mm}$ is the $m \times m$ kernel matrix between the landmarks themselves, and -$K_{mm}^{-1/2}$ is computed once at fit time via its eigendecomposition. The inner product -$\phi(x)^\top \phi(x')$ approximates $K(x, x')$. +where $K_{mm}$ is the $m \times m$ kernel matrix between the landmarks. Scikit-learn computes +the normalization at fit time using SVD, flooring small singular values before taking their +inverse square roots. The inner product $\phi(x)^\top \phi(x')$ approximates $K(x, x')$. ```python import numpy as np @@ -63,20 +64,19 @@ from pretab.transformers import NystroemFeaturesTransformer X = np.random.default_rng(0).uniform(size=(200, 3)) t = NystroemFeaturesTransformer(n_components=100, kernel="rbf") -t.fit_transform(X).shape -# (200, 100) +assert t.fit_transform(X).shape == (200, 100) ``` Constructor highlights: `n_components=100`, `kernel="rbf"`, `gamma=None`, `degree=3`, `coef0=1`, `random_state`. ```{warning} -Nyström samples its landmarks from the training rows, so `n_components` cannot exceed -`n_samples`. If you fit on fewer rows than `n_components` (for example a small -cross-validation fold), scikit-learn silently clamps `n_components` down to `n_samples` and -emits a `UserWarning` rather than raising: the fitted output width is `min(n_components, -n_samples_seen_in_fit)`. Random Fourier features have no such limit, since they draw a random -basis instead of sampling training rows. +Nyström samples its landmarks from the training rows. If a fit has fewer rows than +`n_components` (for example in a small cross-validation fold), scikit-learn emits a +`UserWarning` and uses all the available rows as landmarks. The fitted width is +`min(n_components, n_samples_seen_in_fit)`; the requested `n_components` remains unchanged. +Random Fourier features have no such limit because they draw a random basis instead of +sampling training rows. ``` ```{note} diff --git a/docs/representations/numerical_encoding.md b/docs/representations/numerical_encoding.md index 0799fcd..75ebdcc 100644 --- a/docs/representations/numerical_encoding.md +++ b/docs/representations/numerical_encoding.md @@ -17,37 +17,40 @@ from pretab.transformers import NumericBinningTransformer X = np.random.default_rng(0).uniform(size=(100, 1)) # (100, 1) onehot = NumericBinningTransformer(output_dim=8, encode="onehot", placement_strategy="quantile") -onehot.fit_transform(X).shape -# (100, 8): one column per bin +assert onehot.fit_transform(X).shape == (100, 8) ordinal = NumericBinningTransformer(output_dim=8, encode="ordinal", placement_strategy="quantile") -ordinal.fit_transform(X).shape -# (100, 1): a single integer column, regardless of output_dim +assert ordinal.fit_transform(X).shape == (100, 1) + +tied = np.repeat([0, 1, 2], 3).reshape(-1, 1) +for encoding in ("onehot", "soft"): + binner = NumericBinningTransformer(output_dim=8, encode=encoding, placement_strategy="quantile") + assert binner.fit_transform(tied).shape == (9, 2) + assert binner.n_bins_ == [2] ``` -The `encode` parameter selects the output form, and it changes the output **width**, not just -the values: `"onehot"` produces `output_dim` columns, while `"ordinal"` and `"soft"` behave -differently from each other despite both accepting the same `output_dim`. +`output_dim` requests a bin count per input feature. Quantile placement merges duplicate +edges, so tied data can yield fewer bins than requested. A constant feature falls back to +one bin. Inspect `n_bins_` for the fitted counts. The `encode` parameter determines how those +bins become output columns: `"ordinal"` -: A single integer column giving the bin index (output width is always 1, independent of -`output_dim`). +: One integer column per input feature, giving the bin index regardless of the bin count. `"onehot"` -: One indicator column per bin (output width equals `output_dim`). +: One indicator column per fitted bin. `"soft"` : A soft assignment that spreads each value across neighbouring bins, so the boundaries are not -hard (output width equals `output_dim`, same shape as `"onehot"` but with fractional -membership instead of a single 1). +hard. It emits one column per fitted bin, like `"onehot"`, but with fractional memberships. Edge placement follows `placement_strategy`: `"uniform"` for equal-width bins, `"quantile"` for equal-frequency bins. See [Resolution and placement](../core_concepts/resolution_and_placement.md). ```{tip} -Quantile edges give every bin a similar number of samples, which is usually more stable than -equal-width bins when the feature is skewed. +When the feature has few ties, quantile edges give bins similar sample counts, which can be +more stable than equal-width bins on skewed data. ``` ## Piecewise-linear encoding @@ -64,10 +67,8 @@ from pretab.transformers import PLETransformer X = np.random.default_rng(0).uniform(size=(100, 1)) y = np.random.default_rng(0).integers(0, 2, size=100) t = PLETransformer(output_dim=12, task="classification") -t.fit_transform(X, y).shape -# (100, 12): output_dim is exact here (no adaptive clamping) -t.total_output_dim_ -# 12 +assert t.fit_transform(X, y).shape == (100, 12) +assert t.total_output_dim_ == 12 ``` Constructor highlights: `output_dim`, `placement_strategy="cart"`, `task="regression"`, @@ -80,10 +81,11 @@ and should be fit leakage-safely, ideally with cross-fitting. See ``` ```{warning} -Because PLE always reads `y` to place its bins, fitting it directly on data you will also train -on emits a `LeakageWarning`. Fit it inside a scikit-learn `Pipeline` or wrap it in -`pretab.CrossFittedTransformer` so the bin edges never see the rows they will later transform -for training. +The standalone fit above emits `LeakageWarning` because PLE uses `y` to place its bins. For +evaluation, split before fitting or pass the entire scikit-learn `Pipeline` to +cross-validation. A plain pipeline suppresses the warning but still uses each training +row's target when fitting its bins. For out-of-fold training features, wrap PLE in +`pretab.CrossFittedTransformer` and use `fit_transform(X, y)`. ``` ### Why piecewise-linear rather than one-hot @@ -108,12 +110,18 @@ opposite ends of a number line. ```python import numpy as np +from pretab.exceptions import PretabDataError from pretab.transformers import PeriodicEncodingTransformer X = np.array([[0], [6], [12], [18], [24]]) # hour-of-day style values t = PeriodicEncodingTransformer(period=24, harmonics=2) # e.g. hour of day -t.fit_transform(X).shape -# (5, 4): 2 columns (sin, cos) per harmonic +encoded = t.fit_transform(X) +assert encoded.shape == (5, 4) +np.testing.assert_allclose(encoded[0], encoded[-1], atol=1e-12) +np.testing.assert_allclose(t.transform([[25], [-1]]), t.transform([[1], [23]]), atol=1e-12) + +with np.testing.assert_raises(PretabDataError): + PeriodicEncodingTransformer(period=24).fit([[0], [25]]) ``` Constructor highlights: `period` (required, the cycle length), `harmonics=1`, @@ -124,25 +132,19 @@ one extra column when `include_original=True`. Higher `harmonics` lets the encod finer-grained sub-cycles (for example distinguishing morning from afternoon within a day), at the cost of a wider output. -```{warning} -PreTab has no mechanism to detect the period automatically from the data. `period` is a -required constructor argument with no default, and `fit` only validates that values fall -within `[0, period]`, it never infers the cycle length. You must know and supply the period -yourself (24 for hour of day, 7 for day of week, 12 for month of year, and so on). -``` - ```{important} -Valid input is the **closed interval** `[0, period]`: both endpoints are accepted, and by -construction they map to the identical `(sin, cos)` pair, since `x=0` and `x=period` are the -same point on the cycle. Values outside `[0, period]` raise a `PretabDataError` at fit and -transform, there is no silent wrap-around or clamping. +Supply the period explicitly. `fit` does not infer it and raises `PretabDataError` if a +training value falls outside `[0, period]`. Both endpoints are accepted and their harmonic +columns agree up to floating-point precision. After fitting, `transform` accepts values +outside that interval and the sine and cosine terms wrap around the cycle. If +`include_original=True`, the extra raw column is not wrapped. ``` ```{note} Periodic encoding is a standalone time-series utility. It is not wired into `Preprocessor` because it requires a per-feature `period`, so apply it directly to the relevant cyclical -column. Use [Fourier features](functional_expansions.md#fourier-features) instead when you want -the model to search across a set of frequencies rather than commit to one known period. +column. [Fourier features](functional_expansions.md#fourier-features) instead set their base +frequency from the fitted range; they do not infer a cycle length from the data. ``` ## Binning versus PLE diff --git a/docs/representations/spline_expansions.md b/docs/representations/spline_expansions.md index 4129dcc..10028bc 100644 --- a/docs/representations/spline_expansions.md +++ b/docs/representations/spline_expansions.md @@ -1,29 +1,29 @@ # Spline expansions -Splines are piecewise-polynomial bases with local support. They turn a single numerical column -into a set of smooth, overlapping basis functions, so a linear model on top can bend to follow -the data while staying stable. PreTab ships the full family, from the workhorse B-spline to the -multivariate thin-plate spline. +Knot-based splines turn a numerical column into piecewise-polynomial basis functions, so a +linear model can fit a smooth curve. Some bases, such as B-splines, have local support. PreTab +also provides multivariate splines for modeling smooth surfaces over several inputs. ## The idea A spline places a set of **knots** along the range of a feature and builds basis functions -between them. The transformed feature is the vector of basis values, +between them. The transformed feature is the vector of basis values: $$ -x \mapsto \big(B_1(x),\ B_2(x),\ \dots,\ B_K(x)\big), +x \mapsto \big(B_1(x),\ B_2(x),\ \dots,\ B_K(x)\big). $$ -where each $B_k$ is nonzero only near a few knots. Local support is what keeps splines stable: -a point in one region does not disturb the fit in another. Width is set by `output_dim` and -knot positions by `placement_strategy` (see +For a B-spline basis, each $B_k$ is nonzero only near a few knots, so changing one coefficient +affects the fitted curve only in that region. Configure width with `output_dim` and knot +placement with `placement_strategy` (see [Resolution and placement](../core_concepts/resolution_and_placement.md)). ```{important} -Without explicit knots, `output_dim` is the number of output columns for a univariate spline -**per input feature**, not the total. A `(n_samples, 3)` input produces -`(n_samples, 3 * output_dim)` output (plus one extra column per feature if -`include_bias=True`). Feature names are suffixed per input, for example `age_bs0, age_bs1, ...` +In fixed-width mode with automatic knot placement, a standalone univariate spline emits +`output_dim` columns **per input feature**, plus one per feature if `include_bias=True`. +With adaptive sizing, supported families can fit different widths for different features. +Check `n_basis_` for the per-feature widths, including any bias, or `total_output_dim_` for the +total. Feature names are suffixed per input, for example `age_bs0, age_bs1, ...` for a B-spline fitted on a DataFrame column `age` (`x0_bs0, x0_bs1, ...` for array input). For B/M/I splines with explicit `knot_locations`, a feature with `K` retained unique interior knots instead gets `K + degree + 1` non-bias columns; @@ -67,9 +67,8 @@ smoother, wider-support basis functions at the same `output_dim`; `degree=1` rec piecewise-linear segments. `output_dim` -: The exact per-feature output width (unlike the cubic/natural/tensor families below, no -conversion is applied). Ignored when `knot_locations` is provided. More columns track finer -local detail and increase overfitting risk. +: The per-feature width before any bias in fixed-width mode. Explicit `knot_locations` +override this request. More columns track finer local detail and increase overfitting risk. `include_bias` : Defaults to `False`. A B-spline basis over a clamped knot vector already sums to 1 in every @@ -150,8 +149,8 @@ Requires `output_dim >= 2`. For knots $\xi_1, \dots, \xi_T$ ($\xi_1$, $\xi_T$ th knots), the basis stacks $x$ with one constrained term per interior knot $\xi_k$, $$ -d_k(x) = \frac{(x - \xi_k)_+^3 - (x - \xi_T)_+^3}{\xi_T - \xi_k}, \qquad -N_k(x) = d_k(x) - \frac{\xi_T - \xi_k}{\xi_T - \xi_1} d_1(x) - \frac{\xi_k - \xi_1}{\xi_T - \xi_1} d_T(x). +d_k(x) = (x - \xi_k)_+^3 - (x - \xi_T)_+^3, \qquad +N_k(x) = d_k(x) - \frac{\xi_T - \xi_k}{\xi_T - \xi_1} d_1(x), \quad k = 2, \ldots, T - 1. $$ ```python @@ -161,9 +160,12 @@ from pretab.transformers import NaturalCubicSplineTransformer X = np.linspace(0, 1, 50).reshape(-1, 1) t = NaturalCubicSplineTransformer(output_dim=8) X2 = t.fit_transform(X) -X2.shape # (50, 8): output width equals output_dim exactly -t.n_knots_ # [7]: fitted interior-knot count per feature (output_dim - 1) -t.get_penalty_matrix().shape # (8, 8) +assert X2.shape == (50, 8) +assert t.n_knots_ == [7] +assert t.get_penalty_matrix().shape == (8, 8) + +tail = t.transform([[1.0], [1.25], [1.5]]) +np.testing.assert_allclose(np.diff(tail, n=2, axis=0), 0, atol=1e-12) ``` ```{tip} @@ -198,8 +200,8 @@ t.get_penalty_matrix().shape # (8, 8) ``` Constructor highlights: `output_dim`, `degree=3`, `diff_order=2`, `include_bias=False`, -`placement_strategy="uniform"`, `adaptive`. The P-spline is unsupervised; it does not read the -target. +`placement_strategy="uniform"`. The P-spline uses uniformly spaced knots and a fixed width; +it does not read the target. **Parameter impact.** `diff_order` sets the order of the penalty: `diff_order=1` penalizes changes in level between adjacent coefficients (favors flat fits), `diff_order=2` (the default) diff --git a/docs/tutorials/adaptive_resolution.md b/docs/tutorials/adaptive_resolution.md index 6f7870a..d055410 100644 --- a/docs/tutorials/adaptive_resolution.md +++ b/docs/tutorials/adaptive_resolution.md @@ -1,31 +1,21 @@ # Adaptive resolution -Picking the width of an expansion by hand is guesswork. Adaptive resolution lets the data -choose it for you, within bounds you set. This tutorial shows how to turn it on and how to read -the width that was selected. +Adaptive resolution lets supported representations adjust their width at fit time. This tutorial +shows how to set a search window and how to read the fitted width. ## The idea -Every adaptive-capable method accepts three parameters that turn a fixed width into a searched -one. +Adaptive-capable methods accept three settings: `adaptive=True` -: Enables data-driven width selection. +: Enables width adaptation on supported placement paths. `min_output_dim` and `max_output_dim` -: The lower and upper bounds of the search. The method picks a width in this range. - -When adaptive is on and both bounds are set, `output_dim` is ignored completely: the fitted -width comes only from `[min_output_dim, max_output_dim]` and the data. If you leave one bound -unset, `output_dim` fills in for it (as the missing lower or upper edge of the search), so it -still matters in that case. See -[Resolution and placement](../core_concepts/resolution_and_placement.md) for the mechanics. - -```{warning} -Setting `output_dim` alongside `adaptive=True` with both `min_output_dim` and `max_output_dim` -is harmless but silently has no effect. It is easy to assume it caps or anchors the search; it -does not. Drop it, or drop one of the two bounds if you meant `output_dim` to anchor the window. -``` +: The requested lower and upper bounds. The final width also depends on the method and data. + +When a supervised search runs, two explicit bounds define its search window. If a bound is +omitted, `output_dim` helps determine the missing edge. The requested `output_dim` must still +be valid for the method, even when both bounds are set. ## A worked example @@ -34,8 +24,10 @@ one chose. ```python import warnings + import numpy as np -import pandas as pd + +from pretab.exceptions import LeakageWarning from pretab.transformers import BSplineTransformer rng = np.random.default_rng(0) @@ -51,7 +43,7 @@ for name, y in [("simple", simple), ("wiggly", wiggly)]: target_aware=True, placement_strategy="cart", task="regression", ) with warnings.catch_warnings(): - warnings.simplefilter("ignore") # one-off fit, not reused to train a model + warnings.simplefilter("ignore", LeakageWarning) t.fit(x.reshape(-1, 1), y) print(f"{name:8s} -> selected width {t.total_output_dim_}") ``` @@ -61,12 +53,9 @@ simple -> selected width 20 wiggly -> selected width 20 ``` -Both widths land inside the `[5, 20]` window without you having to guess a number up front. -Here both reach the upper bound: with 3000 samples the CART selector finds more informative -splits than the window admits, so it keeps the most informative ones. Its split count is governed -more by its own tree depth and minimum-samples settings than by how wiggly the signal looks; with -smaller data or a wider window the two searches can land on different widths. The bound is what -you control directly, the exact count inside it is data-driven. +Both fits reach the upper bound in this example. Adaptive width reflects the splits the CART +selector finds under its tree settings. A more irregular signal does not necessarily get more +columns. ```{note} Fitting a target-aware transformer directly like this, outside a `Pipeline`, normally emits a @@ -75,53 +64,59 @@ output is never used to train a downstream model. See [Target awareness](../core_concepts/target_awareness.md) for when the warning matters. ``` -```{note} -Adaptive resolution only takes effect on the target-aware placement path -(`target_aware=True`, paired with `placement_strategy="cart"` or `"lightgbm"`). With the -default `target_aware=False`, `adaptive=True` is a silent no-op and the transformer keeps its -ordinary fixed `output_dim` width. -``` +## Adaptation without a target -```{tip} -Set `min_output_dim` and `max_output_dim` to a range you consider reasonable, then let the data -place the width inside it. This is more robust than committing to a single `output_dim` across -features of different complexity. +B-, M-, and I-splines can also adapt without a target. They start from `output_dim` and adjust +the unsupervised knots toward the requested bounds. For example, a target-free B-spline with +bounds `[4, 6]` can keep a requested width of 5 or reduce a requested width of 12 to 6. +By contrast, natural cubic splines and maps such as RBF and ReLU keep their ordinary fixed +sizing on the target-free path. PLE always uses the target and does not require a +`target_aware` flag. + +```{note} +B-, M-, and I-splines cap the number of interior knots by the number of distinct input +values. A column with few distinct values can produce fewer columns than `min_output_dim`. +Use the fitted width for any downstream model or size check. ``` ## Adaptive across a whole preprocessor -The same switch works at the `Preprocessor` level, so every eligible column adapts -independently. +`Preprocessor` passes the global settings to eligible features, which are fitted independently. +This example applies the target-free B-spline settings to two columns with enough distinct values. ```python import pandas as pd from pretab import Preprocessor -df = pd.DataFrame({"simple": simple, "wiggly": wiggly}) +df = pd.DataFrame({"value": x, "squared": x**2}) pre = Preprocessor( numerical_method="bspline", + output_dim=12, adaptive=True, - min_output_dim=5, - max_output_dim=15, + min_output_dim=4, + max_output_dim=6, + target_aware=False, + placement_strategy="quantile", ) -pre.fit(df, wiggly) -pre.get_feature_info() +pre.fit(df) +assert pre.output_dims_ == {"value": 6, "squared": 6} +assert pre.total_output_dim_ == 12 ``` -Each numerical column receives a width suited to its own complexity, visible in the resolved -feature info. +`output_dims_` and `total_output_dim_` describe the fitted output, not the requested width +or bounds. For a per-feature breakdown, call `pre.get_feature_info()` after fitting. ```{note} -Adaptive resolution is available for B/M/I splines, the freely-placed cubic and natural cubic -splines, PLE, and the RBF, ReLU, sigmoid, and tanh feature maps. The penalized P-spline and the -tensor-product and thin-plate splines have a fixed structure and ignore the adaptive flag. The -[comparison table](../representations/comparison_table.md) marks which methods adapt. +The [comparison table](../representations/comparison_table.md) marks which methods support +adaptive resolution. An unsupported method such as P-spline ignores the global adaptive +setting. An explicit per-feature `RepresentationConfig("pspline", adaptive=True)` is +rejected when `Preprocessor` validates its configuration. ``` ## Where to go next -- [Resolution and placement](../core_concepts/resolution_and_placement.md) for how width and - placement interact. +- [Placement strategies](../core_concepts/resolution_and_placement.md#placement-where-the-units-go) + for how the locations of knots and centers are chosen. - [Comparing representations](comparing_representations.md) to measure adaptive against fixed. - [Choosing a method](../representations/choosing_a_method.md) for width guidance. diff --git a/docs/tutorials/comparing_representations.md b/docs/tutorials/comparing_representations.md index 4d4d10b..5fbdc11 100644 --- a/docs/tutorials/comparing_representations.md +++ b/docs/tutorials/comparing_representations.md @@ -1,8 +1,7 @@ # Comparing representations -Choosing a representation should be an experiment, not a guess. This tutorial evaluates several -numerical methods on the same task with the same model, so the only thing that varies is the -basis. The pattern generalizes to any dataset you have. +Compare numerical representations on the same task, with the same folds and downstream model. +This tutorial measures both validation scores and fitted widths for each candidate. ## The setup @@ -15,7 +14,7 @@ import pandas as pd from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score +from sklearn.model_selection import cross_validate rng = np.random.default_rng(0) n = 3000 @@ -48,18 +47,18 @@ results = {} for name, transformer in candidates.items(): features = ColumnTransformer([("x", transformer, ["x"])]) model = Pipeline([("features", features), ("ridge", Ridge(alpha=1.0))]) - scores = cross_val_score(model, df, y, cv=5, scoring="r2") - results[name] = (scores.mean(), scores.std()) + results[name] = cross_validate(model, df, y, cv=5, scoring="r2", return_estimator=True) -for name, (mean, std) in results.items(): - print(f"{name:20s} R2 = {mean:.3f} +/- {std:.3f}") +for name, result in results.items(): + scores = result["test_score"] + print(f"{name:20s} R2 = {scores.mean():.3f} +/- {scores.std():.3f}") ``` ```text minmax (baseline) R2 = 0.111 +/- 0.030 bspline R2 = 0.966 +/- 0.002 rbf R2 = 0.965 +/- 0.003 -ple R2 = 0.955 +/- 0.005 +ple R2 = 0.942 +/- 0.004 ``` The scaled baseline fits a straight line and cannot follow the sine. Every expansion captures @@ -72,22 +71,24 @@ That isolates the effect of the basis so the comparison is fair. ## Weigh width against accuracy -More columns can buy accuracy, but they also cost memory and overfitting headroom. Estimate the -output width before you commit, using the `Preprocessor` budget tools. +Wider representations use more memory and can overfit. Count the output features of the same +fitted pipelines that produced the validation scores. Widths can differ across folds, so check +each one rather than assuming the requested `output_dim` was realized. ```python -from pretab import Preprocessor - -for method in ["bspline", "rbf", "ple"]: - pre = Preprocessor(numerical_method=method, output_dim=12).fit(df, y) - shape = pre.estimate_output_shape(df) - print(f"{method:8s} -> {shape[1]} columns") +for name, result in results.items(): + widths = [ + len(fold.named_steps["features"].get_feature_names_out()) + for fold in result["estimator"] + ] + print(f"{name:20s} fitted widths: {widths}") ``` ```{note} -A method that wins by a hair but doubles the column count may not be worth it. Read the width -from `estimate_output_shape` and factor it into the decision. See -[Outputs and inspection](../core_concepts/outputs_and_inspection.md). +Here the baseline has one column and every expansion has 12 in each fold. When comparing +`Preprocessor` candidates, you can read `total_output_dim_` after fitting or call +`estimate_output_shape(X)` on a fitted instance to include the row count for new input. See +[Outputs and inspection](../core_concepts/outputs_and_inspection.md) for output budgets. ``` ## When nothing beats the baseline diff --git a/docs/tutorials/custom_representation.md b/docs/tutorials/custom_representation.md index b00a0e4..9dd2590 100644 --- a/docs/tutorials/custom_representation.md +++ b/docs/tutorials/custom_representation.md @@ -12,11 +12,12 @@ A complete, installable version of this example lives in the repository under ## Subclass `BaseRepresentation` -`BaseRepresentation` gives you the shared scikit-learn contract: NaN-aware validation, estimator -tags, `get_feature_names_out`, and a typed `RepresentationSpec`. You implement `fit`, -`transform`, and one sizing hook, and declare a small amount of metadata. Fitted on a DataFrame, -`self._validate` records the column names as `feature_names_in_` and checks them at `transform`, -and the output names use them (`length_f0` rather than `x0_f0`). +`BaseRepresentation` provides input validation, scikit-learn tags, `get_feature_names_out`, +and a typed `RepresentationSpec`. The shared validator accepts `NaN` by default, but it does +not impute values for you. This example sets `_allow_nan = False` because computing a column's +range requires finite data. When fitted on a DataFrame, `self._validate` records its column names +and checks them at transform time. The output names use the recorded names (`length_f0` rather +than `x0_f0`). ```python import numpy as np @@ -31,6 +32,7 @@ class ChebyshevRepresentation(BaseRepresentation): feature_kind = "numerical" scope = "univariate" supervision = "unsupervised" + _allow_nan = False def __init__(self, degree=5): self.degree = degree @@ -47,7 +49,7 @@ class ChebyshevRepresentation(BaseRepresentation): return np.clip(2.0 * (X - self.data_min_) / span - 1.0, -1.0, 1.0) def transform(self, X): - check_is_fitted(self, "n_features_in_") + check_is_fitted(self, ("data_min_", "data_max_")) z = self._rescale(np.asarray(self._validate(X, reset=False), dtype=float)) theta = np.arccos(z) blocks = [ @@ -122,14 +124,18 @@ import pandas as pd rng = np.random.default_rng(0) df = pd.DataFrame({"x": rng.uniform(-3, 3, size=500)}) -y = np.cos(df["x"] * 2) + rng.normal(0, 0.1, size=500) +df.loc[0, "x"] = np.nan pre = Preprocessor(numerical_method="chebyshev", degree=8) -X2 = pre.fit_transform(df, y) +X2 = pre.fit_transform(df) +assert X2.shape == (len(df), 8) +assert np.isfinite(X2).all() ``` The `allowed_args` list tells `Preprocessor` which of its shared keyword arguments to pass -through to your constructor. +through to your constructor. Its numerical pipeline imputes the missing value before calling +the representation. When using the transformer on its own, pass finite data or put an imputer +before it in a pipeline. ## Ship it as a plugin diff --git a/docs/tutorials/multivariate_features.md b/docs/tutorials/multivariate_features.md index 1383855..2a8d3fd 100644 --- a/docs/tutorials/multivariate_features.md +++ b/docs/tutorials/multivariate_features.md @@ -253,7 +253,7 @@ X = rng.uniform(-3, 3, size=(n, 2)) y = np.exp(-(X[:, 0] ** 2 + X[:, 1] ** 2)) * 5 + rng.normal(0, 0.2, n) model = Pipeline([ - ("tps", ThinPlateSplineTransformer(n_components=20)), + ("tps", ThinPlateSplineTransformer(n_components=20, random_state=0)), ("ridge", Ridge(alpha=1.0)), ]) @@ -278,7 +278,7 @@ features approximate an RBF kernel without forming the full kernel matrix. from pretab.transformers import RandomFourierFeaturesTransformer model = Pipeline([ - ("rff", RandomFourierFeaturesTransformer(n_components=200, gamma=0.5)), + ("rff", RandomFourierFeaturesTransformer(n_components=200, gamma=0.5, random_state=0)), ("ridge", Ridge(alpha=1.0)), ]) @@ -286,6 +286,9 @@ scores = cross_val_score(model, X, y, cv=5, scoring="r2") print(f"5-fold R2: {scores.mean():.3f} +/- {scores.std():.3f}") ``` +Both examples seed the transformer as well as the data generator. This makes landmark +selection and random projections repeatable in the same environment. + ```{note} Random Fourier features and Nyström both approximate a kernel machine. Random Fourier features scale to large data with random projections; Nyström samples landmark points and is often more diff --git a/docs/tutorials/nonlinear_regression.md b/docs/tutorials/nonlinear_regression.md index 2c47964..e548d0c 100644 --- a/docs/tutorials/nonlinear_regression.md +++ b/docs/tutorials/nonlinear_regression.md @@ -121,13 +121,13 @@ print(f"MAE: {mean_absolute_error(y_test, pred):.2f}") ```text features: 40 -R2: 0.983 -MAE: 1.78 +R2: 0.977 +MAE: 2.04 ``` The data and the `Ridge` model are unchanged, but the expressive features let it capture the -nonlinear structure. The $R^2$ jumps from `0.124` to `0.983` and the mean absolute error drops -from `11.20` to `1.78`. +nonlinear structure. The $R^2$ rises from `0.124` to `0.977` and the mean absolute error drops +from `11.20` to `2.04`. ```{tip} `Preprocessor.transform` returns a single stacked array by default, so it drops straight into @@ -138,26 +138,23 @@ a plain scikit-learn estimator or `Pipeline`. Pass `output_structure="blocks"` ( ## What actually changed -The `Preprocessor` expands four raw columns into 40 features. Inspect the resolved layout with -`get_feature_info`: +The `Preprocessor` expands four raw columns into 40 features. `get_feature_info()` returns +separate dictionaries for numerical, categorical, and embedding features. Read the fitted +widths directly from those dictionaries: ```python -pre.get_feature_info() +numerical, categorical, _ = pre.get_feature_info(verbose=False) +assert {name: info["dimension"] for name, info in numerical.items()} == { + "age": 12, "income": 12, "tenure": 12, +} +assert categorical["city"]["dimension"] == 4 ``` -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> bspline 12 - -income numerical imputer -> minmax -> ple 12 - -tenure numerical imputer -> minmax -> rbf 12 - -city categorical imputer -> onehot -> to_float 4 4 -``` - -Each numeric column is imputed, scaled, then expanded into a basis the linear model can weight -independently: 12 spline coefficients for `age`, 12 PLE bins for `income`, and 12 RBF bumps for -`tenure`, while `city` becomes four one-hot columns. To trace any single output column back to -its source, use [feature lineage](../core_concepts/outputs_and_inspection.md). +Each numeric column is imputed, scaled, then expanded into features the linear model can weight +independently. The categorical pipeline normalizes missing values, imputes them, and produces +four floating-point one-hot columns. Call `get_feature_info(verbose=True)` to log the fitted +pipelines and fit-time settings. To trace an output column back to its source, use +[feature lineage](../core_concepts/outputs_and_inspection.md). ## Where to go next diff --git a/docs/tutorials/sklearn_pipeline.md b/docs/tutorials/sklearn_pipeline.md index 5a9c966..7749e3c 100644 --- a/docs/tutorials/sklearn_pipeline.md +++ b/docs/tutorials/sklearn_pipeline.md @@ -79,7 +79,7 @@ print(f"5-fold R2: {scores.mean():.3f} +/- {scores.std():.3f}") ``` ```text -5-fold R2: 0.948 +/- 0.005 +5-fold R2: 0.944 +/- 0.004 ``` ## Tune with GridSearchCV @@ -105,7 +105,7 @@ print(f"best CV R2: {grid.best_score_:.3f}") ```text best params: {'features__age__output_dim': 6, 'ridge__alpha': 0.1} -best CV R2: 0.949 +best CV R2: 0.945 ``` Every pretab transformer participates in the search grid just like a native `sklearn` step. diff --git a/docs/tutorials/target_aware_classification.md b/docs/tutorials/target_aware_classification.md index f3d7fc0..9869524 100644 --- a/docs/tutorials/target_aware_classification.md +++ b/docs/tutorials/target_aware_classification.md @@ -142,11 +142,11 @@ print(f"5-fold ROC AUC: {scores.mean():.3f} +/- {scores.std():.3f}") ``` ```{important} -A supervised transformer fit outside a cross-validation or `Pipeline` context emits a -`LeakageWarning`. Inside the `Pipeline` here, the warning is suppressed because each fold fits -the representation on training data only. For the strongest guarantee on training features -themselves, wrap the transformer in `CrossFittedTransformer`. See -[Target awareness](../core_concepts/target_awareness.md). +PreTab suppresses `LeakageWarning` in recognized fitting contexts such as `Pipeline`, even for +a single fit on the full dataset. Here `cross_val_score`, not warning suppression, keeps +validation labels out of the fit. A plain pipeline still trains the classifier on features that +can depend on those same rows' labels. Wrap the preprocessing step in `CrossFittedTransformer` +to generate out-of-fold training features. See [Target awareness](../core_concepts/target_awareness.md). ``` ## Where to go next diff --git a/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py b/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py index 808ae65..495789d 100644 --- a/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py +++ b/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py @@ -24,6 +24,9 @@ class ChebyshevRepresentation(BaseRepresentation): ``T_0`` term is dropped to avoid a redundant bias column). This yields ``degree`` output columns per input feature. + Inputs must be finite. Impute missing values before calling the transformer + directly, or use it in a ``Preprocessor`` numerical pipeline. + Parameters ---------- degree : int, default=5 @@ -34,6 +37,7 @@ class ChebyshevRepresentation(BaseRepresentation): feature_kind = "numerical" scope = "univariate" supervision = "unsupervised" + _allow_nan = False def __init__(self, degree=5): self.degree = degree @@ -50,7 +54,7 @@ def _rescale(self, X): return np.clip(2.0 * (X - self.data_min_) / span - 1.0, -1.0, 1.0) def transform(self, X): - check_is_fitted(self, "n_features_in_") + check_is_fitted(self, ("data_min_", "data_max_")) z = self._rescale(np.asarray(self._validate(X, reset=False), dtype=float)) theta = np.arccos(z) blocks = [ diff --git a/examples/pretab-chebyshev/tests/test_chebyshev.py b/examples/pretab-chebyshev/tests/test_chebyshev.py index 4f52d12..bddb7b9 100644 --- a/examples/pretab-chebyshev/tests/test_chebyshev.py +++ b/examples/pretab-chebyshev/tests/test_chebyshev.py @@ -6,9 +6,28 @@ import numpy as np import pandas as pd +import pytest from pretab_chebyshev import ChebyshevRepresentation +from sklearn.exceptions import NotFittedError from pretab import Preprocessor, check_representation, list_representations, register_representation +from pretab.compose import registry + + +@pytest.fixture(autouse=True) +def _restore_registry(): + saved_registry = registry.TRANSFORMER_REGISTRY.copy() + saved_numerical = registry.NUMERICAL_METHODS.copy() + saved_categorical = registry.CATEGORICAL_METHODS.copy() + try: + yield + finally: + registry.TRANSFORMER_REGISTRY.clear() + registry.TRANSFORMER_REGISTRY.update(saved_registry) + registry.NUMERICAL_METHODS.clear() + registry.NUMERICAL_METHODS.update(saved_numerical) + registry.CATEGORICAL_METHODS.clear() + registry.CATEGORICAL_METHODS.update(saved_categorical) def test_passes_conformance_suite(): @@ -17,11 +36,28 @@ def test_passes_conformance_suite(): assert "deterministic" in passed +def test_rejects_nan_during_fit_and_transform(): + finite = np.array([[0.0], [1.0]]) + missing = np.array([[0.0], [np.nan], [1.0]]) + transformer = ChebyshevRepresentation() + + with pytest.raises(ValueError, match="NaN"): + transformer.fit(missing) + with pytest.raises(NotFittedError): + transformer.transform(finite) + + transformer.fit(finite) + with pytest.raises(ValueError, match="NaN"): + transformer.transform(missing) + assert np.isfinite(transformer.transform(finite)).all() + + def test_register_and_use_through_preprocessor(): register_representation("chebyshev", ChebyshevRepresentation, allowed_args=("degree",), override=True) assert "chebyshev" in list_representations(feature_kind="numerical") X = pd.DataFrame({"a": np.linspace(0, 1, 20), "b": np.linspace(-1, 1, 20)}) + X.loc[0, "a"] = np.nan pre = Preprocessor( numerical_method="chebyshev", categorical_method="none", @@ -31,3 +67,4 @@ def test_register_and_use_through_preprocessor(): ) out = np.asarray(pre.fit_transform(X, return_array=True)) assert out.shape == (20, 8) # degree 4 x 2 features + assert np.isfinite(out).all() diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index 39502ab..2a13280 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -18,6 +18,7 @@ ROOT = Path(__file__).parents[2] TUTORIALS_DIR = ROOT / "docs" / "tutorials" CORE_CONCEPTS_DIR = ROOT / "docs" / "core_concepts" +REPRESENTATIONS_DIR = ROOT / "docs" / "representations" _FENCE = re.compile(r"^```python\n(.*?)^```\s*$", re.DOTALL | re.MULTILINE) @@ -45,8 +46,13 @@ def _code_blocks(path: Path, section: str | None = None) -> list[tuple[int, str] _PAGES = [ *sorted(TUTORIALS_DIR.glob("*.md")), *sorted(CORE_CONCEPTS_DIR.glob("*.md")), + REPRESENTATIONS_DIR / "functional_expansions.md", + REPRESENTATIONS_DIR / "kernel_approximation.md", + REPRESENTATIONS_DIR / "numerical_encoding.md", + REPRESENTATIONS_DIR / "spline_expansions.md", ROOT / "README.md", ROOT / "docs" / "homepage.md", + ROOT / "docs" / "getting_started" / "overview.md", ROOT / "docs" / "getting_started" / "quickstart.md", ROOT / "docs" / "developer_guide" / "architecture.md", ] @@ -77,11 +83,6 @@ def isolate_document_state(tmp_path, monkeypatch): "Grouped preprocessing with Preprocessor", id="feature-groups", ), - pytest.param( - ROOT / "docs" / "representations" / "spline_expansions.md", - "Typed spline penalties", - id="spline-penalties", - ), ], ) @pytest.mark.filterwarnings("ignore::pretab.exceptions.LeakageWarning") From 0c7e4438382fd8f84f0c34e870b1955b36753e54 Mon Sep 17 00:00:00 2001 From: Manish Kumar Date: Tue, 24 Nov 2026 23:42:54 +0100 Subject: [PATCH 86/86] test: include task_validation in resolved facade fields --- tests/compose/test_factory.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index fe46757..66ffdfc 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -662,6 +662,7 @@ def test_preprocessor_routes_one_normalized_config_through_the_factory(sample_fr "output_structure", "output_format", "dtype", + "task_validation", } assert set(resolved) == config_fields | facade_fields assert config_fields.isdisjoint(facade_fields)