Skip to content

Improve MetricFrame performance - #985

Merged
riedgar-ms merged 72 commits into
fairlearn:mainfrom
riedgar-ms:riedgar-ms/metricframe-performance-improvements
Feb 28, 2022
Merged

riedgar-ms merged 72 commits into
fairlearn:mainfrom
riedgar-ms:riedgar-ms/metricframe-performance-improvements

Conversation

@riedgar-ms

@riedgar-ms riedgar-ms commented Oct 22, 2021 •

Copy link
Copy Markdown
Member

Rework the innards of MetricFrame to use DataFrame.groupby() to improve performance. The public API does not change, although there is a slight change to the return - the resultant DataFrames will have dtype=float64 etc. when appropriate, rather than just being object.

The FunctionContainer class has been replaced by AnnotatedMetricFunction. In addition, the GroupFeature class has been simplified, removing its dependence on LabelEncoder. These changes have obsoleted quite a few tests.

Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>

@romanlutz romanlutz 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.

I like the direction this is going! Holding off on reviewing tests since it's still WIP, but I thought I'd take a brief look at least.

args: List[str] = None,
kwargs: Dict[str, str] = None):
self._func = func
self._args = ['y_true', 'y_pred']

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.

Do we expect the args to contain these two? If so, should we check that the provided args contain them?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Evidently not obvious.... these are the positional args, so the names in this array represent the columns of the DataFrame which are going to be extracted. The names used by the function itself don't matter.

import pandas as pd


class AnnotatedMetricFunction:

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.

Since you're (potentially) adding args and kwargs I feel like "augmented" would be better than "annotated". Perhaps it's just not a very important decision, but if anyone has thoughts please respond 🙂

Comment thread fairlearn/metrics/_metric_frame.py Resolved
Comment thread fairlearn/metrics/_metric_frame.py Resolved
Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
@riedgar-ms

Copy link
Copy Markdown
Member Author

We need to discuss the two tests I've disabled. The essential problem is that both of them turn one or more of the inputs into a 2D array. When the code attempts to put this into a DataFrame as a single column, pandas notices that the array is 2D, and refuses. There's probably something we could do to work around this, but I can see it being a gnarly piece of code - for a scenario which may be better supported by having the users give us their DataFrame directly.

@riedgar-ms

Copy link
Copy Markdown
Member Author

I've been doing a few more experiments, and I'm not sure that there's a way forward which doesn't involve breaking something.

The fundamental problem appears to be that we're changing the internal representation of the data from an ndarray to a DataFrame. Some of our tests pass one of the data columns in as a multi-d ndarray, and you can't assign that to a single column of a DataFrame.

The trap is this: in some of our test cases, the data really are 2d. In others, the test passed in an array with dummy dimensions of length 1, which were removed when MetricFrame called np.squeeze().

I'm scratching my head a bit here - there are metrics such as sklearn.metrics.r2_score() which legitimately accept 2-d arrays as arguments. Thoughts welcome @romanlutz @MiroDudik @adrinjalali @hildeweerts

@riedgar-ms

Copy link
Copy Markdown
Member Author

OK, some more experimentation just completed.... sklearn.metrics.r2_score() can accept two column DataFrames as arguments. This can be made to work with the AnnotatedMetricFunction:

import functools

import numpy as np
import pandas as pd
import sklearn.metrics as skm

from fairlearn.metrics._annotated_metric_function import AnnotatedMetricFunction


def test_experimenting():
    n_elements = 100

    metric_fn = functools.partial(skm.r2_score, multioutput='raw_values')

    y_t_2 = np.random.rand(n_elements, 2)
    y_p_2 = np.random.rand(n_elements, 2)

    direct_result = metric_fn(y_t_2, y_p_2)

    all_data = np.concatenate([y_t_2, y_p_2], axis=1)
    data = pd.DataFrame(data=all_data, columns=['y_t_o1', 'y_t_o2', 'y_p_p1', 'y_p_o2'])

    amf = AnnotatedMetricFunction(func=metric_fn,
                                  args=[['y_t_o1', 'y_t_o2'], ['y_p_p1', 'y_p_o2']])

    result_from_annotated = amf.invoke(data)

    assert np.array_equal(result_from_annotated, direct_result)

I think that the least disruptive thing to do would be to add a requirement that 'all arguments to a MetricFrame shall be assignable to columns of a DataFrame.' This will break things (both some of our test cases which rely on an internal call to np.squeeze(), and this r2_score() example until we have an alternative API), but I think it will minimise the number of special cases and hacks we have to add going forward.

Since it is a breaking change, we perhaps want a new class, though....

@riedgar-ms

Copy link
Copy Markdown
Member Author

@adrinjalali could you expand on your concerns about using DataFrame? Also, is there some fast way of doing the masking with numpy, which can match DataFrame.groupby()? That's the performance bottleneck.

@adrinjalali

Copy link
Copy Markdown
Member

I don't think we have to use pd.DataFrame to improve the performance here. Based on the answers here, you can sort the array first, and then do your aggregations on the parts of data you need. Doing min/max groupby I see them being quite fast. It may not be as fast as pandas, but it's much faster than what we have I think.

For instance, to get min, you could do

def group_min(groups, data):
    # sort with major key groups, minor key data
    order = np.lexsort((data, groups))
    groups = groups[order] # this is only needed if groups is unsorted
    data = data[order]
    # construct an index which marks borders between groups
    index = np.empty(len(groups), 'bool')
    index[0] = True
    index[1:] = groups[1:] != groups[:-1]
    return data[index]

You could do a similar thing for other aggregations.

I personally don't have the data in a pandas DataFrame to feed to MetricFrame, with this change, I'd need to first construct a dataframe, just to feed it to the MetricFrame.

@riedgar-ms

Copy link
Copy Markdown
Member Author

@adrinjalali , this current change would not require the input be in DataFrame format - although it would narrow the inputs deemed suitable to 'must be assignable to DataFrame column' - this precludes passing a 2D array for y_true.

@riedgar-ms

Copy link
Copy Markdown
Member Author

Just noting that @adrinjalali also commented on the first pass at this:
#975 (comment)
For my part, I think that we do want to support metrics which don't take y_true or y_pred. Even just simple like selection_rate doesn't want both, so you wind up writing functions which completely ignore one of their arguments.

@riedgar-ms

Copy link
Copy Markdown
Member Author

Running on Python 3.7. First installing fairlearn from PyPI:

Time = 163.8702350616455+/-13.086753780340425 secs

and with the new improved innards:

Time = 1.2914242148399353+/-0.025541574801125556 secs

Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
@riedgar-ms

Copy link
Copy Markdown
Member Author

@adrinjalali , I've gone back and improved some of the documentation. However, the changes are smaller now that the user-facing API is being preserved.

@adrinjalali adrinjalali 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.

Otherwise I think it looks quite good to me! But I would appreciate if you fill out the docstrings of the methods you're touching/creating in this PR.

Comment thread fairlearn/metrics/_metric_frame.py Resolved
Comment thread fairlearn/metrics/_metric_frame.py Outdated
y_p = _convert_to_ndarray_and_squeeze(y_pred)

func_dict = self._process_functions(metrics, sample_params)
all_data['y_true'] = list(y_t)

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.

why do we convert things to an ndarray and then a list here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Because if you try assigning a 2D array to a single pandas column, it complains. However, it doesn't object to a list-of-lists.

Comment thread fairlearn/metrics/_metric_frame.py Resolved
if hasattr(func, "__name__"):
self.name = func.__name__
else:
logger.warning("Supplied 'func' had no __name__ attribute")

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.

this is not tested (hard to find what's not tested, this is why I love codecov)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Do you mean that I don't check for the log message? This branch of the if statement is covered by test_constructor_no_name()

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ping @adrinjalali I'm not sure which part you mean isn't tested.

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.

Yes, the test doesn't check that this warning is raised (I guess that means the test actually raises a warning, which it ideally shouldn't).

Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
Signed-off-by: Richard Edgar <[email protected]>
@riedgar-ms

Copy link
Copy Markdown
Member Author

@adrinjalali please could you take another look?

@adrinjalali adrinjalali added this to the V.8 milestone Feb 10, 2022
@riedgar-ms

Copy link
Copy Markdown
Member Author

Ping.... @adrinjalali , have I adequately addressed your concerns? I would really like to get this checked in.

@adrinjalali adrinjalali 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.

Otherwise this looks good to me. I think it's a positive change. I'm still not super confident with the code since I find it hard to follow in some parts, but this is making things much cleaner than before.

if hasattr(func, "__name__"):
self.name = func.__name__
else:
logger.warning("Supplied 'func' had no __name__ attribute")

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.

Yes, the test doesn't check that this warning is raised (I guess that means the test actually raises a warning, which it ideally shouldn't).

Signed-off-by: Richard Edgar <[email protected]>
@riedgar-ms

Copy link
Copy Markdown
Member Author

@adrinjalali I've adjusted the test so that the warning is checked (although I had to go through warnings.warn() rather than logging). Is there somewhere in particular you feel it would be helpful to have more documentation?

@adrinjalali adrinjalali 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.

I'm happy to have this merged as is, and do improvements in future PRs.

@riedgar-ms
riedgar-ms merged commit 504804b into fairlearn:main Feb 28, 2022
@riedgar-ms
riedgar-ms deleted the riedgar-ms/metricframe-performance-improvements branch February 28, 2022 20:54
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