Skip to content

[Datasets] Multi-aggregations [3/3]: Add Pandas-like multi-aggregation API. - #20090

Closed
clarkzinzow wants to merge 5 commits into
ray-project:masterfrom
clarkzinzow:datasets/feat/groupby-pandas-agg-api
Closed

clarkzinzow wants to merge 5 commits into
ray-project:masterfrom
clarkzinzow:datasets/feat/groupby-pandas-agg-api

Conversation

@clarkzinzow

@clarkzinzow clarkzinzow commented Nov 4, 2021 •

Copy link
Copy Markdown
Contributor

As a stacked follow-up to #20074 (only the last commit contains incremental changes from the last PR), this PR adds a Pandas-like multi-aggregation API, making it much easier to express "do this set of aggregations for this column, and a different set of aggregations for this other column".

Mean + Std with custom ddof on one column, Sum + Min + Max on another - old API

from ray.data.aggregate import Mean, Std, Sum, Min, Max

ds.aggregate(Mean("A"), Std("A", ddof=0), Sum("B"), Min("B"), Max("B"))

Mean + Std with custom ddof on one column, Sum + Min + Max on another - new API

ds.agg({"A": ["mean", Std(ddof=0)], "B": ["sum", "min", "max"]})

TODOs

  1. [Future PR] Add examples to docs. This is saved for a future PR, which will also expand the last-mile preprocessing content in the docs.

Checks

@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch from 9429d5f to de25a6a Compare November 5, 2021 01:07
@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch 2 times, most recently from 90f2983 to 20cfe47 Compare November 5, 2021 13:05
@ericl ericl removed their assignment Nov 5, 2021
@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch 2 times, most recently from 72b85c0 to 9849127 Compare November 7, 2021 02:37
Comment thread python/ray/data/dataset.py Resolved
@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch from 9849127 to 751f9a6 Compare November 10, 2021 00:06
Comment thread python/ray/data/aggregate.py Resolved
@clarkzinzow
clarkzinzow requested a review from jjyao November 10, 2021 00:25
Comment thread python/ray/data/dataset.py Resolved
@ericl ericl self-assigned this Nov 12, 2021
@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch 2 times, most recently from 5fd162e to 6f6fc33 Compare November 13, 2021 02:26
@clarkzinzow
clarkzinzow requested a review from jjyao November 13, 2021 02:37
Comment thread python/ray/data/block.py Resolved
Comment thread python/ray/data/block.py Resolved
Comment thread python/ray/data/dataset.py Resolved
Comment thread python/ray/data/aggregate.py Resolved
Comment thread python/ray/data/dataset.py Resolved
Comment thread python/ray/data/grouped_dataset.py Resolved
Comment thread python/ray/data/tests/test_dataset.py Resolved

@ericl ericl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@jjyao @clarkzinzow how about expressing the typing in a more loose way? It seems to me that trying to express bound vs unbound aggregates is just making things more confusing. Furthermore, what's valid seems to differ based on simple vs arrow block. I think just taking Aggregation = Union[str, AggregateFn] would be sufficient.

Instead, we can raise good errors (e.g., "You must specify the field to sum over (e.g., Sum("foo")) when using the list aggregate syntax.") in all the relevant cases.


class Dataset:
    def aggregate(spec: Union[List[Aggregation], Dict[str, Aggregation]])

# Simple dataset
ds.aggregate(["sum", Max(), Min(lambda x: x + 1)])

# Tabular dataset
ds.aggregate([Sum("f1"), Max("f2"), Min(lambda x: x["f1"])])
ds.aggregate({"f1": [Sum(), "min"], "f2": [Max()]})

@clarkzinzow

clarkzinzow commented Nov 15, 2021 •

Copy link
Copy Markdown
Contributor Author
class Dataset:
    def aggregate(spec: Union[List[Aggregation], Dict[str, Aggregation]])

