Skip to content

FIX Remove spurious feature names warning in IsolationForest #25931

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
merged 5 commits into from
Mar 22, 2023
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
5 changes: 5 additions & 0 deletions doc/whats_new/v1.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,11 @@ Changelog
when `max_samples` is a float and `round(n_samples * max_samples) < 1`.
:pr:`25601` by :user:`Jan Fidor <JanFidor>`.

- |Fix| :meth:`ensemble.IsolationForest.fit` no longer warns about missing
feature names when called with `contamination` not `"auto"` on a pandas
dataframe.
:pr:`25931` by :user:`Yao Xiao <Charlie-XIAO>`.

:mod:`sklearn.exception`
........................
- |Feature| Added :class:`exception.InconsistentVersionWarning` which is raised
Expand Down
24 changes: 16 additions & 8 deletions sklearn/ensemble/_iforest.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,10 @@ def fit(self, X, y=None, sample_weight=None):
self.offset_ = -0.5
return self

# else, define offset_ wrt contamination parameter
self.offset_ = np.percentile(self.score_samples(X), 100.0 * self.contamination)
# Else, define offset_ wrt contamination parameter
# To avoid performing input validation a second time we call
# _score_samples rather than score_samples
self.offset_ = np.percentile(self._score_samples(X), 100.0 * self.contamination)

return self

Expand Down Expand Up @@ -428,15 +430,21 @@ def score_samples(self, X):
The anomaly score of the input samples.
The lower, the more abnormal.
"""
# code structure from ForestClassifier/predict_proba

check_is_fitted(self)

# Check data
X = self._validate_data(X, accept_sparse="csr", dtype=np.float32, reset=False)

# Take the opposite of the scores as bigger is better (here less
# abnormal)
return self._score_samples(X)

def _score_samples(self, X):
"""Private version of score_samples without input validation.

Input validation would remove feature names, so we disable it.
"""
# Code structure from ForestClassifier/predict_proba

check_is_fitted(self)

# Take the opposite of the scores as bigger is better (here less abnormal)
return -self._compute_chunked_score_samples(X)

def _compute_chunked_score_samples(self, X):
Expand Down
18 changes: 18 additions & 0 deletions sklearn/ensemble/tests/test_iforest.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,21 @@ def test_base_estimator_property_deprecated():
)
with pytest.warns(FutureWarning, match=warn_msg):
model.base_estimator_


def test_iforest_preserve_feature_names():
"""Check that feature names are preserved when contamination is not "auto".

Feature names are required for consistency checks during scoring.

Non-regression test for Issue #25844
"""
pd = pytest.importorskip("pandas")
rng = np.random.RandomState(0)

X = pd.DataFrame(data=rng.randn(4), columns=["a"])
model = IsolationForest(random_state=0, contamination=0.05)

with warnings.catch_warnings():
warnings.simplefilter("error", UserWarning)
model.fit(X)