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

Fix simple impute #788

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 2 additions & 2 deletions dask_ml/cluster/k_means.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@
)
from ..utils import _timed, _timer, check_array, row_norms

import numba # isort:skip (see https://github.com/dask/dask-ml/pull/577)

if SK_024:
from ._compat import _kmeans_plusplus
else:
from ._compat import _k_init as _kmeans_plusplus

import numba # isort:skip (see https://github.com/dask/dask-ml/pull/577)


logger = logging.getLogger(__name__)

Expand Down
12 changes: 9 additions & 3 deletions dask_ml/impute.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,18 @@ def _fit_frame(self, X):
if self.strategy == "mean":
avg = X.mean(axis=0).values
elif self.strategy == "median":
avg = X.quantile().values
avg = [np.median(X[col].dropna()) for col in X.columns]
Copy link
Member

Choose a reason for hiding this comment

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

I believe this will eagerly compute the values, thanks to np.median. Since that's done in a list comprehension, we'd end up executing the graph for X once per column. We want to delay computation till the end.

I also think this will end up pulling all the data for a column into a single ndarray, to do the median, which we also want to avoid.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

How about using delayed here?

avg = [dask.delayed(np.median(X[col].dropna())) for col in X.columns]

elif self.strategy == "constant":
avg = np.full(len(X.columns), self.fill_value)
else:
avg = [X[col].value_counts().nlargest(1).index for col in X.columns]
avg = np.concatenate(*dask.compute(avg))
avg = []
for col in X.columns:
val_counts = X[col].value_counts().reset_index()
if isinstance(X, dd.DataFrame):
x = val_counts.to_dask_array(lengths=True)
Copy link
Member

Choose a reason for hiding this comment

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

Do we need lengths here? This also triggers a computation.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is needed to compute chunk sizes ... any suggestion on how to avoid it? Thanks,

else:
x = val_counts.values
avg.append(x[(x[:, 1] == x[:, 1][0])][:, 0].min())

self.statistics_ = pd.Series(dask.compute(avg)[0], index=X.columns)

Expand Down
17 changes: 6 additions & 11 deletions tests/test_impute.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import dask_ml.datasets
import dask_ml.impute
from dask_ml._compat import DASK_2_26_0, PANDAS_1_2_0
from dask_ml.utils import assert_estimator_equal

rng = np.random.RandomState(0)
Expand Down Expand Up @@ -96,8 +95,6 @@ def test_simple_imputer_add_indicator_raises():
@pytest.mark.parametrize("daskify", [True, False])
@pytest.mark.parametrize("strategy", ["median", "most_frequent", "constant"])
def test_frame_strategies(daskify, strategy):
if strategy == "most_frequent" and PANDAS_1_2_0:
raise pytest.skip("Behavior change in pandas. Unclear.")
df = pd.DataFrame({"A": [1, 1, np.nan, np.nan, 2, 2]})
if daskify:
df = dd.from_pandas(df, 2)
Expand All @@ -109,14 +106,12 @@ def test_frame_strategies(daskify, strategy):

b = dask_ml.impute.SimpleImputer(strategy=strategy, fill_value=fill_value)
b.fit(df)
if not daskify and strategy == "median":
expected = pd.Series([1.5], index=["A"])
elif daskify and strategy == "median" and DASK_2_26_0:
# New quantile implementation in Dask
expected = pd.Series([1.0], index=["A"])
else:
expected = pd.Series([2], index=["A"])
tm.assert_series_equal(b.statistics_, expected, check_dtype=False)
c = sklearn.impute.SimpleImputer(strategy=strategy, fill_value=fill_value)
c.fit(df)

tm.assert_series_equal(
b.statistics_, pd.Series(c.statistics_, index=["A"]), check_dtype=False
)


def test_impute_most_frequent():
Expand Down