Spaces:
Runtime error
Runtime error
Download src/data/samplers.py from mshaiel2004/dr-severity-grading: direct link, hf CLI and curl.
- Browser
- Download file 1.41 kB
-
https://huggingface.co/spaces/mshaiel2004/dr-severity-grading/resolve/main/src/data/samplers.py
- Command line
-
hf download hf://spaces/mshaiel2004/dr-severity-grading/src/data/samplers.py
-
curl -L -o samplers.py https://huggingface.co/spaces/mshaiel2004/dr-severity-grading/resolve/main/src/data/samplers.py
1.41 kB
| """Sampling utilities for handling severe class imbalance in medical datasets.""" | |
| from typing import Sequence | |
| import numpy as np | |
| import torch | |
| from torch.utils.data import WeightedRandomSampler | |
| def create_weighted_sampler(labels: Sequence[int], num_samples: int = None) -> WeightedRandomSampler: | |
| """Create a WeightedRandomSampler that inverts class frequencies. | |
| Args: | |
| labels: Sequence of integer class labels for the training set. | |
| num_samples: Total number of samples to draw per epoch. | |
| Defaults to len(labels). | |
| Returns: | |
| Configured PyTorch WeightedRandomSampler. | |
| """ | |
| labels_arr = np.array(labels, dtype=np.int64) | |
| unique_classes, counts = np.unique(labels_arr, return_counts=True) | |
| class_to_count = dict(zip(unique_classes, counts)) | |
| total = len(labels_arr) | |
| # Weight per class = total / (num_classes * count) | |
| class_weights = { | |
| cls: total / (len(unique_classes) * cnt) for cls, cnt in class_to_count.items() | |
| } | |
| # Weight per individual sample | |
| sample_weights = np.array([class_weights[y] for y in labels_arr], dtype=np.float64) | |
| sample_weights_tensor = torch.from_numpy(sample_weights).double() | |
| if num_samples is None: | |
| num_samples = len(labels_arr) | |
| return WeightedRandomSampler( | |
| weights=sample_weights_tensor, | |
| num_samples=num_samples, | |
| replacement=True, | |
| ) | |