You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
MetricFrame should support metrics that don't require y_true and y_pred #756
Right now MetricFrame only works with metrics with the signature metric(y_true, y_pred), but its disaggregation functionality should be much more broadly applicable. Two use cases of interest:
Dataset-only metrics or prediction-only metrics. These are the metrics of the form metric(y_true) and metric(y_pred). While in principle these could be handled by the current API, it's a bit confusing.
Metrics for settings beyond classification / regression. For example, to evaluate a contextual bandit algorithm, the metrics have the signature metric(actions, rewards, propensities). This use case comes up in settings with partial observations, e.g., in lending: we only observe whether the person repays a loan (reward) for the specific loan type we provide (action), including "no loan".
I think regardless of how the API is tweaked, there's an obvious first step. And then hopefully a not-too-controversial second step.
Step 1: Make MetricFrame arguments keyword-only
The suggestion is to change the current API, which is this:
So all arguments would be keyword-only and metric would become metrics (for consistency with other arguments and with columns in pandas). The functionality wouldn't change.
Step 2: Allow flexible names of shared sample parameters
The idea is that any of the shared_sample_params are passed on to all metrics, whereas sample_params is (as before) a dictionary. With the new signature, it would still be possible to write things like
We definitely should be figuring out how to offer metrics for other scenarios. However, I'm a little concerned about a few points. Doing (1) is going to break all existing code. Now, while we hardly have the usage of sklearn (say), that's still not a good thing to do. And I think that doing (2) sort of does the opposite - once you've accepted **kwargs, you can't add any more arguments of your own, since you might clash with something a user has.
For (2), we could add a shared_sample_paramsdictionary and explode it when we invoke the metric functions.
For the rest, would it be wiser to say "MetricFrame is for tabular data; we also offer X, Y, Z ....."
If we want to implement (1), we would not break everything right away. We would start off by issuing deprecation warnings. Would that work, @riedgar-ms@romanlutz@hildeweerts@adrinjalali ?
I just think that our current API is really limiting us, so I'd rather fix this sooner rather than commit to the future of docs that describe all kinds of workarounds.
I want to hold off discussing (2), because I acknowledge that there are a variety of considerations... I think that we have several options there. It would be a non-breaking change, so there's less urgency than with (1), which, if we decide to go that route, would be nice to accomplish before SciPy tutorial (at least the version where we have a new format, and issue warnings if somebody is using the old format).
I am generally not opposed to Step 1 (although I don't really see the need for changing metric into metrics).
When we get to Step 2 things get a bit tricky IMO. I am afraid that trying to fit all different kinds of learning tasks into one MetricFrame will become extremely confusing for novice users. An alternative might be to leave MetricFrame as is and create a new data structure for other types of tasks (e.g., differentiate between things like SupervisedMetricFrame, UnsupervisedMetricFrame, ReinforcementMetricFrame).
Re. metric -> metrics--the rationale is that we have sensitive_features and control_features. I've also noticed that in the tutorials I keep writing things like:
So it seems that metrics is the more appropriate name--it makes no sense to change the name in isolation, but if we decide to implement (1), then it would be an opportunity to change this as well.
@riedgar-ms : the transitional API (i.e., for the purposes of deprecating the old API) would be something like: MetricFrame(*args, metrics, y_true, y_pred, sensitive_features, control_features, sample_params)
I'm not terribly opinionated on this issue, but if we move to something like MetricFrame(*, metrics, sensitive_features, control_features, sample_params, **shared_sample_params) then we better have extremely good documentation. Reading this in an API documentation I would have no clue what to do with that. In contrast, the current signature is very intuitive to me. Obviously that can be fixed with a couple of nice examples right in the API doc and updating the user guide, but I want to make sure this is on our radar (i.e., no code PR without updating the docs).
I would also suggest providing a few examples of what that would look like if we have different kinds of metrics (e.g. accuracy needs y_true and y_pred, selection rate doesn't need a second set of ys) in the same set of metrics passed in.
Finally, I'm wondering whether the right thing to do here would be to add a warning that MetricFrame will have keyword-only args starting with the next version so people should adjust their scripts. [If so, we should make the switch to metrics instead of metric right away, otherwise it breaks people again.]
This would support the current behavior when 1-3 positional arguments are provided, but in those cases it would give a warning that this calling format is being deprecated.
I think that there are a few different things going on here, and I'd like to separate the different threads.
Firstly, I think that the idea behind shared_sample_params is a good one. Indeed, I considered putting something like that in last autumn when I was writing MetricFrame. I didn't because it wasn't a 'must have' feature. However, as I said above, I think it should be a Dict[str,vector] and not **kwargs. Going with the latter makes it harder for us to add any other named arguments of our own (since whatever name we pick, we're bound to break someone) at a later date. We 'explode' the Dict when the metric functions themselves are invoked.
Secondly, I certainly don't think that MetricFrame is the last word on these sort of metrics. Indeed, I'm sure that areas like text or vision may well need similar but different functionality (I don't know enough about them to say). But like @hildeweerts , I think that it may well be better to take each by itself, and figure out what works best for that domain, rather than trying to shoehorn them into MetricFrame.
I can see the logic in renaming the metric argument to metrics (it is a potential break, but only if people are naming their arguments). I'm not sure I understand the motivation behind forcing named arguments. I think that would make the interface much less skearn-like.
@riedgar-ms : one of the reason to have keyword-only parameters is so that you can skip them when they're not needed. For example, if we went with the signature:
Re. shared_sample_params, I think that **shared_sample_params would make the pattern more similar to what we do right now with y_true and y_pred. We could take advantage of inspect.signature() and throw a warning if there's a conflict. In those rare cases, the users could use sample_params as a workaround.
But I also don't mind if y_true=None and y_pred=None are grandfathered in and anything else needs to be provided via an actual dictionary shared_sample_params rather than **shared_sample_params.
@riedgar-ms : one of the reason to have keyword-only parameters is so that you can skip them when they're not needed. For example, if we went with the signature:
Then it would be okay to drop y_true and y_pred and provide all the metric parameters via sample_params.
If the use case is "we can drop the current parameters, and have a different set of parameters instead" then we should probably be creating a new class to handle the second set of parameters. Right now, I feel that MetricFrame does the fairly simple task of taking an sklearn-style (y_true, y_pred) metric, and turning it into one with grouping (via the sensitive features). I'd prefer to keep it that way, and work out the best API for a new use case from a clean sheet.
It may be that there is a more general API hiding within, and that we end up changing MetricFrame to wrap (or subclass) that. But I think it would still be better to keep the existing MetricFrame API around, doing its simple job.
I feel like this discussion could benefit from some concrete examples. Like @riedgar-ms (and @hildeweerts I think) I'm currently struggling to see the benefit of complicating the currently very intuitive API, but perhaps with 3-5 examples of what this would look like for actual metrics (say, one of the existing ones we support, and then whichever new ones we might be able to accommodate through this) we might see the benefits (?)
It may be that there is a more general API hiding within, and that we end up changing MetricFrame to wrap (or subclass) that. But I think it would still be better to keep the existing MetricFrame API around, doing its simple job.
I was thinking the same!
I think the majority of users will be looking for classification/regression metrics and may not even be familiar with reinforcement learning. Having to look at examples to understand how to use an API even in the 'simplest' scenario, signals that it is not intuitive.
I like @romanlutz idea of writing out some examples!
@hildeweerts coming back to the API, though, are there metrics which would accept three parameters - labels, labels_true and labels_pred ? It sounds like the answer is that there aren't, but I'd like to make sure I'm understanding things correctly.
@hildeweerts coming back to the API, though, are there metrics which would accept three parameters - labels, labels_true and labels_pred ? It sounds like the answer is that there aren't, but I'd like to make sure I'm understanding things correctly.
You're right, there aren't. So that's a similar issue as metrics that don't use y_true (only y_pred) or that use y_score instead of y_pred.
Note: MetricFrame requires y_pred (clf.predict). However, ROC curves and AUC scores are generated using y_score (clf.predict_proba). This method substitutes y_score (type:float) for y_pred (type:int) to conform to the MetricFrame required params.
The argument is obviously called y_true but its type is certainly not required to be int.
Yes. It's a nomenclature issue. When I see y_pred I think it's the predicted labels. In fact, MetricFrame also allows you to pass other things in its place. Yes, it works. It's just not clear for the user.
And, in fact, all I needed to do was split the data by sensitive feature. I strongly feel like that should be a class/module on its own. Then you can use it in combination or with custom classes to compute metrics.
I totally agree with @riedgar-ms but would frame it a little differently:
We've got two things going on here:
Where we have a precomputed metric where we just need to slice it up by the sensitive features
Where there are multiple 'columns' in y_pred and/or y_true
Another way to think about it is we have two tasks to perform:
a) splitting the data by sensitive feature (universally needed and MetricFrame currently has a great approach)
b) passing split data to various metrics.
I think Fairlearn will be easier to maintain if we don't have to worry about how the data should be split and how it should be passed to a given metric in a single module/class. I suggest we just offer a class/module for splitting the data. And then worry about applying metrics to the split data in separate modules, which may import/depend on the module that splits the data such that we always handle that consistently. I feel the current module is trying to do too much in one class.
Yes. It's a nomenclature issue. When I see y_pred I think it's the predicted labels. In fact, MetricFrame also allows you to pass other things in its place. Yes, it works. It's just not clear for the user.
I'm not really sure about how best to cope with that. One solution (which would of course break everything) would be to have our own names for the inputs - say from_data and from_model which should avoid the problem of existing conventions. There's then the question of how to route them to the underlying metric function. Currently we do that positionally - first argument is the 'true' column, the second is the 'predicted' column. Now since @MiroDudik 's recent PR moved MetricFrame itself in the direction of keyword-only arguments, one could criticise this as inconsistent too. But having to match arbitrary argument names to MetricFrame to arbitrary argument names in the underlying functions is... not going to be trivial or unconfusing.
It's quite a long conversation here, could you maybe summarize what we've got so far here, for the rest of us to be able to understand the conversation?
I think that we've got a few things going on here:
It seems that when users see y_true and y_pred they may think that MetricFrame only works for classification metrics, rather than more generally (really, they are column_from_data and column_from_model and even that meaning is only really imposed by the underlying metric function)
Sometimes the two 'columns' might actually need to be multiple columns
Some metrics only take one of these (e.g. selection_rate()) and users might not want to write a wrapper for this
@kstohr has also suggested that the 'split up by sensitive and conditional features' part of MetricFrame may well work better as a separate piece of functionality.
My reason for spitting out the group_by sensitive feature function is so that it can be used for descriptive stats and exploration. If you are running a metric and you are getting an error, it may be because a class is underrepresented, not represented at all, or is 'all true.' In these cases, we may need to know which class is impacted in order to handle it. In addition, it is quite common to inspect the data you are working with before passing it to a metric.
Note: It is ok, even preferred, if it is still a method in the class. My issue is that when you instantiate the class, it currently forces you to run a metric. It would be great to be able to perform the group_by function independently of running the metric.
This is a second attempt to summarise the discussion to date, with the goal of reaching a conclusion. The previous summary was overly summarised.
Current Status
As proposed at the the beginning of the thread, we are in the process of moving to requiring named arguments for MetricFrame. We have just released v0.7.0 which issues a warning if positional arguments are used; with v0.8.0 we plan to make named arguments mandatory. At that point, the signature of MetricFrame should be:
Note that the metric functions themselves are dispatched using positional arguments - the basic signature is assumed to be metric_fn(y_true, y_pred). Now that we are requiring named arguments, this is an inconsistency.
Functionality Gaps
The feedback above (and from other sources) has highlighted several gaps in the functionality of MetricFrame. Specifically:
Some metrics don't take y_pred but y_score instead (often y_pred implies a label from a classification)
Some metrics take more than two arguments, e.g. inverse_propensity_score(*, actions_taken, rewards, propensities, actions_target)
We may have a precomputed metric (such as word error rate) and we just need it aggregated
Some metrics only need one argument (such as selection_rate for which we have a custom function which ignores the y_true argument)
A user may have multiple models which they wish to compare in a single MetricFrame
There are actually work arounds for all of these using the existing MetricFrame. These generally involve some combination of custom metric functions, making y_true and/or y_pred into a list of dictionaries, and filling extra arguments out via sample_params. The question is whether we can make the process easier.
A note on precomputed metrics
In the above, one proposed solution for the precomputed metric problem was to have a static factory method MetricFrame.from_precomputed(). However, I don't think this is needed - the precomputed metrics are still per-sample, and need to be aggregated somehow. The aggregation function (such as mean() or min() is then the 'metric'. We should make sure this is documented, though.
Proposed solutions
There are two basic ways to provide other columns - as **kwargs or a separate dictionary. In the following, we assume that the existing y_true and y_pred arguments get folded in eventually , although there would have to be intermediate releases (similar to the switch to named arguments).
Providing **kwargs
In this case, the signature of MetricFrame would become
However, **kwargs has the downside that, it is hard to add other required arguments in future, since we can be sure that whatever name we pick, we will break someone. Personally, I also think it makes documentation more difficult to read.
Providing a dictionary
Rather than provide individual arguments, we can have a direct_sample_params dictionary. The signature would then be:
(or similarly for the non-**kwargs option) and expect things to Just Work.
There are two problems with using reflection in this way. First, consider the example of a precomputed metric such as word_error_rate. We might want to use numpy.mean() as the aggregator.... but the argument for that is called a and not word_error_rate. Users would still have to write a wrapper function to make the names match.
Secondly, using reflection like this opens up a huge trap - a typo in the argument name can cause really subtle problems. If the metric function considers an argument to be mandatory (likely for something like y_true or y_score), then an error will be thrown. However, for an optional argument (think sample_weight vs sample_weights if a user were trying to pass the weights to every metric, rather than using sample_params) then the typo will simply stop the argument being passed, which might not be noticed for a long time (ask me about the value of IMPLICIT NONE and why zero initialisation is a travesty).
Working with Streaming
PR #670 is working to add streaming to MetricFrame. I think that all of the above should be compatible with that, but we should keep it in mind.
Note that the metric functions themselves are dispatched using positional arguments - the basic signature is assumed to be metric_fn(y_true, y_pred). Now that we are requiring named arguments, this is an inconsistency.
I personally don't mind this inconsistency.
As for the rest of the proposal, I find it way too complicated, and not very user friendly, and hard to explain to users.
I would rather settle for a middle ground where we leave MetricFrame unchanged, and have a DatasetMetricFrame which accepts only one y. An API which supports all possible cases is an overly complicated one which is designed to handle 100% of the cases, we could settle for 95% and have a much simpler API, and have the other 5% use-cases do the appropriate workarounds.
We should of course accept extra input required by the metric. For example, in the case of inverse_propensity_score, if I understand correctly, we can have something like:
to get a scorer. Note that this has removed the need for us to do any introspection, but we have a scorer object which is a callable but also has a state.
An alternative here, since we don't actually do slicing to re-call a scorer, is to have an object which only accepts precomputed scores, like
and then pass my_metric_fn to FlexibleMetricFrame (or whatever we call it... I'm not a huge fan of that name). This object would provide the get_metadata_request() method which is mentioned in SLEP006, and which FlexibleMetricFrame could then use to route the arguments. So the user's invocation would be something like:
Since recall_score won't have get_metadata_request() it will only be passed y_true and y_pred (positionally). In contrast, my_metric_fn will respond that it wants rewards and propensities as well, and be passed them. We avoid the 'hole' of dropped arguments due to spelling errors because make_scorer() can check that its score_params all appear in the signature of the underlying function, and similarly FlexibleMetricFrame can check its **kwargs list against the results of get_metadata_request().
Presumably, FlexibleMetricFrame (or its improved cognomen) would not accept the sample_params= dictionaries of MetricFrame because that would be taken care of through get_metadata_request() ?
So what I was trying to say, is that handling the metadata routing is really not that easy, and most APIs we've tried to design are messy. The API in sklearn applies to scorers i.e. scorer(estimator, X, y), rather than scoring functions i.e. score(y_true, y_pred). Adding get_metadata_request() is certainly a way forward, but it's not an easy one.
Alternatively, we could let AlternativeMetricFrame to accept a scorer instead of scoring functions, and then it will be exactly in the scope of SLEP006, which would make things much easier.
We could also accept a scorer instead of the scoring method, but the user would also need to pass the estimator. I kinda would prefer that if we're gonna do routing.
I don't have a lot to add to this discussion, but I agree that leaving MetricFrame as is and adding an alternative more flexible version would be preferable.
pinging @fairlearn/fairlearn-maintainers to move the discussion forward
Activity
MiroDudik commentedon Apr 22, 2021
Resolving this issue would also enable #676 .
riedgar-ms commentedon Apr 30, 2021
We definitely should be figuring out how to offer metrics for other scenarios. However, I'm a little concerned about a few points. Doing (1) is going to break all existing code. Now, while we hardly have the usage of
sklearn(say), that's still not a good thing to do. And I think that doing (2) sort of does the opposite - once you've accepted**kwargs, you can't add any more arguments of your own, since you might clash with something a user has.For (2), we could add a
shared_sample_paramsdictionary and explode it when we invoke the metric functions.For the rest, would it be wiser to say "
MetricFrameis for tabular data; we also offer X, Y, Z ....."MiroDudik commentedon May 3, 2021
If we want to implement (1), we would not break everything right away. We would start off by issuing deprecation warnings. Would that work, @riedgar-ms @romanlutz @hildeweerts @adrinjalali ?
I just think that our current API is really limiting us, so I'd rather fix this sooner rather than commit to the future of docs that describe all kinds of workarounds.
I want to hold off discussing (2), because I acknowledge that there are a variety of considerations... I think that we have several options there. It would be a non-breaking change, so there's less urgency than with (1), which, if we decide to go that route, would be nice to accomplish before SciPy tutorial (at least the version where we have a new format, and issue warnings if somebody is using the old format).
riedgar-ms commentedon May 3, 2021
Is there a way of detecting whether an argument was passed by position rather than by keyword?
hildeweerts commentedon May 3, 2021
I am generally not opposed to Step 1 (although I don't really see the need for changing
metricintometrics).When we get to Step 2 things get a bit tricky IMO. I am afraid that trying to fit all different kinds of learning tasks into one
MetricFramewill become extremely confusing for novice users. An alternative might be to leaveMetricFrameas is and create a new data structure for other types of tasks (e.g., differentiate between things likeSupervisedMetricFrame,UnsupervisedMetricFrame,ReinforcementMetricFrame).MiroDudik commentedon May 3, 2021
Re.
metric->metrics--the rationale is that we havesensitive_featuresandcontrol_features. I've also noticed that in the tutorials I keep writing things like:So it seems that
metricsis the more appropriate name--it makes no sense to change the name in isolation, but if we decide to implement (1), then it would be an opportunity to change this as well.@riedgar-ms : the transitional API (i.e., for the purposes of deprecating the old API) would be something like:
MetricFrame(*args, metrics, y_true, y_pred, sensitive_features, control_features, sample_params)romanlutz commentedon May 3, 2021
I'm not terribly opinionated on this issue, but if we move to something like
MetricFrame(*, metrics, sensitive_features, control_features, sample_params, **shared_sample_params)then we better have extremely good documentation. Reading this in an API documentation I would have no clue what to do with that. In contrast, the current signature is very intuitive to me. Obviously that can be fixed with a couple of nice examples right in the API doc and updating the user guide, but I want to make sure this is on our radar (i.e., no code PR without updating the docs).I would also suggest providing a few examples of what that would look like if we have different kinds of metrics (e.g. accuracy needs
y_trueandy_pred, selection rate doesn't need a second set ofys) in the same set ofmetricspassed in.Finally, I'm wondering whether the right thing to do here would be to add a warning that
MetricFramewill have keyword-only args starting with the next version so people should adjust their scripts. [If so, we should make the switch tometricsinstead ofmetricright away, otherwise it breaks people again.]MiroDudik commentedon May 3, 2021
@romanlutz -- i agree than step (2) requires some care, but what do you think about carrying out step (1), with the intermediate API of the form:
This would support the current behavior when 1-3 positional arguments are provided, but in those cases it would give a warning that this calling format is being deprecated.
riedgar-ms commentedon May 3, 2021
I think that there are a few different things going on here, and I'd like to separate the different threads.
Firstly, I think that the idea behind
shared_sample_paramsis a good one. Indeed, I considered putting something like that in last autumn when I was writingMetricFrame. I didn't because it wasn't a 'must have' feature. However, as I said above, I think it should be aDict[str,vector]and not**kwargs. Going with the latter makes it harder for us to add any other named arguments of our own (since whatever name we pick, we're bound to break someone) at a later date. We 'explode' theDictwhen the metric functions themselves are invoked.Secondly, I certainly don't think that
MetricFrameis the last word on these sort of metrics. Indeed, I'm sure that areas like text or vision may well need similar but different functionality (I don't know enough about them to say). But like @hildeweerts , I think that it may well be better to take each by itself, and figure out what works best for that domain, rather than trying to shoehorn them intoMetricFrame.I can see the logic in renaming the
metricargument tometrics(it is a potential break, but only if people are naming their arguments). I'm not sure I understand the motivation behind forcing named arguments. I think that would make the interface much lessskearn-like.MiroDudik commentedon May 3, 2021
@riedgar-ms : one of the reason to have keyword-only parameters is so that you can skip them when they're not needed. For example, if we went with the signature:
Then it would be okay to drop
y_trueandy_predand provide all the metric parameters viasample_params.MiroDudik commentedon May 3, 2021
Re.
shared_sample_params, I think that**shared_sample_paramswould make the pattern more similar to what we do right now withy_trueandy_pred. We could take advantage ofinspect.signature()and throw a warning if there's a conflict. In those rare cases, the users could usesample_paramsas a workaround.But I also don't mind if
y_true=Noneandy_pred=Noneare grandfathered in and anything else needs to be provided via an actual dictionaryshared_sample_paramsrather than**shared_sample_params.riedgar-ms commentedon May 4, 2021
If the use case is "we can drop the current parameters, and have a different set of parameters instead" then we should probably be creating a new class to handle the second set of parameters. Right now, I feel that
MetricFramedoes the fairly simple task of taking ansklearn-style(y_true, y_pred)metric, and turning it into one with grouping (via the sensitive features). I'd prefer to keep it that way, and work out the best API for a new use case from a clean sheet.It may be that there is a more general API hiding within, and that we end up changing
MetricFrameto wrap (or subclass) that. But I think it would still be better to keep the existingMetricFrameAPI around, doing its simple job.romanlutz commentedon May 4, 2021
I feel like this discussion could benefit from some concrete examples. Like @riedgar-ms (and @hildeweerts I think) I'm currently struggling to see the benefit of complicating the currently very intuitive API, but perhaps with 3-5 examples of what this would look like for actual metrics (say, one of the existing ones we support, and then whichever new ones we might be able to accommodate through this) we might see the benefits (?)
hildeweerts commentedon May 4, 2021
I was thinking the same!
I think the majority of users will be looking for classification/regression metrics and may not even be familiar with reinforcement learning. Having to look at examples to understand how to use an API even in the 'simplest' scenario, signals that it is not intuitive.
I like @romanlutz idea of writing out some examples!
45 remaining items
riedgar-ms commentedon Jun 18, 2021
@hildeweerts coming back to the API, though, are there metrics which would accept three parameters -
labels,labels_trueandlabels_pred? It sounds like the answer is that there aren't, but I'd like to make sure I'm understanding things correctly.hildeweerts commentedon Jun 18, 2021
You're right, there aren't. So that's a similar issue as metrics that don't use
y_true(onlyy_pred) or that usey_scoreinstead ofy_pred.kstohr commentedon Jun 18, 2021
@riedgar-ms
Yes. It's a nomenclature issue. When I see
y_predI think it's the predicted labels. In fact, MetricFrame also allows you to pass other things in its place. Yes, it works. It's just not clear for the user.And, in fact, all I needed to do was split the data by sensitive feature. I strongly feel like that should be a class/module on its own. Then you can use it in combination or with custom classes to compute metrics.
I totally agree with @riedgar-ms but would frame it a little differently:
Another way to think about it is we have two tasks to perform:
a) splitting the data by sensitive feature (universally needed and MetricFrame currently has a great approach)
b) passing split data to various metrics.
I think Fairlearn will be easier to maintain if we don't have to worry about how the data should be split and how it should be passed to a given metric in a single module/class. I suggest we just offer a class/module for splitting the data. And then worry about applying metrics to the split data in separate modules, which may import/depend on the module that splits the data such that we always handle that consistently. I feel the current module is trying to do too much in one class.
riedgar-ms commentedon Jun 21, 2021
I'm not really sure about how best to cope with that. One solution (which would of course break everything) would be to have our own names for the inputs - say
from_dataandfrom_modelwhich should avoid the problem of existing conventions. There's then the question of how to route them to the underlying metric function. Currently we do that positionally - first argument is the 'true' column, the second is the 'predicted' column. Now since @MiroDudik 's recent PR movedMetricFrameitself in the direction of keyword-only arguments, one could criticise this as inconsistent too. But having to match arbitrary argument names toMetricFrameto arbitrary argument names in the underlying functions is... not going to be trivial or unconfusing.hildeweerts commentedon Jun 22, 2021
I think this is an important discussion and I'd love to hear thoughts from other @fairlearn/fairlearn-maintainers as well here!
adrinjalali commentedon Jun 22, 2021
It's quite a long conversation here, could you maybe summarize what we've got so far here, for the rest of us to be able to understand the conversation?
riedgar-ms commentedon Jun 22, 2021
Summary
Per @adrinjalali 's request :-)
I think that we've got a few things going on here:
y_trueandy_predthey may think thatMetricFrameonly works for classification metrics, rather than more generally (really, they arecolumn_from_dataandcolumn_from_modeland even that meaning is only really imposed by the underlying metric function)selection_rate()) and users might not want to write a wrapper for this@kstohr has also suggested that the 'split up by sensitive and conditional features' part of
MetricFramemay well work better as a separate piece of functionality.riedgar-ms commentedon Jun 28, 2021
Pinging..... @adrinjalali @hildeweerts @MiroDudik @michaelamoako @kstohr
kstohr commentedon Jun 28, 2021
@riedgar-ms Yep. That sums it up.
My reason for spitting out the
group_bysensitive feature function is so that it can be used for descriptive stats and exploration. If you are running a metric and you are getting an error, it may be because a class is underrepresented, not represented at all, or is 'all true.' In these cases, we may need to know which class is impacted in order to handle it. In addition, it is quite common to inspect the data you are working with before passing it to a metric.Note: It is ok, even preferred, if it is still a method in the class. My issue is that when you instantiate the class, it currently forces you to run a metric. It would be great to be able to perform the
group_byfunction independently of running the metric.riedgar-ms commentedon Jul 8, 2021
Summary
This is a second attempt to summarise the discussion to date, with the goal of reaching a conclusion. The previous summary was overly summarised.
Current Status
As proposed at the the beginning of the thread, we are in the process of moving to requiring named arguments for
MetricFrame. We have just releasedv0.7.0which issues a warning if positional arguments are used; withv0.8.0we plan to make named arguments mandatory. At that point, the signature ofMetricFrameshould be:Note that the metric functions themselves are dispatched using positional arguments - the basic signature is assumed to be
metric_fn(y_true, y_pred). Now that we are requiring named arguments, this is an inconsistency.Functionality Gaps
The feedback above (and from other sources) has highlighted several gaps in the functionality of
MetricFrame. Specifically:y_predbuty_scoreinstead (ofteny_predimplies a label from a classification)inverse_propensity_score(*, actions_taken, rewards, propensities, actions_target)selection_ratefor which we have a custom function which ignores they_trueargument)MetricFrameThere are actually work arounds for all of these using the existing
MetricFrame. These generally involve some combination of custom metric functions, makingy_trueand/ory_predinto a list of dictionaries, and filling extra arguments out viasample_params. The question is whether we can make the process easier.A note on precomputed metrics
In the above, one proposed solution for the precomputed metric problem was to have a static factory method
MetricFrame.from_precomputed(). However, I don't think this is needed - the precomputed metrics are still per-sample, and need to be aggregated somehow. The aggregation function (such asmean()ormin()is then the 'metric'. We should make sure this is documented, though.Proposed solutions
There are two basic ways to provide other columns - as
**kwargsor a separate dictionary. In the following, we assume that the existingy_trueandy_predarguments get folded in eventually , although there would have to be intermediate releases (similar to the switch to named arguments).Providing
**kwargsIn this case, the signature of
MetricFramewould becomeand it would be invoked like:
However,
**kwargshas the downside that, it is hard to add other required arguments in future, since we can be sure that whatever name we pick, we will break someone. Personally, I also think it makes documentation more difficult to read.Providing a dictionary
Rather than provide individual arguments, we can have a
direct_sample_paramsdictionary. The signature would then be:and it would be invoked like:
This is somewhat clunkier, but does avoid the problems associated with adding extra arguments in future.
Dispatching the Metric Functions
Regardless of how we accept the non-
y_true/y_predarguments, we then have to decide how to call the individual metric functions.The main question is whether we are going to
direct_sample_params(or**direct_sample_params); orinspect.signature()I believe) to examine which functions want which argumentsOption (2) is obviously much more flexible; for example, one could do something like:
(or similarly for the non-
**kwargsoption) and expect things to Just Work.There are two problems with using reflection in this way. First, consider the example of a precomputed metric such as
word_error_rate. We might want to usenumpy.mean()as the aggregator.... but the argument for that is calledaand notword_error_rate. Users would still have to write a wrapper function to make the names match.Secondly, using reflection like this opens up a huge trap - a typo in the argument name can cause really subtle problems. If the metric function considers an argument to be mandatory (likely for something like
y_trueory_score), then an error will be thrown. However, for an optional argument (thinksample_weightvssample_weightsif a user were trying to pass the weights to every metric, rather than usingsample_params) then the typo will simply stop the argument being passed, which might not be noticed for a long time (ask me about the value ofIMPLICIT NONEand why zero initialisation is a travesty).Working with Streaming
PR #670 is working to add streaming to
MetricFrame. I think that all of the above should be compatible with that, but we should keep it in mind.Tagging @adrinjalali @hildeweerts @kstohr @michaelamoako @MiroDudik
adrinjalali commentedon Jul 9, 2021
I personally don't mind this inconsistency.
As for the rest of the proposal, I find it way too complicated, and not very user friendly, and hard to explain to users.
I would rather settle for a middle ground where we leave
MetricFrameunchanged, and have aDatasetMetricFramewhich accepts only oney. An API which supports all possible cases is an overly complicated one which is designed to handle 100% of the cases, we could settle for 95% and have a much simpler API, and have the other 5% use-cases do the appropriate workarounds.We should of course accept extra input required by the metric. For example, in the case of
inverse_propensity_score, if I understand correctly, we can have something like:And with SLEP006 sklearn could accept something like:
to get a scorer. Note that this has removed the need for us to do any introspection, but we have a scorer object which is a callable but also has a state.
An alternative here, since we don't actually do slicing to re-call a scorer, is to have an object which only accepts precomputed scores, like
Or something like that.
riedgar-ms commentedon Jul 22, 2021
First, my apologies @adrinjalali for not responding sooner.
For
MetricFrameitself, I've very happy with leaving it with its current form (as I mentioned above).I'm not quite sure what you're describing with
make_scorer(). Are you saying that users would make a call along the lines of:and then pass
my_metric_fntoFlexibleMetricFrame(or whatever we call it... I'm not a huge fan of that name). This object would provide theget_metadata_request()method which is mentioned in SLEP006, and whichFlexibleMetricFramecould then use to route the arguments. So the user's invocation would be something like:Since
recall_scorewon't haveget_metadata_request()it will only be passedy_trueandy_pred(positionally). In contrast,my_metric_fnwill respond that it wantsrewardsandpropensitiesas well, and be passed them. We avoid the 'hole' of dropped arguments due to spelling errors becausemake_scorer()can check that itsscore_paramsall appear in the signature of the underlying function, and similarlyFlexibleMetricFramecan check its**kwargslist against the results ofget_metadata_request().Presumably,
FlexibleMetricFrame(or its improved cognomen) would not accept thesample_params=dictionaries ofMetricFramebecause that would be taken care of throughget_metadata_request()?riedgar-ms commentedon Aug 6, 2021
Pinging @adrinjalali .... did I get what you meant by
make_scorer()?adrinjalali commentedon Aug 9, 2021
So what I was trying to say, is that handling the metadata routing is really not that easy, and most APIs we've tried to design are messy. The API in sklearn applies to scorers i.e.
scorer(estimator, X, y), rather than scoring functions i.e.score(y_true, y_pred). Addingget_metadata_request()is certainly a way forward, but it's not an easy one.Alternatively, we could let
AlternativeMetricFrameto accept a scorer instead of scoring functions, and then it will be exactly in the scope of SLEP006, which would make things much easier.I guess for now, we could have something like:
We could also accept a scorer instead of the scoring method, but the user would also need to pass the estimator. I kinda would prefer that if we're gonna do routing.
hildeweerts commentedon Sep 1, 2021
I don't have a lot to add to this discussion, but I agree that leaving
MetricFrameas is and adding an alternative more flexible version would be preferable.pinging @fairlearn/fairlearn-maintainers to move the discussion forward