Skip to content

Add (lazy) shape property to dataframe and series - #3212

Merged
TomAugspurger merged 26 commits into
dask:masterfrom
henriqueribeiro:feature/_frame-shape
Aug 3, 2018
Merged

TomAugspurger merged 26 commits into
dask:masterfrom
henriqueribeiro:feature/_frame-shape

Conversation

@henriqueribeiro

@henriqueribeiro henriqueribeiro commented Feb 26, 2018 •

Copy link
Copy Markdown
Contributor
  • Tests added / passed
  • Passes flake8 dask
  • Fully documented, including docs/source/changelog.rst for all changes
    and one of the docs/source/*-api.rst files for new API

Since dask provides (lazy) size, and in order to get close to Pandas API, I propose an implementation of shape property, both for Dataframes and Series.

Tests Example

Imports

Details
import dask
import numpy as np
import pandas as pd
import dask.dataframe as dd

Generation Function

Details
#generate dummy df
def generate_df(size):
    d = {
        'dates':
        pd.date_range('1980-01-01', periods=size, freq='1T'),
        'signal1':
        np.random.normal(0, 0.3, size=size).cumsum() + 50,
        'signal2':
        np.random.normal(0, 0.3, size=size).cumsum() + 50,
        'signal3':
        np.random.normal(0, 0.3, size=size).cumsum() + 50,
        'fake_categorical1':
        np.random.choice(['A', 'B', 'C'], size=size),
        'fake_categorical2':
        np.random.choice(['D', 'E', 'F'], size=size)
    }

    return pd.DataFrame(d)

Generate df and convert to Dask

Details
df = generate_df(15000)
ddf = dd.from_pandas(df, npartitions=5)
ddf.divisions
(0, 3000, 6000, 9000, 12000, 14999)

Using Shape on DataFrame

Details
_shp = ddf.shape
print('Using len: ',len(ddf))
print('Using Dask shape: ',_shp.compute())
print('Using Pandas shape: ',df.shape)
Using len:  15000
Using Dask shape:  (15000, 6)
Using Pandas shape:  (15000, 6)

Get only row lenght

_shp = ddf.shape[0]
print('Dask Row lenght: ',_shp.compute())
print('Pandas Row lenght: ',df.shape[0])
Dask Row lenght:  15000
Pandas Row lenght:  15000

Using Shape on Series

Details
_shp = ddf.signal1.shape
print('Using len: ',len(ddf.signal1))
print('Using Dask shape: ',_shp.compute())
print('Using Pandas shape: ',df.signal1.shape)
Using len:  15000
Using Dask shape:  (15000,)
Using Pandas shape:  (15000,)

@mrocklin mrocklin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In general this seems sensible to me. Thanks for taking it on. I've left a couple of small comments.

Comment thread dask/dataframe/core.py Outdated
row_size = delayed(int)(self.size / col_size)
return delayed(tuple)((row_size, col_size))
else:
return delayed(tuple)((self.size,))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Given the type selection in here perhaps we should define this separately on the DataFrame and Series classes directly?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ok, I will separate it

Comment thread dask/dataframe/tests/test_dataframe.py Outdated
assert_eq(result, len(full.columns))

result = d.a.shape[0].compute()
assert_eq(result, len(full.a))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Would it work to call assert_eq directly on the delayed object like assert_eq(d.shape, full.shape)?

The assert_eq function also checks a few things on task graphs that we probably want to keep if possible

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I believe this is not possible. At least I got this message:

TypeError: Truth of Delayed objects is not supported

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

@mrocklin Please tell me if I need to change more stuff. Thanks

@mrocklin

Copy link
Copy Markdown
Member

It looks like this causes other tests to fail. I recommend clicking on the "details" link to the right of the travis-ci failure at the bottom of this PR (look for a red X). It looks like other parts of code are checking for the .shape property and calling == on it.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

@mrocklin There is some method to check if a variable is delayed or not? I cannot find it

The problem seems to be in dask/utils.py on the is_arraylike function. This function uses shape method to check if the variable is a numpy array or something similar. Then, when x.shape is called it can't convert the result into a boolean because the result is a delayed

Comment thread dask/utils.py Outdated
if isinstance(x, (dd.DataFrame, dd.Series)):
return False
else:
return (hasattr(x, '__array__') and

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There are a couple problems with this:

  1. We can't assume that dask.dataframe will import cleanly here. Dask doesn't require users be able to install dask dataframe in order to use other systems, like dask.bag or dask.array
  2. Arguably dd.Series is array like by this definition, no?

Perhaps instead .shape should return a tuple of delayed objects rather than a delayed tuple?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 on returning a tuple of delayed objects rather than a delayed tuple.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I agree with both of you and that was the first approach that I tried. The "problem" with a tuple of delayed objects is that we need to create a class dask.tuple, otherwise, tuple don't have the compute method and create it, maybe, is a bit overkill.

Somewhere on dask documentation, I saw a scratch of dask.tuple implementation. Do you know if it's usable?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The top-level dask.compute() function is probably the best way to evaluate these.

I suppose the other option is to return a 1D dask array instead of a tuple.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think we should avoid that idea in order to be coherent with Pandas API.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

...the other option is to return a 1D dask array instead of a tuple.

This could also be turned into a tuple of ints once the 1-D Dask Array is created.

@mrocklin

mrocklin commented Feb 27, 2018 via email

Copy link
Copy Markdown
Member

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

Ok, I agree. This will take a bit more time to me to dig and understand the code under the hood. I just started using Dask last week, so I'm newbie on this but I will try anyway

@mrocklin

Copy link
Copy Markdown
Member

We appreciate your effort on this @henriqueribeiro . Please let us know if you have further questions and how we can help.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

Hey @mrocklin! Finally I found some time to work on this again. On this commits, and following your suggestion, I created a Tuple class for dask. Now it's possible to have a tuple of dask objects and then call compute. In the end it turned out to be a very simple implementation but I'm not 100% sure that I'm doing it correctly.

Also, I saw that some tests are failing but I believe it's not because of the shape method or the tuple class. Can you please have a look on it? Thanks a lot

@mrocklin

Copy link
Copy Markdown
Member

I think that we should avoid creating a tuple class in Dask. While I agree that this might be useful sometimes it leads us down a path of recreating an entire language in Dask, which more than I think we want to accomplish.

Instead I recommend that we just return a normal Python tuple that contains a computable object. Perhaps something like the following?

class Series(...):
    def shape(self):
        return (self.size(),)

class DataFrame(...):
    def shape(self):
        return (self.size(), len(self.columns))

This won't have the nice df.shape.compute() semantics that your current solution has, but has the nice advantage of not increasing the scope of the project.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

I understand your point, but the problem with that approach is that then you need to iterate over each element and compute it. Still, and despite the increase of the project's scope, this class is very very simple, only adding compute and persist method to original tuple class.

@mrocklin

Copy link
Copy Markdown
Member

Still, and despite the increase of the project's scope, this class is very very simple, only adding compute and persist method to original tuple class

But now people can ask for dict, set, list and other similar classes. I am -1 on adding a tuple class. I strongly believe that it will create a non-trivial amount of maintenance burden in the future. You're quite welcome to create a Dask Tuple class, but I would prefer that it not be defined or used within the main codebase.

but the problem with that approach is that then you need to iterate over each element and compute it

Yes, I agree that this is suboptimal. People would have to use the dask.compute function instead. I believe that the usability benefit for dataframe.shape here does not balance against the maintenance costs.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

You, better than me, have a much better overview of the whole project and so, I trust on your decision. I will change to the implementation that you proposed.

Off topic: there is a list of these small things/methods that should be implemented in order to have, approximately, the same API as Pandas? I would like to continue contributing to the project and maybe these methods are the best methods to get in.

@jakirkham

jakirkham commented May 14, 2018 •

Copy link
Copy Markdown
Member

FWIW one can do dask.compute(*my_lazy_shape) to get the computed tuple. Maybe not as nice as the method, but not much more complicated.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

Do you think is it ok now?

@mrocklin

Copy link
Copy Markdown
Member

In principle I agree with the changes here. However, it looks like the tests are failing. You can see the logs by clicking on "Details" in the travis-ci section above, and then click on any of the four failing builds:

image

It looks like tests around numpy ufuncs have started to fail? I wonder if, now that we have a .shape dask dataframes/series look enough like numpy arrays to be treated differently by some other part of the ecosystem? The next thing I would do would be to try out some of the failing tests locally and investigate why they are failing:

py.test dask/dataframe/tests/test_ufunc.py --pdb --verbose

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

@mrocklin you are right. The tests are failing because now the dataframe/series have the shape method and, whereas in the past the value returned was -1 for the "shape", now it returns a delayed value.

With this, how do you think is the best way to handle it? To compute the shape and proceed or replace the delayed values and proceed?

@TomAugspurger

Copy link
Copy Markdown
Member

Apologies if this has been discussed already, but have we considered returning a tuple of (delayed_n_rows, concrete_n_columns)? We know the number of columns, so it needn't be delayed.

A common use of DataFrame.shape is getting the length of the second axis in a pandas & numpy generic way. If we have the number of columns be delayed, users will still need to check whether they have a dataframe or array.

@mrocklin

mrocklin commented Jul 23, 2018 via email

Copy link
Copy Markdown
Member

@TomAugspurger

Copy link
Copy Markdown
Member

Thanks. @henriqueribeiro do you have time to implement this soon? I have a short-term need for it.

I think something roughly like

@property
def shape(self):
    return (self.reduction(len, np.sum, token='len', meta=int, split_every=False),
            len(self.columns))
  • docs and tests should do the trick.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

Hey @TomAugspurger and @mrocklin

Yes, we had that discusssion some time ago but in the end, and in the current implmentation, the shape returns a tuple with a delayed object and a scalar, exactly as you suggested.

The only problem that I see is that some methods use the absence of shape method to check if it's dask or not (at least is my understanding). How can we overcome this?

@TomAugspurger

Copy link
Copy Markdown
Member

Sorry I should have looked closer at the implementation. On my quick skim I thought the suggestion was for both values of the tuple to be delayed.

The only problem that I see is that some methods use the absence of shape method to check if it's dask or not (at least is my understanding).

Hmm are these the test failures present in, e.g., https://travis-ci.org/dask/dask/jobs/378727207? I'll take closer look later.

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

@TomAugspurger exactly. Tell me if you need something from me

@TomAugspurger

Copy link
Copy Markdown
Member

Pushed some updates, we'll see if CI passes.

This _unkown_shape hack is pretty ugly https://github.com/dask/dask/pull/3212/files#diff-492da7893fa5fa6ad3a6ef6cdef985f2R309

That's primarily to avoid having to inspect elements of iterables in dask.array.core.elemwise at https://github.com/dask/dask/pull/3212/files#diff-0dc21516366e88095fc3dbf2e9e62f9aL3430. If any element of an iterable is delayed, we would want it's "shape" to be () for the purpose of elemwise. I'd be happy to hear suggestions on how this could be avoided.

We rely on apply_infer_dtype(op, vals, {}, 'elemwise', suggest_dtype=False) returning NotImplemented for op(dask array, dask series). Perhaps we could return that earlier if we get a dask series / dataframe?

@henriqueribeiro

Copy link
Copy Markdown
Contributor Author

We should get some input from @mrocklin

@TomAugspurger

TomAugspurger commented Jul 27, 2018 via email

Copy link
Copy Markdown
Member

@TomAugspurger

TomAugspurger commented Aug 1, 2018 •

Copy link
Copy Markdown
Member

Just pushed a commit removing the _unknow_shape hack, at the cost of having to check is_dask_collection(x) on every element of arr.shape in a few places. This is a bit more expensive, but I'm personally OK with that.

Do you have a preference @mrocklin, @shoyer, or @jakirkham?

@shoyer

shoyer commented Aug 1, 2018

Copy link
Copy Markdown
Member

This looks reasonable to me.

@TomAugspurger

Copy link
Copy Markdown
Member

Thanks. Merging tomorrow if there are no objections.

@jakirkham

Copy link
Copy Markdown
Member

Just pushed a commit removing the _unknow_shape hack, at the cost of having to check is_dask_collection(x) on every element of arr.shape in a few places.

Didn't actually know about that hack. Anyways sounds like an improvement to me.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants