Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show "missing" counts in confusion matrices #5187

Merged
merged 3 commits into from
Dec 19, 2024

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Nov 25, 2024

Change log

When evaluating object detections, confusion matrices need the ability to show an additional row/column to capture “missing” values:

  • "missing": false negative ground truth (no matched prediction)
  • "missing": false positive predictions (no matched ground truth)

TODO

  • Update set_view() callbacks to correctly handle "missing" cases
  • The panel currently throws an exception when I click on a "missing" row/col (bottom row or rightmost col)
  • The backend now includes the "missing" class as the LAST row/col of the confusion matrices (see the example code below). When the user requests k=10 classes, we need to display 11 total rows/cols: the 10 rows/cols representing the classes they requested PLUS the last row/col so that we're showing the "missing" data. This means the frontend logic for applying the limit=k logic will need to select the first k rows plus the last row of the appropriate confusion matrix, rather than just the first k rows

Example usage

import fiftyone as fo
import fiftyone.zoo as foz

dataset = foz.load_zoo_dataset("quickstart")

results = dataset.evaluate_detections(
    "predictions",
    gt_field="ground_truth",
    eval_key="eval",
    classwise=False,
)

session = fo.launch_app(dataset)
from collections import Counter

freq = Counter(results.ytrue)
if results.missing in freq:
    freq.pop(results.missing)

results.missing
# '(none)'

classes = sorted(freq, key=freq.get, reverse=True)[:5]
# ['person', 'kite', 'bird', 'car', 'carrot']

cmat, labels, _ = results._confusion_matrix(
    classes=classes,
    include_other=False,
    include_missing=True,
    tabulate_ids=False,
)

"""
cmat
array([[665,   2,   1,   0,   0,  43],
       [  0, 123,   1,   0,   0,  15],
       [  3,   2,  84,   0,   0,  22],
       [  0,   0,   0,  45,   0,  12],
       [  0,   0,   0,   0,  34,  12],
       [472,  59,  23, 154, 344,   0]])

labels
['person', 'kite', 'bird', 'car', 'carrot', '(none)']
"""

@brimoor brimoor added the enhancement Code enhancement label Nov 25, 2024
@brimoor brimoor requested a review from imanjra November 25, 2024 15:55
Copy link
Contributor

coderabbitai bot commented Nov 25, 2024

Warning

Rate limit exceeded

@imanjra has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 0 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2a39e70 and 325a0a0.

📒 Files selected for processing (2)
  • app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx (3 hunks)
  • fiftyone/operators/builtins/panels/model_evaluation/__init__.py (2 hunks)

Walkthrough

The pull request modifies the EvaluationPanel class in the model evaluation module, focusing on refactoring methods related to evaluation processing. The changes streamline the logic for handling evaluation results, particularly in methods like get_tp_fp_fn, get_confusion_matrices, load_evaluation, and load_view. The modifications improve the handling of evaluation data, including better management of binary classification checks, confusion matrix generation, and view filtering for evaluation comparisons.

Changes

File Change Summary
fiftyone/operators/builtins/panels/model_evaluation/__init__.py - Removed is_binary_classification method
- Updated get_tp_fp_fn to integrate binary classification logic
- Modified get_confusion_matrices to convert classes to list
- Restructured load_view for enhanced evaluation key handling
- Improved load_evaluation method for managing result states

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • imanjra
  • Br2850

Poem

