Repository navigation
fix(missforest): preserve declared roles after header normalization #526
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
JohnnyWilson16
merged 3 commits into
FreshCode-Org:main
from
WilliamK112:codex/missforest-declared-role-normalization
Oct 13, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| """MissForest honors resolved declarations after column-name normalization.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import pandas as pd | ||
| import pytest | ||
|
|
||
| import freshdata as fd | ||
| from freshdata.imputation.missforest import MissForestImputer | ||
|
|
||
| ISOLATE = { | ||
| "strategy": "conservative", "fix_dtypes": False, "verbose": False, | ||
| "drop_empty_rows": False, "drop_empty_columns": False, | ||
| "missforest_add_indicators": False, | ||
| } | ||
|
|
||
|
|
||
| def _frame() -> pd.DataFrame: | ||
| frame = pd.DataFrame({ | ||
| "Observed Hours": [float(i % 12) for i in range(80)], | ||
| "External Measure": [10 + 2 * (i % 12) + 0.5 * (i % 5) for i in range(80)], | ||
| }) | ||
| frame.loc[frame.index[::11], "External Measure"] = float("nan") | ||
| return frame | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("role", ["target", "identifier", "both"]) | ||
| @pytest.mark.parametrize("choice", ["global", "per-column"]) | ||
| @pytest.mark.parametrize("declaration", ["External Measure", "external_measure"]) | ||
| def test_normalized_declared_roles_are_preserved_without_loading_models( | ||
| role, choice, declaration, monkeypatch | ||
| ): | ||
| def forbidden(): | ||
| raise AssertionError("a protected column must not train a model") | ||
|
|
||
| monkeypatch.setattr(MissForestImputer, "_sklearn_forests", staticmethod(forbidden)) | ||
| frame = _frame() | ||
| original = frame.copy(deep=True) | ||
| options = {} | ||
| if role in ("target", "both"): | ||
| options["target_column"] = declaration | ||
| if role in ("identifier", "both"): | ||
| options["id_columns"] = (declaration,) | ||
| if choice == "global": | ||
| options["impute"] = "missforest" | ||
| else: | ||
| options["impute_strategy"] = {"external_measure": "missforest"} | ||
|
|
||
| out, report = fd.clean(frame, return_report=True, **ISOLATE, **options) | ||
|
|
||
| pd.testing.assert_series_equal( | ||
| out["external_measure"], original["External Measure"].rename("external_measure") | ||
| ) | ||
| pd.testing.assert_frame_equal(frame, original) | ||
| (action,) = [a for a in report.actions if a.step == "impute"] | ||
| assert action.count == 0 | ||
| assert action.metadata["imputed_count"] == 0 | ||
| assert action.metadata["selected_model_type"] is None | ||
| expected = "identifier" if role == "identifier" else "target" | ||
| assert action.metadata["fallback_reason"] == f"{expected} column is never imputed" | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("role", ["target", "identifier"]) | ||
| @pytest.mark.parametrize("choice", ["global", "per-column"]) | ||
| def test_original_declarations_still_work_when_renaming_is_disabled(role, choice): | ||
| options = {"target_column": "External Measure"} if role == "target" else { | ||
| "id_columns": ("External Measure",) | ||
| } | ||
| options.update({"impute": "missforest"} if choice == "global" else { | ||
| "impute_strategy": {"External Measure": "missforest"} | ||
| }) | ||
| frame = _frame() | ||
| out = fd.clean(frame, column_names=False, **ISOLATE, **options) | ||
| pd.testing.assert_frame_equal(out, frame) | ||
|
|
||
|
|
||
| def test_eligible_feature_still_trains_while_the_declared_target_is_preserved(): | ||
| pytest.importorskip("sklearn") | ||
| frame = _frame() | ||
| frame["Other Measure"] = [20 + 3 * (i % 12) + 0.5 * (i % 5) for i in range(80)] | ||
| frame.loc[frame.index[::13], "Other Measure"] = float("nan") | ||
| out, report = fd.clean( | ||
| frame, impute="missforest", target_column="External Measure", | ||
| missforest_n_estimators=10, missforest_max_iter=2, return_report=True, **ISOLATE, | ||
| ) | ||
| pd.testing.assert_series_equal( | ||
| out["external_measure"], frame["External Measure"].rename("external_measure") | ||
| ) | ||
| assert out["other_measure"].notna().all() | ||
| (trained,) = [a for a in report.actions if a.column == "other_measure" and a.step == "impute"] | ||
| assert trained.metadata["selected_model_type"] == "regressor" | ||
| assert trained.count == 7 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("role", ["target", "identifier", "both"]) | ||
| @pytest.mark.parametrize("choice", ["global", "per-column"]) | ||
| def test_raw_declaration_tracks_the_correct_deduplicated_header(role, choice): | ||
| pytest.importorskip("sklearn") | ||
| frame = _frame().rename(columns={"External Measure": "A B"}) | ||
| frame["A-B"] = [20 + 3 * (i % 12) + 0.5 * (i % 5) for i in range(80)] | ||
| frame.loc[frame.index[::13], "A-B"] = float("nan") | ||
| options = {} | ||
| if role in ("target", "both"): | ||
| options["target_column"] = "A-B" | ||
| if role in ("identifier", "both"): | ||
| options["id_columns"] = ("A-B",) | ||
| options.update({"impute": "missforest"} if choice == "global" else { | ||
| "impute_strategy": {"a_b": "missforest", "a_b_2": "missforest"} | ||
| }) | ||
| out, report = fd.clean( | ||
| frame, missforest_n_estimators=10, missforest_max_iter=2, | ||
| return_report=True, **ISOLATE, **options, | ||
| ) | ||
| pd.testing.assert_series_equal(out["a_b_2"], frame["A-B"].rename("a_b_2")) | ||
| assert out["a_b"].notna().all() | ||
| (preserved,) = [a for a in report.actions if a.column == "a_b_2" and a.step == "impute"] | ||
| expected = "identifier" if role == "identifier" else "target" | ||
| assert preserved.metadata["fallback_reason"] == f"{expected} column is never imputed" | ||
|
|
||
|
|
||
| def test_resolving_roles_does_not_mutate_the_callers_config(): | ||
| frame = _frame() | ||
| config = fd.CleanConfig( | ||
| target_column="External Measure", impute="missforest", **ISOLATE | ||
| ) | ||
| out = fd.clean(frame, config=config) | ||
| assert config.target_column == "External Measure" | ||
| assert config.id_columns == () | ||
| pd.testing.assert_series_equal( | ||
| out["external_measure"], frame["External Measure"].rename("external_measure") | ||
| ) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When two raw headers such as
A BandA-Bnormalize toa_banda_b_2,_declared_rolesresolvestarget_column="A-B"to the first snake-case match (a_b). If both columns have missing values and enough rows for modeling, this assignment therefore makes MissForest skip the unrelated first column while the explicitly declareda_b_2target remains eligible for imputation. Resolve the declaration through the positional raw-to-normalized rename map (or its correct deduplicated label) before overriding the context role.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 25b936a. Exact raw target/id declarations now follow the positional raw-to-normalized mapping before the original header spellings are lost, so
A-Bcorrectly resolves toa_b_2. Added six model-backed regression cases covering target, identifier, and overlapping roles with global and per-column MissForest selection; all six failed before this change. An additional control verifies the caller's configuration is unchanged. All 44 focused checks pass on pandas 2.3 and 1.5; the full fast suite has 7,640 passes and only the five reproduced baseline failures.