Skip to content

Update metrics.py: Make n_true and n_pred computation more generic for mask Labels#1080

Merged
mrariden merged 1 commit intoMouseLand:mainfrom
KevinCortacero:KevinCortacero-patch-1
May 8, 2025
Merged

Update metrics.py: Make n_true and n_pred computation more generic for mask Labels#1080
mrariden merged 1 commit intoMouseLand:mainfrom
KevinCortacero:KevinCortacero-patch-1

Conversation

@KevinCortacero
Copy link
Copy Markdown

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:

masks_true = [np.array([0, 1, 2, 3]), np.array([0, 4, 5, 6])]
n_true = np.array(list(map(np.max, masks_true)))  # Incorrectly assumes max gives count
print(n_true)  # Output: [3, 6]

Updated Code:

masks_true = [np.array([0, 1, 2, 3]), np.array([0, 4, 5, 6])]
n_true = np.array([len(np.unique(mask)) - 1 for mask in masks_true])
print(n_true)  # Output: [3, 3]

This refactor ensures that the calculation of n_true and n_pred is accurate and adaptable to a variety of label formats.

@KevinCortacero KevinCortacero changed the title Update metrics.py Update metrics.py: Make n_true and n_pred computation more generic for mask Labels Dec 23, 2024
@mrariden mrariden self-assigned this May 7, 2025
@mrariden mrariden merged commit e8637d5 into MouseLand:main May 8, 2025
@KevinCortacero KevinCortacero deleted the KevinCortacero-patch-1 branch May 9, 2025 08:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants