Skip to content

Error Bars/Uncertainty Quantification for MetricFrame #999

Closed

Description

@Harsha-Nori

Is your feature request related to a problem? Please describe.

There is currently no built-in way of assessing the volatility or uncertainty associated with metrics generated via MetricFrame. This has important implications for the interpretation of any observed values or differences between groups. For example, if a metric changes significantly under small changes (e.g. through resampling), the difference might be explained fully by something like sampling error.

For example, here is a plot from the FairLearn documentation:

The differences between the two groups in accuracy and selection_rate appear to be larger than the differences in precision and recall. However, it could just be that metrics like selection_rate are inherently higher variance metrics than precision, which might contextualize why the magnitude of the differences is larger.

Describe the solution you'd like

I'd like to propose a bootstrap based solution built directly into MetricFrame. Bootstrap is a conceptually simple procedure that involves building an empirical distribution of a given metric/dataset by repeatedly:

  1. Sampling up to the full size of the dataset with replacement
  2. Re-calculating the metric on this new sample

When repeated hundreds or thousands of times, we can study the empirical distribution and produce useful summaries like confidence intervals for the metric.

There are several reasons why bootstrap might be an appropriate solution here:

  • It is widely adopted and studied, making it a statistically defensible choice
  • Bootstrap is agnostic to characteristics of the dataset and metric, making it largely assumption-free and widely applicable
  • It is straightforward to explain and implement as a higher level layer on top of the core MetricFrame subroutines

However, it does come with a few downsides. Primarily, bootstrap is very computationally intensive. By definition, it is 100x - 1000x+ as intensive as running the core MetricFrame routine, which makes performance a key concern. This might be mitigated by:

  • Having the bootstrap procedure be opt-in, and defaulted to "off". This has the added benefit of being completely backwards compatible.
  • Improving the performance of the current MetricFrame (which seems to be being addressed by PRs like Improve MetricFrame performance #985).
  • Allowing for parallel processing at the bootstrap layer, as bootstrap is an embarassingly parallel operation. This would achieve an approximately linear speedup with the number of available processes on a user machine.

Like most methods, bootstrap also does not work if the user supplied dataset is not representative of the population. In addition, bootstrap will struggle with very low sample size or incredibly homogenous groups (e.g. if every member of group A had an identical label). These should also be addressed with appropriate warnings.

Finally, it's important to point out that error bars derived from bootstrap cannot directly be used to make claims about statistical significance, especially amongst multiple groups simultaneously. In other words, simply looking at overlaps between error bars does not constitute a formal hypothesis test.

Describe alternatives you've considered, if relevant

There are some alternative resampling methods that might provide tighter estimates or be slightly more computationally efficient, like the jackknife, but these are not as well known in the literature.

There is also a complementary line of work possible in structuring formal hypothesis tests, but it would supplement this contribution (and not be in place of it).

Additional context

I'd like to work on adding support for bootstrap and confidence intervals in FairLearn. I'm opening this issue to solicit community and maintainer feedback on the general idea, proposed approach, and finer details around the implementation. In addition to general comments, some thoughts on the following topics would be appreciated.

Performance / Parallel Processing

As mentioned earlier, one way to mitigate performance concerns would be to introduce parallel processing capabilities into FairLearn specifically for the bootstrap layer. Because scikit-learn is already a FairLearn dependency, we could use the joblib library to achieve this with relatively little additional code without taking on any additional dependencies. I'd just like to make sure the concept of multiprocessing and an explicit (rather than implicit) joblib dependency is OK first.

API

There'd be a few proposed changes to the MetricFrame API here, both in the input parameters to the constructor and the output data formats. Here's an example of what the new constructor may look like (additional parameters annoted with a # NEW comment):

def __init__(self,
             *,
             metrics: Union[Callable, Dict[str, Callable]],
             y_true,
             y_pred,
             sensitive_features,
             control_features: Optional = None,
             sample_params: Optional[Union[Dict[str, Any], Dict[str, Dict[str, Any]]]] = None,
             n_boot: Optional[int] = None,  # NEW
             quantiles: Tuple[float, ...] = (2.5, 97.5), # NEW
             n_jobs: int = -1 # NEW
):

n_boot is the number of bootstrap iterations to run. This can be defaulted to None, which means skipping the bootstrap process altogether and ignoring the following parameters. In practice, it would be recommended to set this to ~1000.

quantiles are the percentiles from the empirical bootstrap distribution to preserve and report back to the user. This is defaulted to (2.5, 97.5) to represent a 95% confidence interval, but can easily be changed to an 80% interval by setting it to (10, 90). With this type of parameter specification, users can also sample more points than just the endpoints of the confidence interval -- for example, if you are interested in every quartile, the API would be flexible enough to allow for e.g quantiles = (2.5, 25, 50, 75, 97.5), or to allow for asymmetric confidence intervals. We could easily drop this though and replace it with a single floating point number representing the width of the CI.

n_jobs is the popular joblib/scikit-learn parameter representing how many cores a user is willing to use on their machine for parallelization. n_jobs=1 would use a single processor, n_jobs=-1 uses every available processor, n_jobs=-2 is all but one processor, etc. More information here: https://scikit-learn.org/stable/glossary.html#term-n_jobs

In terms of output structure, there are two choices that come to mind: modifying the internals of each .by_group dataframe to hold something like a tuple instead of a scalar in each cell, or returning a separate frame for each requested quantile. I tend to prefer the latter approach, which may look something like this:

image

because of its readability and ease of working with -- any operation or workflow established on the "main" frame would also work for the quantiles. It would be great to hear thoughts on this, and if it seems like a decent idea, how it might be exposed off the main MetricFrame object (for example, maybe mf.by_group_intervals or mf.by_group_quantiles)?

Finally, in terms of plotting, the Pandas Dataframe plotting API has support for error bars: https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html#plotting-with-error-bars , and it might be straightforward to extend the plotting documentation to accommodate this.

Would appreciate any and all thoughts!
-Harsha

Activity

  1. riedgar-ms commented on Dec 3, 2021

    @riedgar-ms
    Member

    Thank you for opening this issue!

    My immediate thought is that bootstrapping isn't really anything to do with MetricFrame - couldn't the approach you're describing be made into a wrapper around any metric? Then that metric could be placed in a MetricFrame like any other.

    However, that would force the 'DataFrame of tuples' return type, rather than the 'dictionary of DataFrames' you propose. If people feel that the latter return type would be more useful, then the approach described here seems reasonable. It is possible that my instinct to compartmentalise is operating excessively.

    At the risk of displaying my ignorance of statistics, I would like to know a bit more about the significance testing part. My default assumption is that if two numbers have overlapping error bars, then they're not significantly different. It sounds like that's not the case?

  2. hildeweerts commented on Dec 6, 2021

    @hildeweerts
    Contributor

    Thank you for opening this issue and the thorough and clear description @Harsha-Nori! Let me start by saying I'm super happy that you're picking this up and I think the plan looks really good.

    My immediate thought is that bootstrapping isn't really anything to do with MetricFrame - couldn't the approach you're describing be made into a wrapper around any metric? Then that metric could be placed in a MetricFrame like any other.

    An advantage of adding bootstrapping directly to MetricFrame is that it creates a lot less overhead for the user, especially if you have a bunch of them. And, not unimportantly, it is much easier to locate compared to a separate function. It also opens up some opportunities to automatically ignore the CI's in e.g., 'overall' or difference(), which could avoid some hard-to-interpret results (see also below).

    At the risk of displaying my ignorance of statistics, I would like to know a bit more about the significance testing part. My default assumption is that if two numbers have overlapping error bars, then they're not significantly different. It sounds like that's not the case?

    As far as I understand, the "problem" is that bootstrapping gives a confidence interval around the estimates for each group separately (e.g., p_a and p_b). Because you do not make any assumptions about the distributions (e.g., that they're normally distributed), the overlap of these estimates does not correspond directly to the null hypothesis of comparing means. To use bootstrapping as a hypothesis test I believe you'd need to run the procedure to get an estimation of the difference between the groups (p_a - p_b) directly. But perhaps somebody who understand this on a deeper level can explain it better :)

    This does correspond to a point briefly discussed in last week's community call: our documentation needs to be super clear about what you can and cannot conclude from these confidence intervals. Given that the entire goal of MetricFrame is to compare groups, it is very natural that people will (visually) compare the confidence intervals as an informal hypothesis test, even if we add a warning that they shouldn't.

    Tagging @fairlearn/fairlearn-maintainers

    [A final note not directly relevant to this discussion but so we don't forget:] @MiroDudik also remarked that even if we would add functionality for formal hypothesis testing, statistical significance is not necessarily equal to practical relevance (if your sample is big enough, you'll always find a statistically significant difference). So if we go that route we might want to go for e.g., equivalence testing, where you need to specify beforehand what you'd consider a relevant difference.

  3. Harsha-Nori commented on Dec 7, 2021

    @Harsha-Nori
    Author

    Hi @riedgar-ms and @hildeweerts,

    Thanks for taking the time to provide such thoughtful feedback! Here's my take on a few of the questions raised:

    My immediate thought is that bootstrapping isn't really anything to do with MetricFrame - couldn't the approach you're describing be made into a wrapper around any metric? Then that metric could be placed in a MetricFrame like any other."

    I agree with @hildeweerts' response here -- my feeling is that direct integration means less work for the user in both setting up the analysis and in post-processing results afterwards. A dataframe of tuples is particularly nasty to work with, and will break many existing pandas/numpy workflows users may depend on. In addition, it makes plotting with error bars significantly more tedious as well.

    At the risk of displaying my ignorance of statistics, I would like to know a bit more about the significance testing part. My default assumption is that if two numbers have overlapping error bars, then they're not significantly different. It sounds like that's not the case?

    As far as I understand, the "problem" is that bootstrapping gives a confidence interval around the estimates for each group separately (e.g., p_a and p_b). Because you do not make any assumptions about the distributions (e.g., that they're normally distributed), the overlap of these estimates does not correspond directly to the null hypothesis of comparing means. To use bootstrapping as a hypothesis test I believe you'd need to run the procedure to get an estimation of the difference between the groups (p_a - p_b) directly. But perhaps somebody who understand this on a deeper level can explain it better :)

    Completely agree with @hildeweerts here as well! Hypothesis testing frameworks also often take into account the number of samples present in each group, which the simple bootstrap based error bars don't explicitly account for. In addition, things get even more complex when doing multiple comparisons (for example, a sensitive feature like 'Race' may have 5-10+ different levels to it). Checking for error bar overlap doesn't intuitively translate to probabilities in these settings.

    This does correspond to a point briefly discussed in last week's community call: our documentation needs to be super clear about what you can and cannot conclude from these confidence intervals. Given that the entire goal of MetricFrame is to compare groups, it is very natural that people will (visually) compare the confidence intervals as an informal hypothesis test, even if we add a warning that they shouldn't.

    This is a really important point. On top of documentation on the website, are there any other mechanisms that FairLearn uses to alert users about these types of pitfalls (e.g. warnings or visualization hints)?

  4. Harsha-Nori commented on Dec 7, 2021

    @Harsha-Nori
    Author

    Also want to call out that @fredcam has expressed interest in working on this too, so we'll be handling this together 🙂

  5. hildeweerts commented on Dec 8, 2021

    @hildeweerts
    Contributor

    This is a really important point. On top of documentation on the website, are there any other mechanisms that FairLearn uses to alert users about these types of pitfalls (e.g. warnings or visualization hints)?

    We have discussed this in our learning resources working group, but we currently don't have any. Warnings, hints and documentation on this sounds like a great idea!

  6. riedgar-ms commented on Dec 9, 2021

    @riedgar-ms
    Member

    @Harsha-Nori I agree that if a DataFrame-of-tuples is considered undesirable, then building this into MetricFrame is the proper approach.

    I do think that the statistics is going to need careful explanation. I can sort of see that 'different underlying distributions' etc. etc. might mean that the error bars on a particular metric for subgroups A, B and C aren't strictly comparable. But if seeing the overlap means nothing then the usefulness of the error bars is somewhat lessened.

  7. MiroDudik commented on Dec 9, 2021

    @MiroDudik
    Member

    Some quick thoughts:

    • I'm in favor of this being part of MetricFrame. First, because of convenience, but more importantly, because we really need to be able to obtain error bars on difference(), ratio(), group_max(), and group_min(). The error bars on those are particularly important for the ability to quantify fairness.

    • Also, I agree that we should document how we suggest that the data scientist view these error bars. For example, when comparing, say, false positive rate (FPR) on two segments of population, the data scientist shouldn't be necessarily looking for the overlap, but instead should be looking at what's the worst case difference between those two groups (i.e., the opposite of the overlap).

    • Basically, in the context of fairness, we are not worried that the point estimates are too pessimistic, we are actually worried that the point estimates might be too optimistic, and so with error bars on subpopulations, we are looking at their extreme values. If the error bars are too big, this means that we have too little data--and with the data that we have, it might be the case that the two subpopulations have indeed starkly different FPRs even if their error bars overlap (if their error bars are also big).

    • Another usage of the MetricFrame with error bars is to examine the error bars of difference() (or some of the other aggregates), and again the focus should be on the worst case. This can be even turned into a statistical test. If we get a 95%-confidence interval [a,b] for the value of the difference, we can reject the hypothesis that difference()>b at p=0.05 (in fact we might get a better p, because the test is one-sided, whereas the confidence interval is two-sided).

  8. riedgar-ms commented on Dec 9, 2021

    @riedgar-ms
    Member

    Having had a meeting with @MiroDudik and @Harsha-Nori , my problem was thinking about the issue backwards. I'm more used to the case of seeing people claim that two points with massively overlapping error bars are actually different. However, for fairness (at least as practised by MetricFrame) the 'good' case is where the numbers are the same (because you then have zero disparity), so the incentives for stretching the statistics are reversed.

    Hence point above that making bootstrapping a builtin of MetricFrame, we can add errors to the difference() and ratio() methods, which is where the errors are really useful.

  9. hildeweerts commented on Dec 10, 2021

    @hildeweerts
    Contributor

    I'm in favor of this being part of MetricFrame. First, because of convenience, but more importantly, because we really need to be able to obtain error bars on difference(), ratio(), group_max(), and group_min(). The error bars on those are particularly important for the ability to quantify fairness.

    Just to make sure I understand this correctly, the error bars on difference() would be computed by bootstrapping the difference, right?

    Another usage of the MetricFrame with error bars is to examine the error bars of difference() (or some of the other aggregates), and again the focus should be on the worst case. This can be even turned into a statistical test. If we get a 95%-confidence interval [a,b] for the value of the difference, we can reject the hypothesis that difference()>b at p=0.05 (in fact we might get a better p, because the test is one-sided, whereas the confidence interval is two-sided).

    As a note for future documentation, this would basically constitute a non-inferiority test (the one-sided version of an equivalence test): https://en.wikipedia.org/wiki/Equivalence_test

  10. MiroDudik commented on Dec 10, 2021

    @MiroDudik
    Member

    Just to make sure I understand this correctly, the error bars on difference() would be computed by bootstrapping the difference, right?

    Yes! That's exactly what I had in mind -- it should work reasonably well even if we have many groups, because we don't have to worry about multiple hypothesis testing. However, we'll need to ensure that we deal correctly (that means conservatively) with some bad cases. The main bad case is when the number of data points in one of the subgroups, say G is too small. This can demonstrate in a variety of ways. Two extreme examples that come to mind:

    • Some of the bootstrap replicates have no data points in G. (This could be prevented by stratification.)
    • The sample variance (in the overall dataset) within group G is artificially small. This can happen for example when the value of the metric is 0/1 and we have too few data points and they are all 0s or all 1s. Another extreme case is when we have only one data point from some group (its sample variance is then obviously 0).

    I am not aware of how to address the latter point in the fully distribution-free manner. The most appealing approach to me would be to allow the user specify the range of values that the metric can take (e.g., [0,1] in case of the binary metrics), which seems like a minimal information that would then allow us to construct conservative confidence intervals. Plus we would issue warnings if we detect sample sizes too small and the metric ranges are not specified. (Another alternative would be to go Bayesian and construct credible intervals, but perhaps we can keep that for future.)

    Another usage of the MetricFrame with error bars is to examine the error bars of difference() (or some of the other aggregates), and again the focus should be on the worst case. This can be even turned into a statistical test. If we get a 95%-confidence interval [a,b] for the value of the difference, we can reject the hypothesis that difference()>b at p=0.05 (in fact we might get a better p, because the test is one-sided, whereas the confidence interval is two-sided).

    As a note for future documentation, this would basically constitute a non-inferiority test (the one-sided version of an equivalence test): https://en.wikipedia.org/wiki/Equivalence_test

    Nice. I wasn't aware that that's how these are called!

  11. Harsha-Nori commented on Dec 10, 2021

    @Harsha-Nori
    Author

    Thank you @MiroDudik for the thoughtful comments!

    Another usage of the MetricFrame with error bars is to examine the error bars of difference() (or some of the other aggregates), and again the focus should be on the worst case. This can be even turned into a statistical test. If we get a 95%-confidence interval [a,b] for the value of the difference, we can reject the hypothesis that difference()>b at p=0.05 (in fact we might get a better p, because the test is one-sided, whereas the confidence interval is two-sided).

    @hildeweerts, I'm expanding on your question so quoting it here:

    Just to make sure I understand this correctly, the error bars on difference() would be computed by bootstrapping the difference, right?

    I think this is a natural plan for the 2 groups setting, but I have a few questions about the case when there are >2 groups. I believe the current .difference() implementation adaptively chooses the maximum disparity between any two observed groups. For group/metric combinations with high variance and similar point estimates, the two groups chosen for the absolute difference calculation may change between bootstrap iterations if we just use the built-in fairlearn utility as a subroutine.

    A natural solution here might be to fix the two groups chosen for the difference before doing bootstrap. We can use the entire dataset to estimate the groups with the largest differences in point estimates and fix those as the chosen "differencing" groups.

    But in terms of the hypothesis testing translation, I think it's important to note that this would only be valid for the comparison between the two groups chosen. Take the case of the "2nd largest" group, for example, which may have a smaller mean but maybe a significantly larger variance than the "largest" group. This "2nd largest" group may very well have a significant disparity with another group, even if the two groups chosen for differencing don't have one.

    It could very well be that this is a pathological case and not worth considering too carefully, but I believe it gets increasingly more likely as the number of groups grows.

    One other option is to explicitly run the bootstrap difference on every pairwise combination of groups, and simply log all results. This increases the runtime cost, but we could then adaptively choose at the end of the bootstrap which groups we want to publish a .difference() summary for, instead of choosing before we know the metric variances on each group. Or even allow users to access all pairwise difference distributions. Would appreciate any thoughts on this!

  12. MiroDudik commented on Dec 10, 2021

    @MiroDudik
    Member

    @Harsha-Nori :

    I think this is a natural plan for the 2 groups setting, but I have a few questions about the case when there are >2 groups. I believethe current .difference() implementation adaptively chooses the maximum disparity between any two observed groups. For group/metric combinations with high variance and similar point estimates, the two groups chosen for the absolute difference calculation may change between bootstrap iterations if we just use the built-in fairlearn utility as a subroutine.

    A natural solution here might be to fix the two groups chosen for the difference before doing bootstrap. We can use the entire dataset to estimate the groups with the largest differences in point estimates and fix those as the chosen "differencing" groups.

    I don't think we should fix the two groups in advance. We should basically calculate the difference() value separately for each bootstrap replicate and then report the confidence intervals of that statistic, and be clear in our documentation that we do this and what it means.

    For a comparison of two specific groups, we could consider creating a new aggregator, maybe called "deviation()" or "pairwise_difference()" that would return all-pairs signed differences in the form of a skew-symmetric matrix, and we could then possibly construct separate confidence intervals for each of the matrix entries. However, I'm thinking that this should be proposed and discussed in a separate issue. (Thoughts on this?) Practically speaking, since our groups are non-overlapping, we can construct conservative confidence intervals for the signed differences just using confidence intervals for individual groups... of course, multiple hypothesis issues arise when interpreting such all-pairs difference matrix.

  13. hildeweerts commented on Dec 10, 2021

    @hildeweerts
    Contributor

    I agree that we should not fix the groups in advance - the points raised by @Harsha-Nori are very valid and I think we have the responsibility to avoid possibly misleading results as much as possible.

    Yes! That's exactly what I had in mind -- it should work reasonably well even if we have many groups, because we don't have to worry about multiple hypothesis testing.

    Could you expand a bit more on this @MiroDudik? It is not entirely clear to me why this approach would alleviate issues with multiple hypothesis testing. It seems like you'd still need to repeat the bootstrapping procedure for all pairs of groups and adjust the significance levels accordingly. Or do you mean that you would compute one confidence interval for the difference between any two groups? I am a bit worried that such a result wouldn't be very informative/actionable - if there is a difference, you'd probably want to investigate more fine grained results anyways.

  14. Harsha-Nori commented on Feb 3, 2022

    @Harsha-Nori
    Author

    Hi @hildeweerts, @riedgar-ms, @MiroDudik, and everybody,

    Following up on Miro's comment:

    We should basically calculate the difference() value separately for each bootstrap replicate and then report the confidence intervals of that statistic, and be clear in our documentation that we do this and what it means.

    I have an open question about the calculation of uncertainty intervals for .difference() and .ratio(). I currently generate all bootstrap versions of each frame at __init__() time, log the requested user statistics (e.g. the 95% intervals for each metric/group), and discard the intermediary bootstrap samples. However, because .difference() and .ratio() are accessed as methods after initialization which expose parameters, I believe I have two choices to support uncertainty metrics for them:

    1. Calculate the bootstrap statistics for all possible permutations of .difference() and .ratio() inputs at initialization time, and continue to discard the intermediary bootstrap distribution samples. We can simply use a lookup table to return results to the user when they call the methods. This may lead to (a moderate amount) of wasted computation at initialization if the user doesn't end up asking for a .difference/ratio, and will get significantly more costly if FairLearn ever adds more configuration options for these methods over time.

    2. Pin all bootstrap samples to MetricFrame and calculate everything on the fly as the user requests it. This would allow much more flexibility (e.g. querying any size interval you want without re-initializing your MetricFrame), but would significantly increase the sustained memory footprint of MetricFrame (by 100-1000x+, essentially linear in the number of bootstrap samples).

    This also poses a few interesting design choices in terms of the fairlearn API.

    Currently, .by_group and .overall are implemented as properties, while .difference() and .ratio() are implemented as methods. How should we expose the calculated uncertainty intervals across each of these attributes? One option is to parallel the current structure of the attributes, so add new properties for intervals on .by_group and .overall and new parameters to the methods for .difference() and .ratio().

    So as an example, there may be e.g. a .by_group_uncertainty (making up the name) and e.g. my_metric_frame.difference(return_uncertainty=True) to yield the additional information to the user. I think clarifying the right approach for the first question may help address this question as well.

    Would appreciate any and all thoughts on this!

    -Harsha

  15. MiroDudik commented on Feb 3, 2022

    @MiroDudik
    Member

    @hildeweerts :

    Could you expand a bit more on this @MiroDudik? It is not entirely clear to me why this approach would alleviate issues with multiple hypothesis testing. It seems like you'd still need to repeat the bootstrapping procedure for all pairs of groups and adjust the significance levels accordingly. Or do you mean that you would compute one confidence interval for the difference between any two groups? I am a bit worried that such a result wouldn't be very informative/actionable - if there is a difference, you'd probably want to investigate more fine grained results anyways.

    I think I meant the latter. The logic is this:

    • difference is a statistic that corresponds to the difference between the slice with the largest and the smallest metric value. And we would return a confidence interval for this statistic. In each bootstrap replicate the identity of a slice with the largest and smallest statistic might be different, but the statistic is always well defined. And since we are calculating a confidence interval of only one statistic, we don't need to worry about multiple hypothesis testing.

    In terms of how actionable the results are--I was thinking about the usage like in the comment above. Basically, if the upper bound of the confidence interval is small then it's good news. And if the upper bound is large, then I agree that you the next step is to look into individual slices. I think that you basically want to look at a plot that looks something like what we did in the SciPy tutorial:

    (and what's also covered in #857). And consider groups whose upper confidence interval is hitting the top with groups whose lower confidence interval is hitting the bottom.

    @Harsha-Nori :

    I'm strongly leaning towards option 1--so we would precalculate things for our all of our aggregators, i.e., for difference (two versions), ratio (two versions), group_min, and group_max. That doesn't seem like too much of an overhead.

    Re. API, I think I'd start with something like

    • .overall_ci, .by_group_ci
    • .difference_ci(), .ratio_ci(), ...

    Another alternative would be to add a new field .ci which would be another MetricFrame that contains the confidence intervals, so the access pattern would be:

    • .ci.overall, ci.by_group
    • .ci.difference(), ci.ratio(), ...

    Not sure if this makes things cleaner or more confusing.

  16. Harsha-Nori commented on Feb 5, 2022

    @Harsha-Nori
    Author

    Thank you for the detailed reply @MiroDudik!

    I'm strongly leaning towards option 1--so we would precalculate things for our all of our aggregators, i.e., for difference (two versions), ratio (two versions), group_min, and group_max. That doesn't seem like too much of an overhead.

    I think pre-calculating at init time sounds pretty reasonable, especially if there aren't plans to expand the currently available options significantly. It might be worth considering moving the current/standard difference, ratio, and group_{min,max} calculations into the init call as well, instead of duplicating the logic between confidence intervals and standard outputs.

    Re. API, I think I'd start with something like

    • .overall_ci, .by_group_ci
    • .difference_ci(), .ratio_ci(), ...

    Another alternative would be to add a new field .ci which would be another MetricFrame that contains the confidence intervals, so the access pattern would be:

    • .ci.overall, ci.by_group
    • .ci.difference(), ci.ratio(), ...

    Not sure if this makes things cleaner or more confusing.

    I think both options are interesting, but I'd strongly prefer not to yield a single MetricFrame from the .ci field if it means having a "dataframe of tuples". Returning a list/dictionary of two or more separate frames for the requested interval ranges will be much more friendly for downstream tasks IMO.

  17. MiroDudik commented on Nov 30, 2022

    @MiroDudik
    Member

    I'm adding here this example from @hildeweerts:

    I don't think it would be a one liner, but it is generally not advised to put lists in a DataFrame. To retrieve the data you need to either iterate over all the rows, or use some variation ofapply() to access the data (e.g., df.metric.apply(lambda x: x[0]) ) to access the first item in the list), which is generally very slow - though that is probably a minor concern as MetricFrame.by_group will be rather small in most use case. I'll try to put together some code examples (likely next week) to see which format would be easier to turn into a plot with error bars.

    So I haven't been able to come up with a straightforward code example quickly for either option, mostly because pandas.plot.bar() wants asymmetrical errors to be in an annoying format. (If you want to make a plot where bars are grouped per metric, the means (or more accurately in case of the 0.5 quantile, medians) will be in MxN matrix, where M is metrics and N is groups. Then, pandas.plot.bar() wants yerr to be formatted as an Mx2xN array with the errors relative to the median rather than the absolute values. That's not really doable in a one or two liner in either of the formats...)

    One advantage of hierarchical indexing, though, is that (1) it is somewhat easier to interpret, (2) you can very easily get some kind of plot without further processing. E.g., if you have the following dataframes:

    import pandas as pd 
    
    # create df with lists
    df_l = pd.DataFrame({'fpr' : [[0.1, 0.22, 0.3], [0.05, 0.1, 0.17]],
                  'tpr' : [[0.8, 0.9, 0.95], [0.85,0.92,0.97]]}, index=['group A', 'group B'])
    
    # df with multi index, metrics first
    cols = pd.MultiIndex.from_tuples([("fpr", "q1"), 
                                      ("fpr", "q2"),
                                      ("fpr", "q3"),
                                      ("tpr", "q1"),
                                      ("tpr", "q2"),
                                      ("tpr", "q3"),
                                     ])
    data=[[0.1, 0.22, 0.3,  0.8, 0.9, 0.95], 
          [0.05, 0.1, 0.17, 0.85,0.92,0.97]]
    df_mm = pd.DataFrame(data, columns=cols,index=['group A', 'group B'])
    image
    df_mm.plot.bar()
    image
  18. MiroDudik commented on Nov 30, 2022

    @MiroDudik
    Member

    Based on the conversation on the call today (12/1/2022), I'm in favor of thinking about the use case where we would like to surface confidence intervals (rather than arbitrary quantiles). With that in mind, I think it might be good to center the API on enabling confidence intervals, supporting both one sided and two-sided versions.

    I think that here are some API choices:

    1. Specifying conf. interval quantiles:

      a. in constructor:
      --> two-sided: MetricFrame(..., ci_quantiles=[0.025,0.975], ...)
      --> lower only: MetricFrame(..., ci_quantiles=[0.05], ...)
      --> upper only: MetricFrame(..., ci_quantiles=[0.95], ...)
      --> multiple conf. levels: MetricFrame(..., ci_quantiles=[0.005,0.025,0.975,0.995], ...)

      • (+) storage is only needed for each quantile (not for each bootstrap replicate)
      • (+) all of the functions are coordinated on the same quantile
      • (-) less flexibility

      b. in methods/properties: difference(..., ci_quantiles=[0.025,0.975])

      • (+) more flexibility
      • (-) storage is required for all bootstrap replicates
      • (-) more repetitive if non-default quantiles are desired, because these would need to be repeated at every invocation rather than just in the constructor
      • (+/-): properties (like by_group) would need to become methods, or separate methods would need to be introduced like by_group_ci()
    2. The invocation format to obtain confidence intervals:

      a. new methods/properties via suffix, e.g., by_group_ci, difference_ci()

      • (+) simple to understand API, exactly parallel to existing methods/properties
      • (-) quite a few new methods/properties would need to be added

      b. new arguments to existing methods/properties, e.g., difference(..., ci_quantiles=[...], ...)

      • (-) more complicated API
      • (-) to implement confidence intervals for by_group, it would need to change from a property to a method

      c. a field that behaves like a MetricFrame, e.g., mf.ci.by_group, mf.ci.difference()

      • (-) more complicated API
    3. The return type, e.g., of by_group_ci or difference_ci()

      a. list of frames

      b. frame of lists

      c. frame with a hierarchical column index

    I'm tentatively in favor of 1a, 2a, 3a.

  19. taharallouche commented on Jan 19, 2025

    @taharallouche
    Member

    I assume this can be closed, since the MetricFrame does cover at least all the points mentionned in the last comment #999 (comment)

    Is it ok for you @hildeweerts @riedgar-ms @MiroDudik ? 🙏 If there are some missing features, can you please point me to them so that I can extract them to a seperate issue with a clearer description ?

  20. hildeweerts commented on Jan 24, 2025

    @hildeweerts
    Contributor

    @taharallouche imo, the only thing that could be a separate issue at this point is (documentation on) plotting the CIs. Otherwise, I agree this can be closed, as I don't think we plan to extend the CI functionality soon.

  21. riedgar-ms commented on Jan 24, 2025

    @riedgar-ms
    Member

    'CI' is overloaded....

    I agree that this can be closed. Anything deemed still missing can be a fresh issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions