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

Merging #4758 into develop #4895

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open

Merging #4758 into develop #4895

wants to merge 6 commits into from

Conversation

brimoor
Copy link
Contributor

@brimoor brimoor commented Oct 4, 2024

Merges #4758 into develop after adding these changes to preserve backwards-compatibility (sparse=False as default) and therefore ensuring that the compute_max_ious() and find_duplicates() methods continue to work.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced COCO and Open Images evaluation logic with improved Intersection over Union (IoU) calculations.
    • Added new classes for Open Images evaluation and orthographic projection metadata.
    • Introduced customizable parameters for 3D orthographic projections.
  • Bug Fixes

    • Improved error handling in 3D scene processing functions.
  • Tests

    • Added new unit tests for bounding box evaluations and 3D utilities, enhancing the testing framework.
  • Chores

    • Added new dependency rtree for improved functionality.

@brimoor brimoor added the enhancement Code enhancement label Oct 4, 2024
Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Walkthrough

The pull request introduces significant enhancements to the evaluation logic for COCO and Open Images datasets in the fiftyone library. Key modifications include the implementation of a sparse approach for Intersection over Union (IoU) calculations, improving the efficiency of IoU storage and computation. Additionally, new classes and methods are added to support these changes, along with updates to existing functions for better performance and clarity. The changes extend to unit tests, ensuring robust validation of the new functionalities.

Changes

File Path Change Summary
fiftyone/utils/eval/coco.py Updated _coco_evaluation_setup to compute IoUs using a sparse approach; refined comments; updated method signature.
fiftyone/utils/eval/openimages.py Enhanced IoU computation in _open_images_evaluation_setup with sparse approach; refined matching logic; added new classes.
fiftyone/utils/iou.py Added sparse parameter to multiple IoU functions; optimized IoU calculations using rtree spatial indexing; updated method signatures.
fiftyone/utils/utils3d.py Added OrthographicProjectionMetadata class; enhanced compute_orthographic_projection_images with new parameters; improved error handling.
setup.py Added rtree to INSTALL_REQUIRES.
tests/unittests/evaluation_tests.py Introduced BoxesTests class with tests for IoU computations and duplicate detection; modified existing test methods.
tests/unittests/utils3d_tests.py Added BoxTests class with a test for box vertex validation; included numpy.testing for assertions.

Possibly related PRs

  • Speed up evaluation with r-trees to find overlapping detections #4758: This PR modifies the _coco_evaluation_setup function in fiftyone/utils/eval/coco.py, which is directly related to the changes made in the main PR that also involves modifications to the COCO evaluation logic and IoU calculations.
  • Merge/main to develop #4439: This PR includes changes to the fiftyone/utils/eval/openimages.py file, which similarly updates the IoU computation method, indicating a related enhancement in evaluation logic across different datasets.
  • Cherry picking PRs into v0.24.1 #4455: This PR introduces significant enhancements to the fiftyone/utils/iou.py file, focusing on the computation of IoU metrics, which aligns with the changes in the main PR that also optimizes IoU calculations.
  • Speed up evaluation with r-trees to find overlapping detections #4758: This PR enhances the handling of input predictions and ground truths in the fiftyone/utils/iou.py module, which is relevant to the changes in the main PR that improve the efficiency of IoU calculations.
  • Fix COCO category IDs #4884: This PR addresses issues related to COCO category IDs and ensures that the classes parameter functions correctly when loading COCO datasets, which is relevant to the changes in the main PR that enhance COCO evaluation logic.

Suggested labels

bug

Suggested reviewers

  • findtopher
  • sashankaryal

Poem

In the fields of code, we hop and play,
With IoUs spry, we brighten the day.
Sparse and swift, our metrics now gleam,
Evaluations refined, like a rabbit's sweet dream.
So here’s to the changes, both big and small,
In the world of FiftyOne, we celebrate all! 🐇✨


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 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: 11

🧹 Outside diff range and nitpick comments (5)
tests/unittests/utils3d_tests.py (1)

393-401: LGTM: Good addition of unit test for _Box class.

The new BoxTests class provides a good starting point for testing the _Box class functionality. The test_box_vertices method correctly verifies that a default _Box instance generates the expected unit box vertices.

To improve test coverage, consider adding the following test cases:

  1. A box with non-unit scale
  2. A box with non-zero location
  3. A box with non-zero rotation
  4. A combination of scale, location, and rotation

These additional tests would ensure that the _Box class correctly handles various transformations.

tests/unittests/evaluation_tests.py (3)

