Skip to content

Classifiers may not work with arrays defining __array_function__ #14687

Closed

Description

@TomAugspurger

Description

With NEP-18, numpy functions that previously converted an array-like to an ndarray may no longer do the (implicit) conversion. dask.array recently implemented __array_function__ so np.unique(dask.array.Array) now returns a dask.array.Array.

Some more details in dask/dask-ml#541

Steps/Code to Reproduce

import dask.array as da
import dask_ml.datasets
import sklearn.linear_model

X, y = dask_ml.datasets.make_classification(chunks=50)

clf = sklearn.linear_model.LogisticRegression()
clf.fit(X, y)

Expected Results

No error, the same output as clf.fit(X.compute(), y.compute()),
or by setting the environment variable NUMPY_EXPERIMENTAL_ARRAY_FUNCTION='0'.

Actual Results

That raises

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-b0953fbb1d6e> in <module>
----> 1 clf.fit(X, y)

~/Envs/dask-dev/lib/python3.7/site-packages/sklearn/linear_model/logistic.py in fit(self, X, y, sample_weight)
   1536
   1537         multi_class = _check_multi_class(self.multi_class, solver,
-> 1538                                          len(self.classes_))
   1539
   1540         if solver == 'liblinear':

TypeError: 'float' object cannot be interpreted as an integer

This is because self.classes_ = np.unique(y) is a Dask Array with unknown length

In [2]: np.unique(da.arange(12))
Out[2]: dask.array<getitem, shape=(nan,), dtype=int64, chunksize=(nan,), chunktype=numpy.ndarray>

since Dask is lazy and doesn't know the unique elements until compute time.

Versions

System:
    python: 3.7.3 (default, Apr  5 2019, 14:56:38)  [Clang 10.0.1 (clang-1001.0.46.3)]
executable: /Users/taugspurger/Envs/dask-dev/bin/python
   machine: Darwin-18.6.0-x86_64-i386-64bit

Python deps:
       pip: 19.2.1
setuptools: 41.0.1
   sklearn: 0.21.3
     numpy: 1.18.0.dev0+5e7e74b
     scipy: 1.2.0
    Cython: 0.29.9
    pandas: 0.25.0+169.g5de4e55d6

I think this needs need NumPy>=1.17 and Dask>=2.0.0


Possible solution: Explicitly convert array-likes to concrete ndarrays where necessary (this is a bit hard to determine though). For example

self.classes_ = np.unique(y)
would be self.classes_ = np.asarray(np.unique(y)). That may not be ideal for other libraries implementing __array_function__ (like pydata/sparse).

Activity

  1. jnothman commented on Aug 20, 2019

    @jnothman
    Member
  2. amueller commented on Aug 20, 2019

    @amueller
    Member

    why isn't check_array dealing with this? hrm... I guess it's mostly an issue on y.

  3. adrinjalali commented on Aug 20, 2019

    @adrinjalali
    Member

    check_array shouldn't deal with it if we want to keep a dask array a dask array as long as we can. So it shouldn't convert it (#11447)

    I guess if we want to go down the road of supporting objects implementing __array_function__, we kinda should delay converting to a numpy arrya as long as we can, which would also help us better supporting pandas dataframes.

    We probably would need to do the np.asarray(...) once we need the actual values? Or maybe rely on len(...) instead of x.shape, would that work @TomAugspurger ?

  4. amueller commented on Aug 20, 2019

    @amueller
    Member

    I would argue we shouldn't delay conversion for now because it will get us into hell. Definitely not until we can test for this.
    To test for this, we need to have something that implements __array_function__ for all possible functions and then test that things are handled correctly.
    Maybe I'd create a class that raises an error if any __array_function__ is called at all? That should allow us to test conservatively.

  5. amueller commented on Aug 20, 2019

    @amueller
    Member

    For this concrete example: what does len return? and what should it return? what operations trigger the computation for dask?

  6. TomAugspurger commented on Aug 20, 2019

    @TomAugspurger
    ContributorAuthor

    len(dask.array.Array) will hit the same issue. We're returning nan, which python will convert to a TypeError, since len is supposed to return an int.

    Just to be clear, I'm not sure this is a case that scikit-learn should support. At least not for arbitrary estimators. For specific estimators like ColumnTransformer handling a Dask Array without unnecessarily converting to a NumPy array makes sense.

  7. amueller commented on Aug 20, 2019

    @amueller
    Member

    If StandardScaler can be lazy or on GPU I wouldn't mind, but I think making sure that nothing breaks should be the first priority.
    And I feel like len returning NaN seems to imply that dask doesn't actually implement the protocol fully, right?

    There's two options basically: convert early or convert late, and as I think I mentioned in other issues, it could become very opaque to the user which one is happening.
    In this case, it seems it tries to convert late but it fails. But I would argue it fails because dask is misbehaving and not returning the thing the numpy api asks for.

  8. TomAugspurger commented on Aug 20, 2019

    @TomAugspurger
    ContributorAuthor

    And I feel like len returning NaN seems to imply that dask doesn't actually implement the protocol fully, right?

    Do you mean the __array_function__ protocol, or Python's data model? Most of the time Dask arrays have a known shape, so len will return an int. But when you do an operation where the size of the output depends on the values of the data (like np.unique) the length is unknown.

  9. amueller commented on Aug 20, 2019

    @amueller
    Member

    I guess my thought was the __array_function__ protocol but I guess you're not even implementing Python's data model ;)

    Is there a specification of what a duck array should support? @shoyer might have thoughts?

    I guess len is not an __array_function__. np.shape is, though. What does np.shape return?

  10. amueller commented on Aug 20, 2019

    @amueller
    Member

    ok looks like np.shape also returns np.nan. Does that satisfy what implementing the __array_function__ protocol requires?

  11. shoyer commented on Aug 20, 2019

    @shoyer
    Contributor

    NumPy itself doesn't really impose any restrictions on what you can do with __array_function__. I think it would be perfectly reasonable to error when length is NaN.

    I would definitely coerce everything to NumPy arrays in check_array. As a first pass that's definitely the right thing to do. I'm a little surprised that wasn't happening already. Duck array support is something you want to add intentionally, not accidentally.

  12. amueller commented on Aug 20, 2019

    @amueller
    Member

    @shoyer well they were coerced, but apparently sometimes using numpy fuctions. So this will only be an issue on the next numpy release.

  13. shoyer commented on Aug 20, 2019

    @shoyer
    Contributor

    The next NumPy release (1.17) is already here! __array_function__ is now enabled by default.

    Unfortunately, this is indeed a breaking a change, because __array_function__ means that dask can now implements overrides of existing NumPy functions like np.unique which previously always did coercion.

  14. amueller commented on Aug 20, 2019

    @amueller
    Member

    oh but it's not available on conda? Or I'm doing something weird?

  15. shoyer commented on Aug 20, 2019

    @shoyer
    Contributor

    You can find it in the conda-forge channel.

  16. amueller commented on Aug 21, 2019

    @amueller
    Member

    #14702 should do it

  17. cmarmo commented on Apr 14, 2022

    @cmarmo
    Contributor

    @TomAugspurger , @thomasjpfan I'm closing this one as per dask-ml#541 comment.
    The original snippet of code works with the current version of scikit-learn (once dask/dask-ml#910 is applied).

  18. Repository owner moved this from Todo📬 to Done🚀 in Quansight's scikit-learn Project Boardon Apr 14, 2022
  19. TomAugspurger commented on Apr 14, 2022

    @TomAugspurger
    ContributorAuthor

    Thanks! I'll try to take a look at dask/dask-ml#910 soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions