Skip to content

Initial implementation of streaming metric - #670

Closed
Dref360 wants to merge 17 commits into
fairlearn:mainfrom
Dref360:streaming
Closed

Dref360 wants to merge 17 commits into
fairlearn:mainfrom
Dref360:streaming

Conversation

@Dref360

@Dref360 Dref360 commented Jan 7, 2021

Copy link
Copy Markdown
Contributor

Summary:

In #655, we propose streaming metrics so that we can use Fairlearn metrics with batches as it is common in Deep learning. The naive implementation is to simply accumulate the values before computing the metric when asked.

NOTE This is WIP, open to suggestions and I wanted some guidance to be sure I didn't miss something obvious. I will add unit tests before making it ready for review.

Related issues

Quick test:

import numpy as np
import sklearn.metrics as skm
from fairlearn.metrics import MetricFrame
classes = [0,1]
sensitive = ['a', 'b']
y_true = np.random.choice(classes, [100], replace=True)
y_pred = np.random.choice(classes, [100], replace=True)
sensitive_attrs = np.random.choice(sensitive, [100], replace=True)
met = MetricFrame(skm.recall_score, y_true=y_true, y_pred=y_pred, sensitive_features=sensitive_attrs)
met.overall


# Batched, we simulate 2 batches.
yt1,yt2 = y_true[:40], y_true[40:]
yp1,yp2 = y_pred[:40], y_pred[40:]
sa1,sa2 = sensitive_attrs[:40], sensitive_attrs[40:]


met_strt = MetricFrame(skm.recall_score, y_true=[], y_pred=[], sensitive_features=[], streaming=True)
met_strt.add_data(yt1, yp1, sensitive_features=sa1)
met_strt.add_data(yt2, yp2, sensitive_features=sa2)

# Check that it's equal.
assert met_strt.overall == met.overall

Signed-off-by: Dref360 [email protected]

Dref360 and others added 4 commits January 6, 2021 19:12
Signed-off-by: Frederic Branchaud-Charron <[email protected]>
Signed-off-by: Frederic Branchaud-Charron <[email protected]>
Signed-off-by: Frederic Branchaud-Charron <[email protected]>
Comment thread fairlearn/metrics/_metric_frame.py Outdated
y_pred, *,
sensitive_features,
control_features: Optional = None,
):

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 want to add sample_params so as to pretty much follow the same format as constructor minus metric?

@riedgar-ms riedgar-ms 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.

Could you start adding some tests, please? The sample code in the PR description is helpful, but it's much better to have something which is running in the automation.

Comment thread fairlearn/metrics/_metric_frame.py Outdated
func_dict = self._process_functions(metric, sample_params)
self._y_t.append(y_t)
self._y_p.append(y_p)
self._s_f.append(sensitive_features)

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.

Does this work when self._s_f is a dictionary? I might be getting lost as to what all of these accumulators will actually be.

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 will add support for more formats, but these accumulators accumulate batches and we concatenate them when needed.

Comment thread fairlearn/metrics/_metric_frame.py Resolved
@Dref360

Dref360 commented Jan 12, 2021

Copy link
Copy Markdown
Contributor Author

I will add tests later this week.

Comment thread fairlearn/metrics/_metric_frame.py Resolved

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

Here's a few notes :) Thanks @Dref360

Comment thread fairlearn/metrics/_metric_frame.py Outdated
"Keys in 'sample_params' do not match those in 'metric'"
_BAD_INIT_ERROR = """Non streaming metrics require data to process.
Set streaming=True for streaming metrics"""
_NON_EMPTY_INIT_STR = "Streaming metrics must be initialized with empty lists."

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.

is this also an ERROR?

Comment thread fairlearn/metrics/_metric_frame.py Outdated
Comment on lines +117 to +118
If True, will modify the behavior to accept the accumulation of values before computing
the score. One can append data with ``add_data``.

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.

also add a note that the user can't pass data in the constructor when streaming=True

Comment thread fairlearn/metrics/_metric_frame.py Outdated
control_features: Optional = None,
sample_params: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None):
sample_params: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None,
streaming=False):

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.

Suggested change
streaming=False):
streaming: bool=False):

Comment thread fairlearn/metrics/_metric_frame.py Outdated
sample_params: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None,
streaming=False):
"""Read a placeholder comment."""
if len(y_true) == 0 and not streaming:

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.

y_true may be None

Comment thread fairlearn/metrics/_metric_frame.py Resolved
Comment thread fairlearn/metrics/_metric_frame.py Outdated
raise ValueError(_BAD_INIT_ERROR)

self._y_t = None
self._y_p = None

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.

we shouldn't silently ignore y_pred. Also, I think y_pred is short enough, doesn't need to be shortenned to y_p

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.

also, there's an if/else down here assigning values to these, we don't need to initialize them, they're initialized immediately after these lines

Comment thread fairlearn/metrics/_metric_frame.py Outdated
Comment on lines +137 to +138
self._s_f = sensitive_features
self._c_f = control_features

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.

same with these attributes

Comment thread fairlearn/metrics/_metric_frame.py Outdated
if not self._streaming:
raise Exception("This MetricFrame does not support adding data.")
check_consistent_length(y_true, y_pred)
check_consistent_length(y_true, sensitive_features)

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 think you can pass multiple arrays to the same function call here

Dref360 added 2 commits January 16, 2021 15:57
Signed-off-by: Dref360 <[email protected]>
@Dref360

Dref360 commented Jan 17, 2021

Copy link
Copy Markdown
Contributor Author

I added some tests and implemented most of the comments. Thank you everyone!

As for _pandify, @MiroDudik I'm not sure how to handle "metric-wide" sample_params like average in skm.recall_score using this method. I would need some guidance.

Comment thread fairlearn/metrics/_metric_frame.py Outdated

self._overall = self._compute_overall(func_dict, y_t, y_p, cf_list)
self._by_group = self._compute_by_group(func_dict, y_t, y_p, sf_list, cf_list)
self.func_dict = self._process_functions(self.metric, s_p)

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 has the processing of the functions been moved out of the constructor?

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.

Because the process_functions is dependent on the sample_params.

target = metrics.MetricFrame(skm.recall_score, [], [], sensitive_features=[],
sample_params=None, streaming=True)

with pytest.raises(ValueError) as excinfo:

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 think this should be a separate test.

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.

And on a related point, what happens if you call .overall before calling add_data() when streaming?

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.

It will raise ValueError('No data to process.') Exception message to be reworded.

@pytest.mark.parametrize("transform_y_p", conversions_for_1d)
@pytest.mark.parametrize("transform_y_t", conversions_for_1d)
@pytest.mark.parametrize("num_batches", [1, 3, 5])
def test_basic_streaming(transform_y_t, transform_y_p, num_batches):

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.

Thanks for adding these. Could you also have a test where the batches change type each time? e.g. the first add_data() call uses a list, the next a Series, the next an ndarray etc.?

@Dref360 Dref360 Jan 26, 2021 •

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 my current implementation does not support it. I'll think on how to support it.
Do we want to support this behavior?

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 think we should

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.

Have you added these tests? I seem to be overlooking them.

assert isinstance(target.by_group, pd.Series)

# Check we have expected number of elements
assert len(target.by_group) == 2

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 that the non-streaming tests already do this sort of checking, would it be easier to just put the data into a non-streaming MetricFrame and then check for equality?

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.

Right!

@pytest.mark.parametrize("num_batches", [1, 3, 5])
def test_basic_streaming(transform_y_t, transform_y_p, num_batches):
batch_generator = batchify(num_batches, y_t, y_p, g_4)
target = metrics.MetricFrame(skm.recall_score, [], [], sensitive_features=[],

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.

Could we also have a case where some subgroups of the sensitive feature(s) are not present in the initial batch?

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.

And another case where there are intermixed calls to add_data() and .overall and .by_group etc.?

Base automatically changed from master to main February 6, 2021 06:05
@Dref360

Dref360 commented Mar 4, 2021

Copy link
Copy Markdown
Contributor Author

Hello!
Sorry for the delay.
I think I answered most questions and fixed most issues. So I would welcome a new round of review.

Of course, if we want to change the design I am open to suggestions!

@riedgar-ms riedgar-ms 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.

Thanks for keeping at this!

Comment thread fairlearn/metrics/_metric_frame.py Outdated
self._compute_metric(y_t, y_p, sensitive_features, control_features, sample_params)
else:
# If we are streaming, we wait, but initialize accumulators.
assert y_true == [] and y_pred == [] and sensitive_features == [], _NON_EMPTY_INIT_ERR

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 will eventually need to get changed to a ValueError, but that can wait until we're on to the polishing stage.

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.

done

Comment thread fairlearn/metrics/_metric_frame.py Outdated
metric function name, with the values being the string-to-array-like dictionaries.
"""
if not self._streaming:
raise Exception("This MetricFrame does not support adding data.")

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.

Again, not vital quite yet, but could we raise a more specific exception? Although I'm not sure that ValueError is appropriate here.

@Dref360 Dref360 Mar 25, 2021 •

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.

yeah not sure which Exception there is here.
Can I create my own MetricStreamingException?

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.

@adrinjalali would have better thoughts than I do on that.

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.

Isn't this a NotImplementedError?

Comment thread fairlearn/metrics/_metric_frame.py Resolved
Comment thread fairlearn/metrics/_metric_frame.py Outdated
elif isinstance(self._s_p, list):
self._s_p.append(sample_params)
else:
raise ValueError("MetricFrame was initialized with `sample_params` already set.")

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 don't understand this error. Aren't there two cases which should be being caught:

  • User provides sample_params on the first call to this method, but then forgets on a subsequent call
  • User doesn't provide sample_params on the first call, but tries to on some later call

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.

There is also the case where the user supplies sample_params at initialization. For example, to provide average='binary' to skm.f1_score. Then, the user is not allowed to supply sample_params after.

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.

Surely average='binary' isn't a sample parameter? By definition, sample parameters have a unique value for each sample - things like sample weights.

Signed-off-by: Dref360 <[email protected]>

@riedgar-ms riedgar-ms 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.

Sorry for the delay in reviewing.


batch_generator = batchify(num_batches, y_t, y_p, g_4)
# We initialize with CF
target = metrics.MetricFrame(skm.recall_score, [], [], sensitive_features=[],

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.

Can you make this 'success' case a separate test?


# Version with sample_weights supplied at the start.
target = metrics.MetricFrame(skm.recall_score, [], [], sensitive_features=[],
sample_params={'sample_weight': sample_weights},

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.

Shouldn't this be sample_params={'sample_weight': [] } here - the sample weights would need to be streamed as well?

@riedgar-ms

Copy link
Copy Markdown
Member

@Dref360 did you have any questions about my review comments? Have I missed something else you've changed?

@Dref360

Dref360 commented May 25, 2021

Copy link
Copy Markdown
Contributor Author

Sorry about that, I'll work on the comments this week.

@riedgar-ms

Copy link
Copy Markdown
Member

Sorry about that, I'll work on the comments this week.

No problem - we know this is volunteer work!

@Dref360
Dref360 marked this pull request as ready for review May 30, 2021 19:30

@riedgar-ms riedgar-ms 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.

Thank you for keeping at this!

Comment thread fairlearn/metrics/_metric_frame.py Outdated
@@ -119,24 +133,162 @@ def __init__(self,
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.

As a warning #822 is changing this signature slightly. There may be merge conflicts.

Comment thread fairlearn/metrics/_metric_frame.py Resolved
Comment thread fairlearn/metrics/_metric_frame.py Outdated
result = sum(batches, [])
elif batch_type is pd.DataFrame:
col_nums = batches[0].columns
assert all([col_nums == df.columns for df in batches]), 'Need same columns'

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.

Can this raise a ValueError too?

Comment thread fairlearn/metrics/_metric_frame.py Resolved
@pytest.mark.parametrize("transform_y_p", conversions_for_1d)
@pytest.mark.parametrize("transform_y_t", conversions_for_1d)
@pytest.mark.parametrize("num_batches", [1, 3, 5])
def test_basic_streaming(transform_y_t, transform_y_p, num_batches):

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 think we should

target = metrics.MetricFrame(skm.recall_score, [], [], sensitive_features=[],
streaming=True)
# We supply CF in the call, it should fail.
with pytest.raises(ValueError):

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.

Should there be a check on the exception message, so you can be sure that it raised on the right statement?

sample_params={'sample_weight': sw_batches})

# We forget to supply it the next time, it should raise.
with pytest.raises(ValueError):

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.

Again, a lot of things can raise a ValueError. Can you check the exception message to make sure that the 'right' one was raised?

self._overall = None
self._by_group = None

def _concat_batches(self, batches):

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 know that it's technically private, but it might be worth writing tests of this specific method. It may be easier to make sure that each branch is checked that way.

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.

we really need to have that "patch" check @riedgar-ms , it'd be easier to review here then.

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 you mean the code coverage check?

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

@riedgar-ms riedgar-ms 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.

Tagging @adrinjalali and @MiroDudik ... @Dref360 deserves a break from my reviews :-)

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

Thanks for all the work so far @Dref360 , it's certainly getting there.

Comment thread fairlearn/metrics/_metric_frame.py Outdated
Comment on lines +23 to +24
_SF_DICT_CONVERSION_FAILURE = "DataFrame.from_dict() failed on sensitive features. " \
"Please ensure each array is strictly 1-D."
"Please ensure each array is strictly 1-D."

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.

You could also do

_SF_DICT_CONVERSION_FAILURE = (
    "DataFrame.from_dict() failed on sensitive features. "
    "Please ensure each array is strictly 1-D."
)

Comment thread fairlearn/metrics/_metric_frame.py Outdated
Comment on lines +252 to +258
def add_data(self,
y_true,
y_pred, *,
sensitive_features,
control_features: Optional = None,
sample_params: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None
):

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.

they should all be kwonly args I think.

Comment thread fairlearn/metrics/_metric_frame.py Outdated
self._y_true = None
self._y_pred = None
check_consistent_length(y_true, y_pred)
y_t = _convert_to_ndarray_and_squeeze(y_true)

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.

please use more explainable names, I'm not sure if we need to shorten the variable names by this much

Comment thread fairlearn/metrics/_metric_frame.py Outdated
Comment on lines +232 to +233
self._y_true = None
self._y_pred = None

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.

we don't have to set these in this case. They don't need to exist in the instance.

Comment thread fairlearn/metrics/_metric_frame.py Outdated
metric function name, with the values being the string-to-array-like dictionaries.
"""
if not self._streaming:
raise NotImplementedError("This MetricFrame does not support adding data.")

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.

We could be more explicit on how the user can make it a streaming metric.

self._overall = None
self._by_group = None

def _concat_batches(self, batches):

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.

we really need to have that "patch" check @riedgar-ms , it'd be easier to review here then.

Comment thread fairlearn/metrics/_metric_frame.py Outdated
self._by_group = None

def _concat_batches(self, batches):
"""Concatenate a list of items together."""

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.

please explain in the docstring what this function's supposed to do exactly, the code seems a bit not so nice here.

Comment thread fairlearn/metrics/_metric_frame.py Resolved
Comment thread fairlearn/metrics/_metric_frame.py Outdated
def _compute_metric(self, y_t, y_p, s_f, c_f, s_p):
# Now, prepare the sensitive features
sf_list = self._process_features("sensitive_feature_", sensitive_features, y_t)
sf_list = self._process_features("sensitive_feature_", s_f, 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.

could we please not have the very shortened version of the variable names?

Comment thread fairlearn/metrics/_metric_frame.py Outdated
the score. One can append data with ``add_data``. The user can't supply data in the
constructor if ``streaming=True``.

**Note** currently, it only stores the values before computing the metric.

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 not quite sure that this note is supposed to mean.

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.

In #655, we mentioned that in the future we would like to support object that have an "update function. Like Keras Stateful Metrics or BaaL Metrics.

In this PR, we simply accumulate the predictions and we run the metrics on all values.

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.

Isn't that always going to be required?

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.

Yeah I guess, unless we have multiple metrics object at the same time for each combination of sensitive attribute.

I'll remove for now and we can decide what to do later.

Comment thread fairlearn/metrics/_metric_frame.py Outdated
accumulators = [y_true, y_pred, sensitive_features]
# CF must be None or an empty list.
cf_validated = control_features is None or len(control_features) == 0
# Same for SP

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.

Nit: can we write out 'SP' and 'CF' in the comment at least.

assert target._overall is None # has been reset
assert target._by_group is None # has been reset

# We can recompute it with the new batches.

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.

You mean that invoking by_group implicitly recomputes?

assert target._by_group is None

# We can't initialize streaming metrics with data
with pytest.raises(ValueError) as excinfo:

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 looks like it should be a separate test.

@riedgar-ms riedgar-ms 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.

Thank you for the update!

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

Thanks for all the work so far @Dref360

One general concern I have is that this is touching a lot of the MetricFrame. The question is, do we want it to be the same class, or rather have a StreamingMetricFrame where everything is just assumed to be streamed? We can share the common code in a common parent class.

We should also add this to our user guides.

Comment on lines +32 to +33
_BAD_INIT_ERROR = """Non streaming metrics require data to process.
Set streaming=True for streaming metrics"""

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.

we should be consistent, either have newlines in all messages or none, I prefer none.

Comment thread fairlearn/metrics/_metric_frame.py Resolved
cf_validated = control_features is None or len(control_features) == 0
# Same for sample_params
sp_validator = sample_params in (None, {})
if any(acc != [] for acc in accumulators) or not cf_validated or not sp_validator:

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.

Suggested change
if any(acc != [] for acc in accumulators) or not cf_validated or not sp_validator:
if any(acc for acc in accumulators) or not cf_validated or not sp_validator:


Parameters
----------
y_true : List, pandas.Series, numpy.ndarray, pandas.DataFrame

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.

Suggested change
y_true : List, pandas.Series, numpy.ndarray, pandas.DataFrame
y_true : array-like

?

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.

Doesn't sphinx complain about this since it's not technically a "type"?

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.

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.

Comment on lines +263 to +264
sensitive_features : List, pandas.Series, dict of 1d arrays, numpy.ndarray,
pandas.DataFrame

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.

Suggested change
sensitive_features : List, pandas.Series, dict of 1d arrays, numpy.ndarray,
pandas.DataFrame
sensitive_features : array-like, or dict of array-like

?

Comment on lines +340 to +359
if batch_type is np.ndarray:
result = np.concatenate(batches)
elif batch_type is list:
result = sum(batches, [])
elif batch_type is pd.Series:
result = pd.concat(batches)
elif batch_type is pd.DataFrame:
# To concat dataframe, we check if the columns match.
col_nums = batches[0].columns
if any([col_nums != df.columns for df in batches]):
raise ValueError(f"Column mismatch expected {col_nums},"
f" got {[df.columns for df in batches]}")
result = pd.concat(batches)
elif batch_type is dict:
# Create a new dict that merges values of all keys.
all_keys = set(sum((list(b.keys()) for b in batches), []))
return {k: self._concat_batches([b[k] for b in batches if k in b])
for k in all_keys}
else:
raise ValueError(f"Can't concatenate {batches}")

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 think I'd be happier if we just convert everything to numpy arrays and concatenate them instead of all these different cases. Do we need them to stay the same type?

@riedgar-ms

Copy link
Copy Markdown
Member

To @adrinjalali 's suggestion of a separate StreamingMetricFrame (and implicitly a BaseMetricFrame class, which only has protected methods for doing the calculations).... I'm not averse, although I think we did discuss that way back when we started talking about this. I can't remember if there was a particular reason for not going that route, beyond wanting to minimise the number of classes which Fairlearn introduces.

@adrinjalali

Copy link
Copy Markdown
Member

Maybe with a bit of refactoring I'd be happier with having only one class, but right now reviewing the PR gives me the impression that it's not very maintainable.

@Dref360

Dref360 commented Aug 22, 2021

Copy link
Copy Markdown
Contributor Author

I agree that simply making a wrapper class around MetricFrame would be easier, so I'll close this PR and open another later with a new implementation.

Thank you for your reviews!

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