Repository navigation
[Datasets] Multi-aggregations [3/3]: Add Pandas-like multi-aggregation API. - #20090
clarkzinzow wants to merge 5 commits into
Conversation
9429d5f to
de25a6a
Compare
90f2983 to
20cfe47
Compare
72b85c0 to
9849127
Compare
9849127 to
751f9a6
Compare
5fd162e to
6f6fc33
Compare
ericl
left a comment
There was a problem hiding this comment.
@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()]})
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
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 # 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: # 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:
I'll make the following changes to show what this would look like:
|
5124723 to
a8b1c2c
Compare
a8aee4d to
8543768
Compare
8543768 to
d5bab1d
Compare
ericl
left a comment
There was a problem hiding this comment.
First pass auditing the public API
|
|
||
| @PublicAPI(stability="beta") | ||
| class AggregateFn(object): | ||
| class BoundAggregateFn: |
There was a problem hiding this comment.
Can we keep this one private?
| finalize=finalize) | ||
|
|
||
|
|
||
| Aggregation = Union[str, AggregateFn] |
There was a problem hiding this comment.
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"]]): |
There was a problem hiding this comment.
| 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.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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"], |
There was a problem hiding this comment.
Btw what happens if you do: lambda x: x["A"] + x["B"]: ["min"]? Is a reasonable column name generated for the output?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
What actually happens here though? Do you end up with a column like <anonymous lambda 0x43234>?
There was a problem hiding this comment.
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"], |
There was a problem hiding this comment.
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".
There was a problem hiding this comment.
I had proposed those semantics for a None key earlier, and we settled on removing that logic. Should I add it back?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
What use cases aren't covered now? Can we remove this?
There was a problem hiding this comment.
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")]})There was a problem hiding this comment.
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[ |
There was a problem hiding this comment.
| 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?
There was a problem hiding this comment.
I think we need the same syntax sugar in both?
There was a problem hiding this comment.
Oh I see, then it should be just dict?
There was a problem hiding this comment.
Hmm weird I thought that I updated this, I'll fix it.
|
|
||
| aggregate = agg | ||
|
|
||
| def apply_bound_aggregations(self, *aggs: BoundAggregateFn) -> Dataset[U]: |
|
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. |
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
Mean + Std with custom ddof on one column, Sum + Min + Max on another - new API
TODOs
Checks
scripts/format.shto lint the changes in this PR.