1887-1910: Enhance assertions in test_compute_max_ious

While the test checks that the bounds are not None, it would be more robust to assert specific expected values or ranges for the IoU calculations.

Consider adding more specific assertions, such as:

self.assertGreaterEqual(bounds1[0], 0)
self.assertLessEqual(bounds1[1], 1)
self.assertGreaterEqual(bounds2[0], 0)
self.assertLessEqual(bounds2[1], 1)

This will ensure that the IoU values are within the expected range of [0, 1].


1911-1931: Enhance test_find_duplicates with more specific checks

The current test only checks the length of the returned duplicate IDs. To make the test more robust, consider adding the following improvements:

  1. Check that the returned IDs are actually present in the dataset.
  2. Verify that the duplicates have high IoU with each other.
  3. Test with different IoU thresholds to ensure the function behaves correctly.

Example additions:

# Check that returned IDs are in the dataset
self.assertTrue(all(id in dataset.values("ground_truth.detections.id") for id in dup_ids1))

# Test with different IoU thresholds
dup_ids_high = foui.find_duplicates(dataset, "ground_truth", iou_thresh=0.99, method="simple")
self.assertEqual(len(dup_ids_high), 0)  # Expect no duplicates with very high threshold

dup_ids_low = foui.find_duplicates(dataset, "ground_truth", iou_thresh=0.1, method="simple")
self.assertGreater(len(dup_ids_low), len(dup_ids1))  # Expect more duplicates with lower threshold

2024-2031: Improve error handling in _check_iou method

The modification to use foui.compute_ious is a good improvement. However, the error handling and checking could be enhanced:

  1. Add a check to ensure that ious is not empty before accessing its values.
  2. Use assertAlmostEqual for floating-point comparisons instead of assertTrue(np.isclose()).

Consider refactoring the method as follows:

def _check_iou(self, dataset, field1, field2, expected_iou):
    dets1 = dataset.first()[field1].detections
    dets2 = dataset.first()[field2].detections
    ious = foui.compute_ious(dets1, dets2, sparse=True)
    
    self.assertNotEqual(len(ious), 0, "No IoUs were computed")
    
    result = next(iter(ious.values()), [])
    
    if expected_iou == 0:
        self.assertEqual(len(result), 0, "Expected no overlap, but found some")
    else:
        self.assertGreater(len(result), 0, "Expected overlap, but found none")
        _, actual_iou = result[0]
        self.assertAlmostEqual(actual_iou, expected_iou, places=7, 
                               msg=f"IoU {actual_iou} does not match expected {expected_iou}")

This refactoring provides more informative error messages and uses more appropriate assertion methods.

fiftyone/utils/iou.py (1)

95-96: Avoid unnecessary dictionary comprehension when preds is empty

When preds is empty, the comprehension {p.id: [] for p in preds} returns an empty dictionary. Since preds can be empty, the check if preds else {} is redundant.

You can simplify the return statement:

-            return {p.id: [] for p in preds} if preds else {}
+            return {p.id: [] for p in preds}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 54ce128 and e7223af.

📒 Files selected for processing (7)
  • fiftyone/utils/eval/coco.py (1 hunks)
  • fiftyone/utils/eval/openimages.py (1 hunks)
  • fiftyone/utils/iou.py (11 hunks)
  • fiftyone/utils/utils3d.py (1 hunks)
  • setup.py (1 hunks)
  • tests/unittests/evaluation_tests.py (2 hunks)
  • tests/unittests/utils3d_tests.py (2 hunks)
🧰 Additional context used
🪛 Ruff
fiftyone/utils/iou.py

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

Rewrite iscrowd as a def

(E731)


100-100: Ambiguous variable name: l

(E741)


570-573: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


582-585: Use ternary operator gts = preds if is_symmetric else _polylines_to_detections(gts) instead of if-else-block

Replace if-else-block with gts = preds if is_symmetric else _polylines_to_detections(gts)

(SIM108)


637-640: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


705-708: Use ternary operator union = pred_area if gt_crowd else pred_area + gt_area - inter instead of if-else-block

Replace if-else-block with union = pred_area if gt_crowd else pred_area + gt_area - inter

(SIM108)


727-730: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


802-805: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


847-850: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)

🔇 Additional comments (7)
setup.py (1)

63-63: Approved: Addition of "rtree" to INSTALL_REQUIRES

The addition of "rtree" to the INSTALL_REQUIRES list is correctly placed alphabetically. This change ensures that the "rtree" package will be installed along with FiftyOne.

However, I have a few points for clarification:

  1. Could you please explain the necessity of adding "rtree" as a dependency? What new functionality in FiftyOne requires this package?

  2. The PR objectives mention preserving backwards compatibility and setting a default value for 'sparse', but don't mention adding "rtree". Could you clarify how this addition relates to the stated objectives?

  3. It would be helpful to update the PR description to include information about adding "rtree" as a new dependency, to ensure all changes are properly documented.

To verify the usage of "rtree" in the codebase, please run the following script:

This will help us understand where and how "rtree" is being used in the project.

✅ Verification successful

Verified: "rtree" is utilized in the codebase

The usage of "rtree" in fiftyone/utils/iou.py confirms the necessity of adding it to the INSTALL_REQUIRES list. This ensures that "rtree" will be properly installed with FiftyOne.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for "rtree" usage in Python files

# Test: Search for "rtree" imports or usage
rg --type python 'import\s+rtree|from\s+rtree\s+import|rtree\.'

Length of output: 96


Script:

#!/bin/bash
# Description: Search for "rtree" usage in Python files using correct file type

# Test: Search for "rtree" imports or usage in .py files
rg --type py 'import\s+rtree|from\s+rtree\s+import|rtree\.'

Length of output: 109

tests/unittests/utils3d_tests.py (1)

13-13: LGTM: Appropriate import for numpy testing.

The addition of import numpy.testing as nptest is appropriate for the new test case that compares numpy arrays.

tests/unittests/evaluation_tests.py (2)

1848-1886: New test class for bounding box operations

The BoxesTests class has been added to test bounding box-related operations. The _make_dataset method creates a small dataset with ground truth and prediction detections for testing purposes.


Line range hint 1848-2031: Overall improvement in bounding box and cuboid testing

The additions and modifications in this file enhance the test coverage for bounding box and cuboid operations in FiftyOne. The new BoxesTests class introduces valuable tests for IoU computations and duplicate detection. The changes in the CuboidTests class simplify IoU calculations by leveraging utility functions.

While these changes are positive, there are opportunities to further improve the robustness of the tests by:

  1. Adding more specific assertions in the BoxesTests class.
  2. Enhancing error handling and providing more informative error messages.
  3. Considering edge cases and different scenarios in the tests.

These improvements will help catch potential issues earlier and make the tests more maintainable in the long run.

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

530-532: Approved change to use sparse=True in compute_ious for performance optimization

The addition of sparse=True to the foui.compute_ious function call optimizes the computation of IoUs by utilizing a sparse matrix representation. This enhances performance when handling large numbers of detections without altering the existing matching logic or evaluation outcomes.

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

566-567: ⚠️ Potential issue

Verify the handling of IoU outputs with sparse=True.

Changing compute_ious to use sparse=True alters the format of the returned ious data structure. Ensure that all parts of the code that use pred_ious are updated to correctly handle the new format.

Run the following script to find usages of pred_ious and verify they handle the sparse format:

✅ Verification successful

IoU Output Handling with sparse=True Confirmed

All usages of pred_ious properly handle the sparse format as per the reviewed code snippets.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of `pred_ious` in the codebase to verify correct handling.

# Test: Search for `pred_ious` variable usages.
rg --type py -A 5 -B 5 'pred_ious'

# Additionally, search for other calls to `compute_ious` to check if the `sparse` parameter is consistently used.
rg --type py -A 2 -B 2 'compute_ious\('

Length of output: 15444


Script:

#!/bin/bash
# Description: Verify all accesses and manipulations of `pred_ious` to ensure they handle the sparse format correctly.

# Search for indexing of `pred_ious`
rg --type py 'pred_ious\['

# Search for iteration over `pred_ious`
rg --type py 'for .* in pred_ious'

# Search for method calls on `pred_ious`
rg --type py 'pred_ious\.\w+'

Length of output: 834

fiftyone/utils/utils3d.py (1)

170-170: LGTM!

The computation of self.vertices with the updated line correctly applies the rotation and translation to each vertex.

fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Outdated Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
fiftyone/utils/iou.py Outdated Show resolved Hide resolved
fiftyone/utils/iou.py Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (9)
fiftyone/utils/iou.py (7)

90-91: Fix typo in docstring

There's a minor typo in the return description of the compute_ious function.

Apply this diff to fix the typo:

-        a ``num_preds x num_gts`` array of IoUs when ``sparse=False`, or a dict
+        a ``num_preds x num_gts`` array of IoUs when ``sparse=False``, or a dict

175-177: Fix typo in docstring

There's a minor typo in the return description of the compute_segment_ious function.

Apply this diff to fix the typo:

-        a ``num_preds x num_gts`` array of segment IoUs when ``sparse=False`,
+        a ``num_preds x num_gts`` array of segment IoUs when ``sparse=False``,

561-621: LGTM: Efficient IoU calculation with R-tree and sparse output support

The updates to _compute_bbox_ious function, including the use of an R-tree spatial index and support for sparse output, significantly improve the efficiency of IoU calculations. The implementation is correct and consistent with the changes made to other functions.

Consider optimizing the sparse output case by avoiding the creation of zero-IoU entries:

 if sparse:
-    ious[pred.id].append((gt.id, iou))
+    if iou > 0:
+        ious[pred.id].append((gt.id, iou))
     if is_symmetric:
-        ious[gt.id].append((pred.id, iou))
+        if iou > 0:
+            ious[gt.id].append((pred.id, iou))

This optimization would reduce memory usage for sparse outputs with many zero-IoU pairs.

🧰 Tools
🪛 Ruff

570-573: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


582-585: Use ternary operator gts = preds if is_symmetric else _polylines_to_detections(gts) instead of if-else-block

Replace if-else-block with gts = preds if is_symmetric else _polylines_to_detections(gts)

(SIM108)


Line range hint 624-719: LGTM: Efficient polygon IoU calculation with R-tree and sparse output support

The updates to _compute_polygon_ious function, including the use of an R-tree spatial index and support for sparse output, significantly improve the efficiency of polygon IoU calculations. The implementation is correct and consistent with the changes made to other functions.

Consider applying the same optimization for the sparse output case as suggested for _compute_bbox_ious:

 if sparse:
-    ious[pred.id].append((gt.id, iou))
+    if iou > 0:
+        ious[pred.id].append((gt.id, iou))
     if is_symmetric:
-        ious[gt.id].append((pred.id, iou))
+        if iou > 0:
+            ious[gt.id].append((pred.id, iou))

This optimization would reduce memory usage for sparse outputs with many zero-IoU pairs.

🧰 Tools
🪛 Ruff

705-708: Use ternary operator union = pred_area if gt_crowd else pred_area + gt_area - inter instead of if-else-block

Replace if-else-block with union = pred_area if gt_crowd else pred_area + gt_area - inter

(SIM108)


727-730: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


724-753: LGTM: Polyline similarities with sparse output support

The updates to _compute_polyline_similarities function, including support for sparse output, are consistent with the changes made to other functions. The implementation is correct and maintains the overall structure of the codebase.

Consider applying the same optimization for the sparse output case as suggested for previous functions:

 if sparse:
-    sims[pred.id].append((gt.id, sim))
+    if sim > 0:
+        sims[pred.id].append((gt.id, sim))
     if is_symmetric:
-        sims[gt.id].append((pred.id, sim))
+        if sim > 0:
+            sims[gt.id].append((pred.id, sim))

This optimization would reduce memory usage for sparse outputs with many zero-similarity pairs.

🧰 Tools
🪛 Ruff

727-730: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


799-839: LGTM: Segment IoU computation with sparse output support

The updates to _compute_segment_ious function, including support for sparse output, are consistent with the changes made to other functions. The implementation is correct and maintains the overall structure of the codebase.

Consider applying the same optimization for the sparse output case as suggested for previous functions:

 if sparse:
-    ious[pred.id].append((gt.id, iou))
+    if iou > 0:
+        ious[pred.id].append((gt.id, iou))
     if is_symmetric:
-        ious[gt.id].append((pred.id, iou))
+        if iou > 0:
+            ious[gt.id].append((pred.id, iou))

This optimization would reduce memory usage for sparse outputs with many zero-IoU pairs.

🧰 Tools
🪛 Ruff

802-805: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


844-873: LGTM: Keypoint similarities with sparse output support

The updates to _compute_keypoint_similarities function, including support for sparse output, are consistent with the changes made to other functions. The implementation is correct and maintains the overall structure of the codebase.

Consider applying the same optimization for the sparse output case as suggested for previous functions:

 if sparse:
-    sims[pred.id].append((gt.id, sim))
+    if sim > 0:
+        sims[pred.id].append((gt.id, sim))
     if is_symmetric:
-        sims[gt.id].append((pred.id, sim))
+        if sim > 0:
+            sims[gt.id].append((pred.id, sim))

This optimization would reduce memory usage for sparse outputs with many zero-similarity pairs.

🧰 Tools
🪛 Ruff

847-850: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)

tests/unittests/evaluation_tests.py (2)

1887-1909: Enhance IoU computation test assertions

While the test checks for non-None bounds, consider adding more specific assertions to verify the correctness of the IoU computation. For example, you could add assertions to check if the IoU values are within the expected range (0 to 1) or compare them against pre-calculated expected values for the given bounding boxes.


1911-1930: Enhance duplicate detection test

Consider the following improvements to the test_find_duplicates method:

  1. Add assertions to check the specific duplicate IDs returned, not just the count.
  2. Include test cases with no duplicates and with multiple duplicates to ensure the function works correctly in various scenarios.
  3. Verify that the duplicates found are actually duplicates by comparing their bounding boxes or IoU values.

These enhancements will provide more comprehensive coverage of the find_duplicates function's behavior.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e7223af and b0b93e8.

📒 Files selected for processing (2)
  • fiftyone/utils/iou.py (11 hunks)
  • tests/unittests/evaluation_tests.py (2 hunks)
🧰 Additional context used
🪛 Ruff
fiftyone/utils/iou.py

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

Rewrite iscrowd as a def

(E731)


100-100: Ambiguous variable name: l

(E741)


570-573: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


582-585: Use ternary operator gts = preds if is_symmetric else _polylines_to_detections(gts) instead of if-else-block

Replace if-else-block with gts = preds if is_symmetric else _polylines_to_detections(gts)

(SIM108)


637-640: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


705-708: Use ternary operator union = pred_area if gt_crowd else pred_area + gt_area - inter instead of if-else-block

Replace if-else-block with union = pred_area if gt_crowd else pred_area + gt_area - inter

(SIM108)


727-730: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


802-805: Use ternary operator ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with ious = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)


847-850: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)

🔇 Additional comments (7)
fiftyone/utils/iou.py (5)

38-38: LGTM: New sparse parameter implementation

The addition of the sparse parameter and its implementation for handling empty input cases looks good. It provides a flexible way to return IoU results either as a full matrix or a sparse dictionary.

Also applies to: 77-78, 94-97


105-109: LGTM: Consistent implementation of sparse parameter

The sparse parameter has been correctly added to all relevant function calls within compute_ious. This ensures consistent behavior across different types of IoU computations.

Also applies to: 114-119, 122-127, 130-135, 150-150, 153-159


162-162: LGTM: Sparse parameter implementation in compute_segment_ious

The addition of the sparse parameter to the compute_segment_ious function and its implementation for handling empty input cases looks good. It maintains consistency with the changes made to other functions.

Also applies to: 171-172, 180-183


530-550: LGTM: New helper functions for bounding box extraction

The new helper functions _get_detection_box and _get_poly_box provide a clean and efficient way to handle both 2D and 3D bounding boxes. The implementation looks good and should improve code readability and maintainability.

Also applies to: 553-559


Line range hint 759-795: LGTM: Mask IoU computation with sparse parameter

The update to _compute_mask_ious function to include the sparse parameter is correct and consistent with the changes made to other functions in the file. This maintains the overall structure and functionality of the codebase.

🧰 Tools
🪛 Ruff

705-708: Use ternary operator union = pred_area if gt_crowd else pred_area + gt_area - inter instead of if-else-block

Replace if-else-block with union = pred_area if gt_crowd else pred_area + gt_area - inter

(SIM108)


727-730: Use ternary operator sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts))) instead of if-else-block

Replace if-else-block with sims = defaultdict(list) if sparse else np.zeros((len(preds), len(gts)))

(SIM108)

tests/unittests/evaluation_tests.py (2)

1849-1885: Well-structured dataset creation method

The _make_dataset method is well-implemented, creating a suitable dataset for testing with appropriate use of FiftyOne classes and structures.


Line range hint 1-2031: Overall assessment of changes

The additions and modifications to the tests/unittests/evaluation_tests.py file enhance the test coverage for bounding box operations and IoU computations. The new BoxesTests class provides valuable tests for max IoU computation and duplicate detection. However, there are opportunities to improve the robustness and comprehensiveness of these tests:

  1. In test_compute_max_ious, consider adding more specific assertions for IoU values.
  2. In test_find_duplicates, expand the test cases and verify the actual duplicate detections.
  3. In the modified _check_iou method of CuboidTests, add error handling for potential edge cases in IoU retrieval.

Implementing these suggestions will further strengthen the test suite and increase confidence in the correctness of the bounding box and IoU-related functionality.

fiftyone/utils/iou.py Outdated Show resolved Hide resolved
tests/unittests/evaluation_tests.py Show resolved Hide resolved
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.

1 participant