Repository navigation
Conversation
Signed-off-by: Dref360 <[email protected]>
Signed-off-by: Frederic Branchaud-Charron <[email protected]>
Signed-off-by: Frederic Branchaud-Charron <[email protected]>
Signed-off-by: Frederic Branchaud-Charron <[email protected]>
| y_pred, *, | ||
| sensitive_features, | ||
| control_features: Optional = None, | ||
| ): |
There was a problem hiding this comment.
Do we want to add sample_params so as to pretty much follow the same format as constructor minus metric?
riedgar-ms
left a comment
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I will add support for more formats, but these accumulators accumulate batches and we concatenate them when needed.
|
I will add tests later this week. |
adrinjalali
left a comment
There was a problem hiding this comment.
Here's a few notes :) Thanks @Dref360
| "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." |
| If True, will modify the behavior to accept the accumulation of values before computing | ||
| the score. One can append data with ``add_data``. |
There was a problem hiding this comment.
also add a note that the user can't pass data in the constructor when streaming=True
| 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): |
There was a problem hiding this comment.
| streaming=False): | |
| streaming: bool=False): |
| 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: |
| raise ValueError(_BAD_INIT_ERROR) | ||
|
|
||
| self._y_t = None | ||
| self._y_p = None |
There was a problem hiding this comment.
we shouldn't silently ignore y_pred. Also, I think y_pred is short enough, doesn't need to be shortenned to y_p
There was a problem hiding this comment.
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
| self._s_f = sensitive_features | ||
| self._c_f = control_features |
| 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) |
There was a problem hiding this comment.
I think you can pass multiple arrays to the same function call here
Signed-off-by: Dref360 <[email protected]>
Signed-off-by: Dref360 <[email protected]>
|
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 |
|
|
||
| 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) |
There was a problem hiding this comment.
Why has the processing of the functions been moved out of the constructor?
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
I think this should be a separate test.
There was a problem hiding this comment.
And on a related point, what happens if you call .overall before calling add_data() when streaming?
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.?
There was a problem hiding this comment.
Hmm my current implementation does not support it. I'll think on how to support it.
Do we want to support this behavior?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
| @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=[], |
There was a problem hiding this comment.
Could we also have a case where some subgroups of the sensitive feature(s) are not present in the initial batch?
There was a problem hiding this comment.
And another case where there are intermixed calls to add_data() and .overall and .by_group etc.?
Signed-off-by: Dref360 <[email protected]>
|
Hello! Of course, if we want to change the design I am open to suggestions! |
riedgar-ms
left a comment
There was a problem hiding this comment.
Thanks for keeping at this!
| 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 |
There was a problem hiding this comment.
This will eventually need to get changed to a ValueError, but that can wait until we're on to the polishing stage.
| 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.") |
There was a problem hiding this comment.
Again, not vital quite yet, but could we raise a more specific exception? Although I'm not sure that ValueError is appropriate here.
There was a problem hiding this comment.
yeah not sure which Exception there is here.
Can I create my own MetricStreamingException?
There was a problem hiding this comment.
@adrinjalali would have better thoughts than I do on that.
There was a problem hiding this comment.
Isn't this a NotImplementedError?
| elif isinstance(self._s_p, list): | ||
| self._s_p.append(sample_params) | ||
| else: | ||
| raise ValueError("MetricFrame was initialized with `sample_params` already set.") |
There was a problem hiding this comment.
I don't understand this error. Aren't there two cases which should be being caught:
- User provides
sample_paramson the first call to this method, but then forgets on a subsequent call - User doesn't provide
sample_paramson the first call, but tries to on some later call
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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=[], |
There was a problem hiding this comment.
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}, |
There was a problem hiding this comment.
Shouldn't this be sample_params={'sample_weight': [] } here - the sample weights would need to be streamed as well?
|
@Dref360 did you have any questions about my review comments? Have I missed something else you've changed? |
|
Sorry about that, I'll work on the comments this week. |
No problem - we know this is volunteer work! |
riedgar-ms
left a comment
There was a problem hiding this comment.
Thank you for keeping at this!
| @@ -119,24 +133,162 @@ def __init__(self, | |||
| y_pred, *, | |||
There was a problem hiding this comment.
As a warning #822 is changing this signature slightly. There may be merge conflicts.
| 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' |
There was a problem hiding this comment.
Can this raise a ValueError too?
| @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): |
| target = metrics.MetricFrame(skm.recall_score, [], [], sensitive_features=[], | ||
| streaming=True) | ||
| # We supply CF in the call, it should fail. | ||
| with pytest.raises(ValueError): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
we really need to have that "patch" check @riedgar-ms , it'd be easier to review here then.
There was a problem hiding this comment.
Do you mean the code coverage check?
riedgar-ms
left a comment
There was a problem hiding this comment.
Tagging @adrinjalali and @MiroDudik ... @Dref360 deserves a break from my reviews :-)
adrinjalali
left a comment
There was a problem hiding this comment.
Thanks for all the work so far @Dref360 , it's certainly getting there.
| _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." |
There was a problem hiding this comment.
You could also do
_SF_DICT_CONVERSION_FAILURE = (
"DataFrame.from_dict() failed on sensitive features. "
"Please ensure each array is strictly 1-D."
)| 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 | ||
| ): |
There was a problem hiding this comment.
they should all be kwonly args I think.
| self._y_true = None | ||
| self._y_pred = None | ||
| check_consistent_length(y_true, y_pred) | ||
| y_t = _convert_to_ndarray_and_squeeze(y_true) |
There was a problem hiding this comment.
please use more explainable names, I'm not sure if we need to shorten the variable names by this much
| self._y_true = None | ||
| self._y_pred = None |
There was a problem hiding this comment.
we don't have to set these in this case. They don't need to exist in the instance.
| 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.") |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
we really need to have that "patch" check @riedgar-ms , it'd be easier to review here then.
| self._by_group = None | ||
|
|
||
| def _concat_batches(self, batches): | ||
| """Concatenate a list of items together.""" |
There was a problem hiding this comment.
please explain in the docstring what this function's supposed to do exactly, the code seems a bit not so nice here.
| 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) |
There was a problem hiding this comment.
could we please not have the very shortened version of the variable names?
| 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. |
There was a problem hiding this comment.
I'm not quite sure that this note is supposed to mean.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Isn't that always going to be required?
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
This looks like it should be a separate test.
adrinjalali
left a comment
There was a problem hiding this comment.
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.
| _BAD_INIT_ERROR = """Non streaming metrics require data to process. | ||
| Set streaming=True for streaming metrics""" |
There was a problem hiding this comment.
we should be consistent, either have newlines in all messages or none, I prefer none.
| 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: |
There was a problem hiding this comment.
| 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 |
There was a problem hiding this comment.
| y_true : List, pandas.Series, numpy.ndarray, pandas.DataFrame | |
| y_true : array-like |
?
There was a problem hiding this comment.
Doesn't sphinx complain about this since it's not technically a "type"?
There was a problem hiding this comment.
There was a problem hiding this comment.
| sensitive_features : List, pandas.Series, dict of 1d arrays, numpy.ndarray, | ||
| pandas.DataFrame |
There was a problem hiding this comment.
| sensitive_features : List, pandas.Series, dict of 1d arrays, numpy.ndarray, | |
| pandas.DataFrame | |
| sensitive_features : array-like, or dict of array-like |
?
| 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}") |
There was a problem hiding this comment.
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?
|
To @adrinjalali 's suggestion of a separate |
|
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. |
|
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! |
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:
Signed-off-by: Dref360 [email protected]