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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion pretab/preprocessing/missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@


class _CategoricalMissingNormalizer(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Normalize object missing markers without changing numeric or sparse inputs."""
"""Normalize object missing markers without changing numeric or sparse inputs.

A batch in which every value is missing is returned as an ``object`` array of
NaN, whatever its dtype: pandas and polars type an all-missing column as
float, which an encoder fitted on string categories cannot compare with them.
"""

def fit(self, X, y=None):
validate_data(self, X, skip_check_array=True)
Expand All @@ -28,6 +33,11 @@ def transform(self, X):
# rejects nonzero fill values and changes OneHotEncoder's input contract.
return X.copy()
values = check_array(X, dtype=None, ensure_all_finite=False, copy=True) # type: ignore[arg-type]
if values.dtype.kind != "O" and values.size and pd.isna(values).all():
# An all-missing categorical column (e.g. one serving row with an unknown
# value) arrives as float NaN; as object NaN it matches the encoder's
# missing category whether the categories were strings or numbers.
values = values.astype(object)
if values.dtype.kind == "O":
return np.where(pd.isna(values), np.nan, values)
return X.copy() if isinstance(X, pd.DataFrame) else values
Expand Down
51 changes: 51 additions & 0 deletions tests/integration/test_pandas_missing.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,54 @@ def test_propagate_none_retains_raw_marker(marker, return_array):
else:
assert np.isnan(result[1, 0])
pd.testing.assert_frame_equal(frame, original)


_UNIMPUTED_OPTIONS = [
{"missing_policy": "propagate"},
{"categorical_imputation": None},
{"categorical_imputation": None, "add_missing_indicator": True},
{"missing_policy": "separate_state"},
]


@pytest.mark.parametrize("categorical_method", ["one-hot", "int"])
@pytest.mark.parametrize("missing_options", _UNIMPUTED_OPTIONS)
def test_all_missing_categorical_batch_matches_object_nan(categorical_method, missing_options):
"""pandas types an all-missing column as float64, so one serving row with an
unknown category crashed the one-hot encoder fitted on string categories."""
pre = Preprocessor(numerical_method="minmax", categorical_method=categorical_method, **missing_options)
pre.fit(_frame())
row = pd.DataFrame({"x": [0.3], "c": [np.nan]})
assert row["c"].dtype == np.float64

expected = pre.transform(row.astype({"c": object}), return_array=True)
np.testing.assert_array_equal(pre.transform(row, return_array=True), expected)


@pytest.mark.parametrize("with_missing_category", [True, False])
@pytest.mark.parametrize("categories", ["strings", "integers"])
def test_all_missing_one_hot_batch_encodes_as_missing_or_unknown(with_missing_category, categories):
codes = [3, 1, 2, 3, 2, 3] if categories == "integers" else ["a", "b", "c", "a", "c", "a"]
frame = pd.DataFrame({"x": [0.1, 0.4, 0.2, 0.9, 0.5, 0.7], "c": pd.Series(codes, dtype=object)})
if with_missing_category:
frame.loc[1, "c"] = np.nan
pre = Preprocessor(
numerical_method="minmax", categorical_method="one-hot", missing_policy="propagate", cat_cutoff=10
).fit(frame)
names = list(pre.get_feature_names_out())

out = pre.transform(pd.DataFrame({"x": [0.3, 0.6], "c": [np.nan, np.nan]}), return_array=True)

category_columns = [i for i, name in enumerate(names) if name.startswith("cat_c_")]
expected = [1.0 if names[i] == "cat_c_nan" else 0.0 for i in category_columns]
np.testing.assert_array_equal(out[:, category_columns], [expected, expected])


def test_all_missing_polars_column_is_encoded_like_pandas():
pl = pytest.importorskip("polars")
pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot", missing_policy="propagate")
pre.fit(_frame())
row = pl.DataFrame({"x": [0.3], "c": [None]})

expected = pre.transform(pd.DataFrame({"x": [0.3], "c": pd.Series([np.nan], dtype=object)}), return_array=True)
np.testing.assert_array_equal(pre.transform(row, return_array=True), expected)
Loading