Skip to content
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

Make RegressionOutlier dataframe-agnostic #665

Merged
Show file tree
Hide file tree
Changes from 2 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
26 changes: 22 additions & 4 deletions sklego/meta/regression_outlier_detector.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import narwhals as nw
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, OutlierMixin
from sklearn.utils.validation import check_array, check_is_fitted

Expand All @@ -11,8 +11,11 @@ class RegressionOutlierDetector(BaseEstimator, OutlierMixin):
----------
model : scikit-learn compatible regression model
A regression model that will be used for prediction.
column : int
The index of the target column to predict in the input data.
column : int | str
This should be:

- The index of the target column to predict in the input data, when the input is an array.
- The name of the target column to predict in the input data, when the input is a dataframe.
lower : float, default=2.0
Lower threshold for outlier detection. The method used for detection depends on the `method` parameter.
upper : float, default=2.0
Expand All @@ -32,6 +35,20 @@ class RegressionOutlierDetector(BaseEstimator, OutlierMixin):
The standard deviation of the differences between true and predicted values.
idx_ : int
The index of the target column in the input data.

Notes
-----
Native cross-dataframe support is achieved using
[Narwhals](https://narwhals-dev.github.io/narwhals/){:target="_blank"}.
Supported dataframes are:

- pandas
- Polars (eager)
- Modin
- cuDF

See [Narwhals docs](https://narwhals-dev.github.io/narwhals/extending/){:target="_blank"} for an up-to-date list
(and to learn how you can add your dataframe library to it!).
"""

def __init__(self, model, column, lower=2, upper=2, method="sd"):
Expand Down Expand Up @@ -112,7 +129,8 @@ def fit(self, X, y=None):
ValueError
If the `model` is not a regression estimator.
"""
self.idx_ = np.argmax([i == self.column for i in X.columns]) if isinstance(X, pd.DataFrame) else self.column
X = nw.from_native(X, eager_only=True, strict=False)
self.idx_ = np.argmax([i == self.column for i in X.columns]) if isinstance(X, nw.DataFrame) else self.column
X = check_array(X, estimator=self)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does check_array behave on narwhals frame? Converts it to numpy array?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point actually, thanks for having asked! I just digged into it, but admittedly I should have checked it more carefully in the first place

Yes, just like for pandas/polars input directly, it converts to a numpy array. BUT - they have some pandas-specific logic in there. So, we can just pass nw.to_native(X, strict=False), and then we can be sure there'll be no difference with respect to the status quo

if not self._is_regression_model():
raise ValueError("Passed model must be regression!")
Expand Down
11 changes: 7 additions & 4 deletions tests/test_meta/test_regression_outlier.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import numpy as np
import pandas as pd
import polars as pl
import pytest
from sklearn.linear_model import LinearRegression, LogisticRegression

Expand Down Expand Up @@ -42,14 +43,15 @@ def test_obvious_example():
assert preds[i] == -1


def test_obvious_example_pandas():
@pytest.mark.parametrize("frame_func", [pd.DataFrame, pl.DataFrame])
def test_obvious_example_dataframe(frame_func):
# generate random data for illustrative example
np.random.seed(42)
x = np.random.normal(0, 1, 100)
y = 1 + x + np.random.normal(0, 0.2, 100)
for i in [20, 25, 50, 80]:
y[i] += 2
X = pd.DataFrame({"x": x, "y": y})
X = frame_func({"x": x, "y": y})

# fit and plot
mod = RegressionOutlierDetector(LinearRegression(), column="y")
Expand All @@ -58,14 +60,15 @@ def test_obvious_example_pandas():
assert preds[i] == -1


def test_raises_error():
@pytest.mark.parametrize("frame_func", [pd.DataFrame, pl.DataFrame])
def test_raises_error(frame_func):
# generate random data for illustrative example
np.random.seed(42)
x = np.random.normal(0, 1, 100)
y = 1 + x + np.random.normal(0, 0.2, 100)
for i in [20, 25, 50, 80]:
y[i] += 2
X = pd.DataFrame({"x": x, "y": y})
X = frame_func({"x": x, "y": y})

with pytest.raises(ValueError):
mod = RegressionOutlierDetector(LogisticRegression(), column="y")
Expand Down
Loading