# Simple dataset
ds.aggregate(["sum", Max(), Min(lambda x: x + 1)])

# Tabular dataset
ds.aggregate([Sum("f1"), Max("f2"), Min(lambda x: x["f1"])])
ds.aggregate({"f1": [Sum(), "min"], "f2": [Max()]})

@ericl This is essentially what we had before with the old implementation of AggregateFn, but we went away from this since Aggregation becomes a messy abstraction when the on data subsetting spec (e.g. "f1", lambda x: x["f1"]) is optional at instantiation time, and is required for some APIs (ds.aggregate([Sum("f1")])) and not for others (ds.aggregate({"f1": [Sum()]})). You end up with an Aggregation abstraction that's partially specified at instantiation and is expected to be mutated at some point before it's API can be used, which is a bad abstraction smell and resulted in a difficult to document class and a complex implementation.

It seems to me that trying to express bound vs unbound aggregates is just making things more confusing. Furthermore, what's valid seems to differ based on simple vs arrow block.

With the current design that has both bound and unbound aggregations, the user will only have to work with unbound aggregations except for multi-aggregation use cases that aren't expressible with the .agg() API, which I think are currently limited to multi-aggregations on simple datasets, since all Arrow datasets use cases should be covered:

# Single aggregation on a single column
ds.mean("A")

# Single aggregation on multiple columns
ds.mean(["A", "B"])

# Multiple aggregations on each column
ds.agg(["mean", "std"])

# Multiple customized aggregations on each column
ds.agg(["mean", Std(ddof=0)])

# Multiple customized aggregations on multiple columns
ds.agg({"A": ["mean", Std(ddof=0)], "B": ["min", "max"]})

With a very small extension, we can expand this to fully cover simple datasets by expanding the scope of the column --> aggregations mapping to allow for callable keys: Dict[AggregateOnT, List[Union[str, AggregateFn]]]. At that point, we can make .apply_aggregations() a private API (renamed to .apply_bound_aggregations()) and completely hide the bound aggregations from the user.

# Multiple customized aggregations on multiple data subsets
ds.agg({lambda x: x[0]: ["mean", Std(ddof=0)], lambda x: x[1]: ["min", "max"]})

I think this is the best of both worlds:

  1. There's a single user-facing aggregation abstraction, AggregationFn.
  2. The user-facing aggregation abstraction is dataset subsetting-agnostic, so the data model is clean with no weird partially specified + mutated state.
  3. The multi-aggregation API closely mimics the Pandas multi-aggregation API, with a clean application to simple datasets: list of aggregations applied to whole row, dict of aggregations applied to subset produced by callable key.
  4. With the aggregation-specific APIs and the multi-aggregation API, we have full expressivity for aggregations while keeping the common use cases simple.

I'll make the following changes to show what this would look like:

  1. Rename Aggregation --> BoundAggregateFn (possible marked as private API).
  2. Rename .apply_aggregations() --> .apply_bound_aggregations() (possibly marked as private API).
  3. Define .aggregate() alias for .agg() to mirror Pandas.
  4. Define and use an Aggregation = Union[str, AggregateFn] type.
  5. Expand the scope of the .agg() API to allow for callable keys in the column --> aggregations mapping: Dict[AggregateOnT, List[Aggregation]].

@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch from 5124723 to a8b1c2c Compare November 15, 2021 20:56
@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch 2 times, most recently from a8aee4d to 8543768 Compare November 15, 2021 23:07
@clarkzinzow
clarkzinzow force-pushed the datasets/feat/groupby-pandas-agg-api branch from 8543768 to d5bab1d Compare November 16, 2021 00:03

@ericl ericl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

First pass auditing the public API


@PublicAPI(stability="beta")
class AggregateFn(object):
class BoundAggregateFn:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we keep this one private?

finalize=finalize)


Aggregation = Union[str, AggregateFn]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we move this type higher in the file with a forward reference ("AggregateFn")?


def aggregate(self, *aggs: AggregateFn) -> U:
"""Aggregate the entire dataset as one group.
def agg(self, aggs: Dict[AggregateOnT, List["Aggregation"]]):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
def agg(self, aggs: Dict[AggregateOnT, List["Aggregation"]]):
def aggregate(self, aggs: Dict[AggregateOnT, List["Aggregation"]]):

I think the long form is preferable for clarity, as this isn't that common.

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.

Long-form is already added as an alias (see below this function definition), and the .agg() shorthand is the more commonly used one for Pandas users (Pandas has both .agg() and .aggregate() as well).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't think we should have both.

... {"A": x, "B": x**2} for x in range(100)])
... .agg({
... "A": ["mean", Std(ddof=0)],
... "B": ["min", "max"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Btw what happens if you do: lambda x: x["A"] + x["B"]: ["min"]? Is a reasonable column name generated for the output?

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.

The column names are best effort, pulled from the function name, so the user is expected to define a function with a sensible name if they care about the output column name.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What actually happens here though? Do you end up with a column like <anonymous lambda 0x43234>?

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.

Yes, the column name inherits the opaque lambda function name, which is why users would need to define a function with a sensible name. If this best-effort output column naming won't suffice, we'll need to give the user some way to specify the output column names in the .agg() API, something like what I indicated here: #20090 (comment)

Examples:
>>> ray.data.range(100).agg({
... lambda x: x % 3: ["min", "max"],
... lambda x: x % 2: ["mean", "std"],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could we provide a simpler example too, like "lambda x: x" in the common case? I think it would be nice to have "None" here as an alias for "lambda x: x".

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 had proposed those semantics for a None key earlier, and we settled on removing that logic. Should I add it back?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm ok with it as an alias for "identity lambda". I think this is helpful in case you want to implement a custom aggregate over the entire ArrowRow as well.

I'd push back on "expanding to all fields" though, that's pretty strange unless you're coming from pandas.

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.

So would None only be a valid key for simple datasets, and we'd throw an error if it's given for an Arrow dataset?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It can return ArrowRow for Arrow dataset (you might want to aggregate over some complex combination of columns, which would otherwise not be possible without this escape-hatch).

aggs_.append(agg_)
return aggs_

def apply_bound_aggregations(self, *aggs: BoundAggregateFn) -> U:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What use cases aren't covered now? Can we remove this?

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.

AFAIK, the only use case that isn't covered is: aggregations with custom output column names. I was planning on adding support for output column naming in .agg() in a future PR, since I'm less sure about that API.

The only API that I've found tenable for this is the 2-tuple (agg, output_column_name) aggregations API:

Aggregation = Union[str, AggregateFn]

def agg(self, aggs: Dict[AggregateOnT, List[Union[Aggregation, Tuple[Aggregation, str]]]]):
    ...

ds.agg({"A": [("mean", "A_mean"), (Std(ddof=0), "biased_stddev")]})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we should support column naming here, and remove this API in this PR. It's exposing internal implementation details / terminology.


def aggregate(self, *aggs: AggregateFn) -> Dataset[U]:
"""Implements an accumulator-based aggregation.
def agg(self, aggs: Union[Aggregation, List[Aggregation], Dict[

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
def agg(self, aggs: Union[Aggregation, List[Aggregation], Dict[
def agg(self, aggregate: Union[Aggregation, List[Aggregation], Dict[

For grouped dataset, can we just take *aggs: Aggregation?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we need the same syntax sugar in both?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Oh I see, then it should be just dict?

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.

Hmm weird I thought that I updated this, I'll fix it.


aggregate = agg

def apply_bound_aggregations(self, *aggs: BoundAggregateFn) -> Dataset[U]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove?

@clarkzinzow

Copy link
Copy Markdown
Contributor Author

After discussion offline, there are strong opinions that the Pandas API is bad and that we shouldn't add a Pandas-like multi-aggregation API, so I'm closing this PR.

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.

4 participants