🐰 Evaluation's dance, a code ballet so fine,
Matrices twirl, metrics align
Panels refactored with rabbit's might
Complexity fades, clarity shines bright
A hop of progress, clean and clear! 🔍


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@brimoor brimoor marked this pull request as draft November 25, 2024 15:56
@brimoor brimoor changed the title Show "missing" counts in confusion matrices [WIP] Show "missing" counts in confusion matrices Nov 25, 2024
Base automatically changed from bugfix/model-eval-conf-matrix to release/v1.1.0 November 25, 2024 22:56
@brimoor brimoor changed the title [WIP] Show "missing" counts in confusion matrices [WIP] Show "missing"/"other" counts in confusion matrices Nov 26, 2024
@brimoor brimoor changed the title [WIP] Show "missing"/"other" counts in confusion matrices [HOLD] Show "missing"/"other" counts in confusion matrices Dec 2, 2024
Base automatically changed from release/v1.1.0 to main December 6, 2024 15:31
@brimoor brimoor changed the base branch from main to develop December 9, 2024 05:49
@brimoor brimoor changed the title [HOLD] Show "missing"/"other" counts in confusion matrices Show "missing"/"other" counts in confusion matrices Dec 9, 2024
@brimoor brimoor marked this pull request as ready for review December 9, 2024 05:49
@brimoor brimoor force-pushed the model-eval-show-missing-none branch from f4bf6c5 to cf54730 Compare December 15, 2024 05:20
@brimoor brimoor changed the base branch from develop to release/v1.2.0 December 15, 2024 05:20
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Nitpick comments (2)
fiftyone/operators/builtins/panels/model_evaluation/__init__.py (1)

252-278: Consider consolidating calls to results._confusion_matrix to improve performance.

In get_confusion_matrices, the method calls results._confusion_matrix multiple times with different class orderings. If this operation is computationally expensive, consider caching the results or refactoring the logic to reduce redundant computations.

app/packages/core/src/plugins/SchemaIO/components/NativeModelEvaluationView/Evaluation.tsx (1)

Line range hint 169-180: Define explicit TypeScript types for evaluationConfig and related variables.

Currently, variables like evaluationConfig, evaluationType, and evaluationMethod may be implicitly typed as any. Defining explicit interfaces or types for these variables will enhance type safety and improve code readability.

🛑 Comments failed to post (1)
fiftyone/operators/builtins/panels/model_evaluation/__init__.py (1)

443-448: ⚠️ Potential issue

Handle potential None value for field before calling field.upper().

In the load_view method, field.upper() is called without checking if field is not None. If field is None, this will raise an AttributeError. Please add a check to ensure field is not None before calling upper().

Apply this diff to fix the issue:

 if self.is_binary_classification(info):
+    if field is not None:
         uppercase_field = field.upper()
+    else:
+        # Handle the None case appropriately
+        uppercase_field = None
     view = ctx.dataset.match(
         {computed_eval_key: {"$eq": uppercase_field}}
     )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            if self.is_binary_classification(info):
                if field is not None:
                    uppercase_field = field.upper()
                else:
                    # Handle the None case appropriately
                    uppercase_field = None
                view = ctx.dataset.match(
                    {computed_eval_key: {"$eq": uppercase_field}}
                )
            else:

@brimoor brimoor force-pushed the model-eval-show-missing-none branch from cf54730 to 2a39e70 Compare December 15, 2024 06:00
@brimoor brimoor changed the base branch from release/v1.2.0 to model-eval-fixes2 December 15, 2024 06:01
@brimoor brimoor changed the title Show "missing"/"other" counts in confusion matrices Show "missing" counts in confusion matrices Dec 15, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Nitpick comments (3)
fiftyone/operators/builtins/panels/model_evaluation/__init__.py (3)

249-275: Add error handling for edge cases

While the implementation correctly handles missing classes, consider adding error handling for the following edge cases:

  1. Empty results (no classes)
  2. All classes being missing/other
  3. Invalid class types in results
 def get_confusion_matrices(self, results):
+    if not results.classes or len(results.classes) == 0:
+        raise ValueError("No classes found in results")
+
     default_classes = results.classes.tolist()
     freq = Counter(results.ytrue)
     if results.missing in freq:
         freq.pop(results.missing)
+    if not freq:
+        raise ValueError("All classes are missing/other")

329-330: Add type validation for missing state

Consider validating the type of results.missing before setting it as state to ensure consistent behavior across different result types.

-    ctx.panel.set_state("missing", results.missing)
+    missing = results.missing
+    if not isinstance(missing, (str, int)):
+        missing = str(missing)
+    ctx.panel.set_state("missing", missing)

