Fix class_weights background voxel calculation to use actual data volume sizes#68
Closed
Fix class_weights background voxel calculation to use actual data volume sizes#68
Conversation
Merged
…lass_weights Co-authored-by: rhoadesScholar <37990507+rhoadesScholar@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] [WIP] Address feedback on total_voxels calculation
Fix class_weights background voxel calculation to use actual data volume sizes
Mar 13, 2026
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## rewrite #68 +/- ##
===========================================
- Coverage 80.84% 79.73% -1.12%
===========================================
Files 23 23
Lines 1535 1564 +29
===========================================
+ Hits 1241 1247 +6
- Misses 294 317 +23 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Contributor
There was a problem hiding this comment.
Pull request overview
Fixes CellMapMultiDataset.class_weights background voxel computation by using true per-class volume sizes (total_voxels - fg) rather than “other classes’ foreground”.
Changes:
- Add
total_voxelstoCellMapImage(s0 spatial shape → voxel count, scaled to training resolution) andEmptyImage(0). - Add
CellMapDataset.total_voxelsaggregation across target sources. - Update
CellMapMultiDataset.class_weightsto computebg = max(total - fg, 0)and warn whenfg > total.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| src/cellmap_data/multidataset.py | Recomputes class weights using aggregated per-class total voxels and corrected background calculation. |
| src/cellmap_data/image.py | Introduces CellMapImage.total_voxels derived from s0 spatial shape and scaled to training resolution. |
| src/cellmap_data/empty_image.py | Adds EmptyImage.total_voxels = 0 for unannotated placeholders. |
| src/cellmap_data/dataset.py | Adds per-class CellMapDataset.total_voxels mapping from target sources. |
Comment on lines
+556
to
+565
| @property | ||
| def total_voxels(self) -> int: | ||
| """Total number of voxels in the s0 data volume, normalised to training-resolution voxels.""" | ||
| try: | ||
| s0_path = self._level_info[0][0] | ||
| s0_arr = zarr.open_array(f"{self.path}/{s0_path}", mode="r") | ||
| n_spatial = len(self.axes) | ||
| spatial_shape = s0_arr.shape[-n_spatial:] | ||
| s0_total = int(np.prod(spatial_shape)) | ||
| return self._scale_count(s0_total, s0_idx=0) |
Comment on lines
+76
to
+81
| fg_counts = self.class_counts["totals"] | ||
| # Aggregate actual total voxels per class across all datasets | ||
| total_voxels: dict[str, int] = {cls: 0 for cls in self.classes} | ||
| for ds in self.datasets: | ||
| ds_total = ds.total_voxels | ||
| for cls in self.classes: |
Comment on lines
70
to
97
| def class_weights(self) -> dict[str, float]: | ||
| """Per-class sampling weight: ``bg_voxels / fg_voxels``.""" | ||
| counts = self.class_counts["totals"] | ||
| total_voxels = sum(counts.values()) | ||
| """Per-class sampling weight: ``bg_voxels / fg_voxels``. | ||
|
|
||
| Background voxels are computed as the total voxels in the data volume | ||
| minus the foreground voxels for each class. | ||
| """ | ||
| fg_counts = self.class_counts["totals"] | ||
| # Aggregate actual total voxels per class across all datasets | ||
| total_voxels: dict[str, int] = {cls: 0 for cls in self.classes} | ||
| for ds in self.datasets: | ||
| ds_total = ds.total_voxels | ||
| for cls in self.classes: | ||
| total_voxels[cls] += ds_total.get(cls, 0) | ||
| weights: dict[str, float] = {} | ||
| for cls in self.classes: | ||
| fg = counts.get(cls, 0) | ||
| bg = total_voxels - fg | ||
| fg = fg_counts.get(cls, 0) | ||
| total = total_voxels.get(cls, 0) | ||
| if fg > total > 0: | ||
| logger.warning( | ||
| "class_weights: fg (%d) > total_voxels (%d) for class %r; " | ||
| "this may indicate a counting error upstream.", | ||
| fg, | ||
| total, | ||
| cls, | ||
| ) | ||
| bg = max(total - fg, 0) | ||
| weights[cls] = float(bg) / float(max(fg, 1)) | ||
| return weights |
Comment on lines
+424
to
+428
| """Total voxels in the data volume per class, normalised to training-resolution voxels.""" | ||
| totals: dict[str, int] = {} | ||
| for cls in self.classes: | ||
| src = self.target_sources.get(cls) | ||
| totals[cls] = src.total_voxels if src is not None else 0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
class_weightswas computing background assum(all_fg_counts) - fg_class, which is semantically wrong — that's "other classes' foreground", not background. True background requirestotal_voxels_in_volume - fg_class.Changes
CellMapImage.total_voxels: New property reading the s0 array's spatial shape, computingnp.prod(spatial_shape), scaled to training resolution via the existing_scale_counthelperEmptyImage.total_voxels: Returns 0 (no annotated data)CellMapDataset.total_voxels: Aggregates per-classtotal_voxelsfrom each class's target sourceCellMapMultiDataset.class_weights: Aggregates actualtotal_voxelsacross all datasets per class; computesbg = total - fg. Adds a warning log whenfg > total_voxelsto surface upstream counting inconsistencies💬 Send tasks to Copilot coding agent from Slack and Teams to turn conversations into code. Copilot posts an update in your thread when it's finished.