⚡️ Speed up method MeanAveragePrecision._match_detection_batch
by 16%
#45
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.
📄 16% (0.16x) speedup for
MeanAveragePrecision._match_detection_batch
insupervision/metrics/mean_average_precision.py
⏱️ Runtime :
14.6 milliseconds
→12.6 milliseconds
(best of161
runs)📝 Explanation and details
o3-mini
We replace the repeated use of np.where and np.stack/hstack with np.nonzero to obtain the target and prediction indices directly. We also inline some intermediate arrays and avoid unnecessary array stacking. This simplifies the loop (though it still loops over thresholds) and removes some overhead in the inner loop. The logic remains the same so that each function return value is identical.
Below is the optimized version:
Explanation of the changes made:
• Instead of using np.where to obtain a tuple and then stacking the resulting arrays, we use np.nonzero to get target and prediction indices directly.
• We compute the valid mask for each threshold once and then sort the matches by their iou values in descending order.
• We then use np.unique on the prediction indices (and then on the target indices) to remove duplicate matches.
• This avoids repeated array creation (via stacking) and improves the run‐time.
✅ Correctness verification report:
🌀 Generated Regression Tests Details