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

Support adding custom metrics to existing evaluations #5436

Merged
merged 2 commits into from
Jan 28, 2025

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Jan 25, 2025

Change log

  • Custom metrics can now be added to existing evaluations via a new results.add_custom_metrics() method

Example usage

# Install the example metrics plugin
fiftyone plugins download \
    https://github.com/voxel51/fiftyone-plugins \
    --plugin-names @voxel51/metric-examples
import random
import numpy as np

import fiftyone as fo
import fiftyone.zoo as foz

dataset = foz.load_zoo_dataset("cifar10", split="test")
dataset.delete_sample_field("ground_truth")

for idx, sample in enumerate(dataset.iter_samples(autosave=True, progress=True), 1):
    ytrue = random.random() * idx
    ypred = ytrue + np.random.randn() * np.sqrt(ytrue)
    confidence = random.random()
    sample["ground_truth"] = fo.Regression(value=ytrue)
    sample["predictions"] = fo.Regression(value=ypred, confidence=confidence)

results = dataset.evaluate_regressions(
    "predictions",
    gt_field="ground_truth",
    eval_key="eval",
)

Later in another session:

import fiftyone as fo

dataset = fo.load_dataset("cifar10-test")
results = dataset.load_evaluation_results("eval")

results.add_custom_metrics(
    [
        "@voxel51/metric-examples/absolute_error",
        "@voxel51/metric-examples/squared_error",
    ]
)

print(dataset.bounds("eval_absolute_error"))
print(dataset.bounds("eval_squared_error"))

results.print_metrics()

dataset.delete_evaluation("eval")

assert not dataset.has_field("eval_absolute_error")
assert not dataset.has_field("eval_squared_error")

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced model evaluation capabilities with support for custom metrics.
    • Added ability to dynamically add custom metrics to existing evaluations.
  • Documentation

    • Updated user guide with comprehensive details on model evaluation techniques.
    • Expanded documentation on custom metrics implementation and usage.
  • Improvements

    • Introduced more flexible evaluation methods for regressions, classifications, detections, and segmentations.
    • Improved metric filtering and management during model evaluations.

These updates provide users with greater control and customization options when evaluating machine learning models in FiftyOne.

@brimoor brimoor added the feature Work on a feature request label Jan 25, 2025
Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

Walkthrough

This pull request introduces enhancements to FiftyOne's model evaluation framework, focusing on expanding custom metrics functionality. The changes allow users to add and apply custom metrics across different model evaluation types (regressions, classifications, detections, segmentations). The documentation in docs/source/user_guide/evaluation.rst is updated to provide comprehensive guidance on implementing and using these custom metrics, emphasizing the platform's flexibility in model evaluation processes.

Changes

File Change Summary
docs/source/user_guide/evaluation.rst Added documentation on custom metrics, evaluation methods, and new metric integration techniques
fiftyone/core/collections.py Updated evaluation method signatures to support optional custom_metrics parameter
fiftyone/utils/eval/base.py Added add_custom_metrics() method, enhanced custom metric handling with metric_uris filtering

Sequence Diagram

sequenceDiagram
    participant User
    participant SampleCollection
    participant EvaluationResults
    participant CustomMetrics

    User->>SampleCollection: evaluate_regressions(predictions, gt_field, eval_key, custom_metrics)
    SampleCollection->>EvaluationResults: Compute Evaluation
    EvaluationResults->>CustomMetrics: Add and Process Custom Metrics
    CustomMetrics-->>EvaluationResults: Return Metric Results
    EvaluationResults-->>User: Evaluation Results with Custom Metrics
Loading

Possibly related PRs

Suggested labels

enhancement, documentation

Suggested reviewers

  • manushreegangwar
  • imanjra

Poem

🐰 Metrics dance, custom and bright
In FiftyOne's evaluation light
Flexible code, a rabbit's delight
Evaluations soar to new height
With metrics that shine so right! 🔍

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 (3)
fiftyone/utils/eval/base.py (3)

31-32: Add input validation for custom_metrics parameter.

Consider adding type validation to ensure custom_metrics is either a list or dict when provided. This would help catch configuration errors early.

 def __init__(self, custom_metrics=None, **kwargs):
+    if custom_metrics is not None and not isinstance(custom_metrics, (list, dict)):
+        raise ValueError("custom_metrics must be a list or dict")
     self.custom_metrics = custom_metrics
     super().__init__(**kwargs)

Line range hint 63-93: Enhance error handling in compute_custom_metrics.

While the method handles errors gracefully, consider:

  1. Including the operator URI in the error context
  2. Adding debug logging for successful computations
  3. Potentially raising an exception if too many metrics fail
     for metric, kwargs in custom_metrics.items():
+        success = False
         try:
             operator = foo.get_operator(metric)
             value = operator.compute(samples, results, **kwargs or {})
             if value is not None:
                 if results.custom_metrics is None:
                     results.custom_metrics = {}

                 key = operator.config.aggregate_key
                 if key is None:
                     key = operator.config.name

                 results.custom_metrics[operator.uri] = {
                     "key": key,
                     "value": value,
                     "label": operator.config.label,
                     "lower_is_better": operator.config.kwargs.get(
                         "lower_is_better", True
                     ),
                 }
+                success = True
+                logger.debug("Successfully computed metric '%s'", metric)
         except Exception as e:
             logger.warning(
-                "Failed to compute metric '%s': Reason: %s",
-                metric,
+                "Failed to compute metric '%s' (uri: %s): Reason: %s",
+                operator.config.name if 'operator' in locals() else 'unknown',
+                metric,
                 e,
             )
+        if not success:
+            results.failed_metrics = results.get("failed_metrics", 0) + 1
+            if results.failed_metrics > len(custom_metrics) // 2:
+                raise ValueError(f"Too many metrics failed to compute ({results.failed_metrics})")

164-206: LGTM! Well-structured implementation with proper error handling.

The implementation is thorough and handles edge cases well. The save_config() call before computation ensures proper cleanup even if computation fails.

Consider adding a docstring example to demonstrate the usage with both list and dict formats.

     """Computes the given custom metrics and adds them to these results.

     Args:
         custom_metrics: a list of custom metrics to compute or a dict
             mapping metric names to kwargs dicts
         overwrite (True): whether to recompute any custom metrics that
             have already been applied
+
+    Example:
+        # Using a list
+        results.add_custom_metrics(["metric1", "metric2"])
+
+        # Using a dict with kwargs
+        results.add_custom_metrics({
+            "metric1": {"threshold": 0.5},
+            "metric2": {"min_value": 10}
+        })
     """
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7b6459 and 91e7618.

📒 Files selected for processing (1)
  • fiftyone/utils/eval/base.py (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • 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: test / test-app
  • GitHub Check: e2e / test-e2e
  • GitHub Check: lint / eslint
  • GitHub Check: build / build
  • GitHub Check: build
🔇 Additional comments (1)
fiftyone/utils/eval/base.py (1)

47-61: LGTM! Clean implementation of metrics filtering.

The method efficiently handles both list and dict formats while providing URI-based filtering capability.

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 185d6b8 into develop Jan 28, 2025
14 checks passed
@brimoor brimoor deleted the add-custom-metrics branch January 28, 2025 17:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Work on a feature request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants