Update metrics.py: Make n_true and n_pred computation more generic for mask Labels #1080
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description:
The original implementation for calculating n_true and n_pred was based on using np.max, which assumes that the mask labels always start from 1 and are consecutive. This implementation can fail in cases where the labels start from an arbitrary number (e.g., 5, 6, 7...) or are cropped, leading to incorrect counts.
To address this, the code has been updated to use np.unique. The new approach ensures that the calculation of the number of unique labels in each mask is robust and independent of the starting value of the labels. Subtracting 1 accounts for the background label (assumed to be 0).
Changes Made:
Replaced the np.max approach with len(np.unique(mask)) - 1 to count the number of unique labels in each mask, excluding the background label.
Used a list comprehension to ensure this works for all elements in masks_true and masks_pred.
Benefits:
Robustness: The new implementation works regardless of the starting value of the labels or whether they are consecutive.
Generality: It ensures consistent behavior for cropped images or cases with arbitrary label ranges.
Correctness: Avoids errors caused by relying on np.max when the labels are not consecutive.
Example:
Original Code:
Updated Code:
This refactor ensures that the calculation of n_true and n_pred is accurate and adaptable to a variety of label formats.