481-545: Improve code structure for better maintainability

The detection view filtering logic is complex and could benefit from being split into smaller, focused methods. This would improve readability and maintainability.

Consider extracting the following methods:

def _filter_class_view(self, view, x, gt_field, pred_field, gt_field2=None, pred_field2=None):
    """Handle class-specific view filtering."""
    pass

def _filter_matrix_view(self, view, x, y, missing, eval_key, gt_field, pred_field):
    """Handle confusion matrix cell filtering."""
    pass

def _filter_field_view(self, view, field, eval_key, gt_field, pred_field):
    """Handle field-specific view filtering."""
    pass
🛑 Comments failed to post (1)
fiftyone/operators/builtins/panels/model_evaluation/__init__.py (1)

425-447: 🛠️ Refactor suggestion

Add evaluation compatibility validation

When comparing two evaluations, it's important to validate that they are compatible (same evaluation type, comparable metrics, etc.).

 eval_key2 = view_state.get("compareKey", None)
 pred_field2 = None
 gt_field2 = None
 if eval_key2 is not None:
     info2 = ctx.dataset.get_evaluation_info(eval_key2)
+    if info2.config.type != info.config.type:
+        raise ValueError(
+            f"Incompatible evaluation types: {info.config.type} vs {info2.config.type}"
+        )
     pred_field2 = info2.config.pred_field
     if info2.config.gt_field != gt_field:
         gt_field2 = info2.config.gt_field
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        view_options = ctx.params.get("options", {})

        eval_key = view_state.get("key")
        eval_key = view_options.get("key", eval_key)
        eval_view = ctx.dataset.load_evaluation_view(eval_key)
        info = ctx.dataset.get_evaluation_info(eval_key)
        pred_field = info.config.pred_field
        gt_field = info.config.gt_field

        eval_key2 = view_state.get("compareKey", None)
        pred_field2 = None
        gt_field2 = None
        if eval_key2 is not None:
            info2 = ctx.dataset.get_evaluation_info(eval_key2)
            if info2.config.type != info.config.type:
                raise ValueError(
                    f"Incompatible evaluation types: {info.config.type} vs {info2.config.type}"
                )
            pred_field2 = info2.config.pred_field
            if info2.config.gt_field != gt_field:
                gt_field2 = info2.config.gt_field

        x = view_options.get("x", None)
        y = view_options.get("y", None)
        field = view_options.get("field", None)
        missing = ctx.panel.get_state("missing", "(none)")

@brimoor brimoor force-pushed the model-eval-show-missing-none branch from 2a39e70 to 683a612 Compare December 15, 2024 06:40
@brimoor brimoor force-pushed the model-eval-show-missing-none branch from 683a612 to 3168e30 Compare December 15, 2024 06:41
Base automatically changed from model-eval-fixes2 to release/v1.2.0 December 18, 2024 04:22
imanjra
imanjra previously approved these changes Dec 19, 2024
Copy link
Contributor

@imanjra imanjra left a comment

Choose a reason for hiding this comment

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

LGTM

@brimoor brimoor marked this pull request as draft December 19, 2024 14:54
@brimoor
Copy link
Contributor Author

brimoor commented Dec 19, 2024

@imanjra there's a couple frontend TODO items in the PR description that will need to be addressed before we can merge this. Could you take a look??

@imanjra imanjra force-pushed the model-eval-show-missing-none branch from 6f5dc95 to 76a1492 Compare December 19, 2024 18:45
@imanjra imanjra marked this pull request as ready for review December 19, 2024 18:45
@imanjra imanjra force-pushed the model-eval-show-missing-none branch from 76a1492 to ba1ecf6 Compare December 19, 2024 18:46
imanjra
imanjra previously approved these changes Dec 19, 2024
Copy link
Contributor

@imanjra imanjra left a comment

Choose a reason for hiding this comment

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

LGTM

@imanjra imanjra force-pushed the model-eval-show-missing-none branch from ba1ecf6 to 325a0a0 Compare December 19, 2024 18:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Code enhancement
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants