-
Notifications
You must be signed in to change notification settings - Fork 132
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use torchmetrics to calculate map #99
Draft
vlaminckaxel
wants to merge
7
commits into
MultimediaTechLab:main
Choose a base branch
from
vlaminckaxel:feature/torchmetrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
03178fc
➖ ➕ Remove pycocotools and add torchmetrics
vlaminckaxel 1588fe3
🔒️ only load weights
vlaminckaxel 6e7a85e
✨ implement torchmetrics in ModelValidator
vlaminckaxel 384d552
🔥 remove map test code
vlaminckaxel e0e86be
✅ Remove image_paths from tests
vlaminckaxel cd6e83a
✅ Update validator test
vlaminckaxel c3b8a31
🐛 remove dataset config from validator
vlaminckaxel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ loguru | |
numpy | ||
opencv-python | ||
Pillow | ||
pycocotools | ||
torchmetrics | ||
requests | ||
rich | ||
torch | ||
|
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -134,16 +134,16 @@ def load_valid_labels(self, label_path: str, seg_data_one_img: list) -> Union[Te | |
def get_data(self, idx): | ||
img_path, bboxes = self.data[idx] | ||
img = Image.open(img_path).convert("RGB") | ||
return img, bboxes, img_path | ||
return img, bboxes | ||
|
||
def get_more_data(self, num: int = 1): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could you add return types please? |
||
indices = torch.randint(0, len(self), (num,)) | ||
return [self.get_data(idx)[:2] for idx in indices] | ||
return [self.get_data(idx) for idx in indices] | ||
|
||
def __getitem__(self, idx) -> Tuple[Image.Image, Tensor, Tensor, List[str]]: | ||
img, bboxes, img_path = self.get_data(idx) | ||
img, bboxes = self.get_data(idx) | ||
img, bboxes, rev_tensor = self.transform(img, bboxes) | ||
return img, bboxes, rev_tensor, img_path | ||
return img, bboxes, rev_tensor | ||
|
||
def __len__(self) -> int: | ||
return len(self.data) | ||
|
@@ -189,11 +189,11 @@ def collate_fn(self, batch: List[Tuple[Tensor, Tensor]]) -> Tuple[Tensor, List[T | |
batch_targets[idx, : min(target_size, 100)] = batch[idx][1][:100] | ||
batch_targets[:, :, 1:] *= self.image_size | ||
|
||
batch_images, _, batch_reverse, batch_path = zip(*batch) | ||
batch_images, _, batch_reverse = zip(*batch) | ||
batch_images = torch.stack(batch_images) | ||
batch_reverse = torch.stack(batch_reverse) | ||
|
||
return batch_size, batch_images, batch_targets, batch_reverse, batch_path | ||
return batch_size, batch_images, batch_targets, batch_reverse | ||
|
||
|
||
def create_dataloader(data_cfg: DataConfig, dataset_cfg: DatasetConfig, task: str = "train", use_ddp: bool = False): | ||
|
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -227,7 +227,19 @@ def __call__(self, target: Tensor, predict: Tuple[Tensor]) -> Tuple[Tensor, Tens | |||||
2. Select the targets | ||||||
2. Noramlize the class probilities of targets | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
""" | ||||||
|
||||||
predict_cls, predict_bbox = predict | ||||||
|
||||||
# return if target has no gt information. | ||||||
n_targets = target.shape[1] | ||||||
if n_targets == 0: | ||||||
device = predict_bbox.device | ||||||
align_cls = torch.zeros_like(predict_cls, device=device) | ||||||
align_bbox = torch.zeros_like(predict_bbox, device=device) | ||||||
valid_mask = torch.zeros(predict_cls.shape[:2], dtype=bool, device=device) | ||||||
anchor_matched_targets = torch.cat([align_cls, align_bbox], dim=-1) | ||||||
return anchor_matched_targets, valid_mask | ||||||
|
||||||
target_cls, target_bbox = target.split([1, 4], dim=-1) # B x N x (C B) -> B x N x C, B x N x B | ||||||
target_cls = target_cls.long().clamp(0) | ||||||
|
||||||
|
@@ -262,7 +274,7 @@ def __call__(self, target: Tensor, predict: Tuple[Tensor]) -> Tuple[Tensor, Tens | |||||
normalize_term = normalize_term.permute(0, 2, 1).gather(2, unique_indices) | ||||||
align_cls = align_cls * normalize_term * valid_mask[:, :, None] | ||||||
|
||||||
return torch.cat([align_cls, align_bbox], dim=-1), valid_mask.bool() | ||||||
return torch.cat([align_cls, align_bbox], dim=-1), valid_mask | ||||||
|
||||||
|
||||||
class Vec2Box: | ||||||
|
@@ -398,51 +410,4 @@ def bbox_nms(cls_dist: Tensor, bbox: Tensor, nms_cfg: NMSConfig, confidence: Opt | |||||
) | ||||||
|
||||||
predicts_nms.append(predict_nms) | ||||||
return predicts_nms | ||||||
|
||||||
|
||||||
def calculate_map(predictions, ground_truths, iou_thresholds=arange(0.5, 1, 0.05)) -> Dict[str, Tensor]: | ||||||
# TODO: Refactor this block, Flexible for calculate different mAP condition? | ||||||
device = predictions.device | ||||||
n_preds = predictions.size(0) | ||||||
n_gts = (ground_truths[:, 0] != -1).sum() | ||||||
ground_truths = ground_truths[:n_gts] | ||||||
aps = [] | ||||||
|
||||||
ious = calculate_iou(predictions[:, 1:-1], ground_truths[:, 1:]) # [n_preds, n_gts] | ||||||
|
||||||
for threshold in iou_thresholds: | ||||||
tp = torch.zeros(n_preds, device=device, dtype=bool) | ||||||
|
||||||
max_iou, max_indices = ious.max(dim=1) | ||||||
above_threshold = max_iou >= threshold | ||||||
matched_classes = predictions[:, 0] == ground_truths[max_indices, 0] | ||||||
max_match = torch.zeros_like(ious) | ||||||
max_match[arange(n_preds), max_indices] = max_iou | ||||||
if max_match.size(0): | ||||||
tp[max_match.argmax(dim=0)] = True | ||||||
tp[~above_threshold | ~matched_classes] = False | ||||||
|
||||||
_, indices = torch.sort(predictions[:, 1], descending=True) | ||||||
tp = tp[indices] | ||||||
|
||||||
tp_cumsum = torch.cumsum(tp, dim=0) | ||||||
fp_cumsum = torch.cumsum(~tp, dim=0) | ||||||
|
||||||
precision = tp_cumsum / (tp_cumsum + fp_cumsum + 1e-6) | ||||||
recall = tp_cumsum / (n_gts + 1e-6) | ||||||
|
||||||
precision = torch.cat([torch.ones(1, device=device), precision, torch.zeros(1, device=device)]) | ||||||
recall = torch.cat([torch.zeros(1, device=device), recall, torch.ones(1, device=device)]) | ||||||
|
||||||
precision, _ = torch.cummax(precision.flip(0), dim=0) | ||||||
precision = precision.flip(0) | ||||||
|
||||||
ap = torch.trapezoid(precision, recall) | ||||||
aps.append(ap) | ||||||
|
||||||
mAP = { | ||||||
"mAP.5": aps[0], | ||||||
"mAP.5:.95": torch.mean(torch.stack(aps)), | ||||||
} | ||||||
return mAP | ||||||
return predicts_nms |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you add return types please?