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

Fix confidence handling for keypoint evaluation #5344

Merged
merged 1 commit into from
Jan 7, 2025

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Jan 6, 2025

Change log

  • Fixes a bug where evaluate_detections() would fail when applied to Keypoints fields
    • The reason was that confidence is a list, not a scalar, for keypoints

Example usage

import numpy as np

import fiftyone as fo
import fiftyone.zoo as foz
from fiftyone import ViewField as F

dataset = foz.load_zoo_dataset(
    "coco-2017",
    split="validation",
    label_types="detections",
    classes=["person"],
    max_samples=10,
    only_matching=True,
)

model = foz.load_zoo_model("keypoint-rcnn-resnet50-fpn-coco-torch")
dataset.default_skeleton = model.skeleton

dataset.apply_model(model, label_field="gt")

dataset.clone_sample_field("gt_keypoints", "pred_keypoints")

for sample in dataset.iter_samples(autosave=True):
    for keypoint in sample.pred_keypoints.keypoints:
        points = np.array(keypoint.points)
        points += 0.02 * np.random.randn(*points.shape)
        keypoint.points = points.tolist()

# Previously failed; now successfully completes!
results = dataset.evaluate_detections(
    "pred_keypoints",
    gt_field="gt_keypoints",
    eval_key="eval",
)

results.print_report()

# Open Model Evaluation panel and verify that everything loads correctly
session = fo.launch_app(dataset)

Summary by CodeRabbit

  • New Features

    • Enhanced support for keypoint-based object detection evaluations
    • Improved confidence calculation for keypoint predictions
  • Bug Fixes

    • Fixed handling of confidence values for different prediction types
    • Resolved potential issues with NaN confidence values during evaluation
  • Improvements

    • Updated sorting and matching logic for keypoint predictions
    • More robust evaluation process for object detection metrics

Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Walkthrough

The pull request introduces modifications to the evaluation utilities in FiftyOne, specifically focusing on enhancing the handling of predicted objects, particularly keypoints, in COCO and OpenImages evaluation processes. The changes primarily involve updating the sorting and confidence calculation logic to accommodate fol.Keypoints instances. The modifications ensure more robust evaluation by introducing conditional logic that handles different types of predictions, particularly focusing on how confidence values are computed and used during the matching and sorting phases of the evaluation.

Changes

File Change Summary
fiftyone/utils/eval/coco.py - Added import for fiftyone.core.labels
- Updated _coco_evaluation_setup to handle keypoints sorting
- Modified _compute_matches to calculate confidence for keypoints using np.nanmean()
fiftyone/utils/eval/openimages.py - Added import for fiftyone.core.labels
- Updated evaluation logic to handle keypoints in sorting and matching
- Introduced conditional confidence calculation for different prediction types

Sequence Diagram

sequenceDiagram
    participant Evaluator
    participant Predictions
    participant MatchingLogic
    
    Evaluator->>Predictions: Sort predictions
    alt Is Keypoints
        Predictions-->>Evaluator: Sort by mean keypoint confidence
    else Regular Predictions
        Predictions-->>Evaluator: Sort by prediction confidence
    end
    
    Evaluator->>MatchingLogic: Compute matches
    alt Is Keypoints
        MatchingLogic-->>Evaluator: Use np.nanmean(confidence)
    else Regular Predictions
        MatchingLogic-->>Evaluator: Use direct confidence
    end
Loading

Possibly related PRs

Poem

🐰 Hopping through code with glee and might,
Keypoints dancing in evaluation's light
Confidence calculated, NaNs swept away
Matching logic leaps into a brighter day
A rabbit's code, precise and bright! 🔍


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.

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.

Actionable comments posted: 0

🧹 Nitpick comments (2)
fiftyone/utils/eval/coco.py (1)

556-560: Consider replacing lambda with a regular function
Per static analysis suggestions, defining a named function is often considered more readable and debuggable than assigning a lambda.

-if isinstance(preds, fol.Keypoints):
-    sort_key = lambda p: np.nanmean(p.confidence) if p.confidence else -1
-else:
-    sort_key = lambda p: p.confidence or -1
+def _sort_key_for_keypoints(p):
+    return np.nanmean(p.confidence) if p.confidence else -1

+def _sort_key_for_detections(p):
+    return p.confidence or -1

if isinstance(preds, fol.Keypoints):
    sort_key = _sort_key_for_keypoints
else:
    sort_key = _sort_key_for_detections
🧰 Tools
🪛 Ruff (0.8.2)

557-557: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)


559-559: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)

fiftyone/utils/eval/openimages.py (1)

549-553: Consider replacing lambda with a regular function
Replacing the lambda definitions with named functions can improve readability, as recommended by static analysis.

-if isinstance(preds, fol.Keypoints):
-    sort_key = lambda p: np.nanmean(p.confidence) if p.confidence else -1
-else:
-    sort_key = lambda p: p.confidence or -1
+def _sort_key_for_keypoints(p):
+    return np.nanmean(p.confidence) if p.confidence else -1

+def _sort_key_for_detections(p):
+    return p.confidence or -1

if isinstance(preds, fol.Keypoints):
    sort_key = _sort_key_for_keypoints
else:
    sort_key = _sort_key_for_detections
🧰 Tools
🪛 Ruff (0.8.2)

550-550: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)


552-552: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 199872a and e37e4fd.

📒 Files selected for processing (2)
  • fiftyone/utils/eval/coco.py (6 hunks)
  • fiftyone/utils/eval/openimages.py (5 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
fiftyone/utils/eval/openimages.py

550-550: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)


552-552: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)

fiftyone/utils/eval/coco.py

557-557: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)


559-559: Do not assign a lambda expression, use a def

Rewrite sort_key as a def

(E731)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.11)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.10)
  • GitHub Check: test / test-python (ubuntu-latest-m, 3.9)
  • GitHub Check: e2e / test-e2e
  • GitHub Check: build
🔇 Additional comments (12)
fiftyone/utils/eval/coco.py (6)

16-16: Import added for keypoint handling
This import allows proper recognition of Keypoints for COCO evaluation.


568-568: Sorting predictions by confidence
Sorting by descending confidence is a necessary step for COCO-style matching and looks correct.


596-602: Keypoint confidence logic
Using np.nanmean for Keypoint confidences is an effective approach to handle multiple values. The rest of the fallback logic seems correct.


654-654: Recording prediction confidence in match
Including pred_conf in the stored match data is correct and ensures consistent calculations.


667-667: Recording unmatched object as false positive
Keeping pred_conf in the appended match record clarifies the final confidence used, which is good for debugging.


681-681: Recording false positive for unmatched predictions
This line correctly saves pred_conf alongside the unmatched prediction label.

fiftyone/utils/eval/openimages.py (6)

13-13: Import added for keypoint handling
This import line matches the changes needed to properly process Keypoints.


561-561: Sorting predictions
Sorting in descending confidence is essential for the matching approach and is correctly implemented.


592-598: Handling Keypoint vs detection confidences
Averaging multiple keypoint confidences with np.nanmean ensures robust evaluation. The fallback for regular detections is consistent.


683-683: Storing confidence in crowd or matched scenario
Preserves pred_conf in the matches for further reporting, which is beneficial for debugging.


695-695: Unmatched prediction labeled false positive
Recording the pred_conf for unsuccessful matches is valuable for deeper analysis.


703-703: Persisting confidence for leftover predictions
Maintaining pred_conf in the final data ensures consistent logging of confidence values for unmatched objects.

Copy link
Contributor

@manushreegangwar manushreegangwar 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 merged commit 3096e0a into develop Jan 7, 2025
14 checks passed
@brimoor brimoor deleted the bugfix/keypoint-evaluation branch January 7, 2025 14:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Bug fixes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants