point_sample.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import torch
  3. from mmcv.ops import point_sample
  4. from torch import Tensor
  5. def get_uncertainty(mask_preds: Tensor, labels: Tensor) -> Tensor:
  6. """Estimate uncertainty based on pred logits.
  7. We estimate uncertainty as L1 distance between 0.0 and the logits
  8. prediction in 'mask_preds' for the foreground class in `classes`.
  9. Args:
  10. mask_preds (Tensor): mask predication logits, shape (num_rois,
  11. num_classes, mask_height, mask_width).
  12. labels (Tensor): Either predicted or ground truth label for
  13. each predicted mask, of length num_rois.
  14. Returns:
  15. scores (Tensor): Uncertainty scores with the most uncertain
  16. locations having the highest uncertainty score,
  17. shape (num_rois, 1, mask_height, mask_width)
  18. """
  19. if mask_preds.shape[1] == 1:
  20. gt_class_logits = mask_preds.clone()
  21. else:
  22. inds = torch.arange(mask_preds.shape[0], device=mask_preds.device)
  23. gt_class_logits = mask_preds[inds, labels].unsqueeze(1)
  24. return -torch.abs(gt_class_logits)
  25. def get_uncertain_point_coords_with_randomness(
  26. mask_preds: Tensor, labels: Tensor, num_points: int,
  27. oversample_ratio: float, importance_sample_ratio: float) -> Tensor:
  28. """Get ``num_points`` most uncertain points with random points during
  29. train.
  30. Sample points in [0, 1] x [0, 1] coordinate space based on their
  31. uncertainty. The uncertainties are calculated for each point using
  32. 'get_uncertainty()' function that takes point's logit prediction as
  33. input.
  34. Args:
  35. mask_preds (Tensor): A tensor of shape (num_rois, num_classes,
  36. mask_height, mask_width) for class-specific or class-agnostic
  37. prediction.
  38. labels (Tensor): The ground truth class for each instance.
  39. num_points (int): The number of points to sample.
  40. oversample_ratio (float): Oversampling parameter.
  41. importance_sample_ratio (float): Ratio of points that are sampled
  42. via importnace sampling.
  43. Returns:
  44. point_coords (Tensor): A tensor of shape (num_rois, num_points, 2)
  45. that contains the coordinates sampled points.
  46. """
  47. assert oversample_ratio >= 1
  48. assert 0 <= importance_sample_ratio <= 1
  49. batch_size = mask_preds.shape[0]
  50. num_sampled = int(num_points * oversample_ratio)
  51. point_coords = torch.rand(
  52. batch_size, num_sampled, 2, device=mask_preds.device)
  53. point_logits = point_sample(mask_preds, point_coords)
  54. # It is crucial to calculate uncertainty based on the sampled
  55. # prediction value for the points. Calculating uncertainties of the
  56. # coarse predictions first and sampling them for points leads to
  57. # incorrect results. To illustrate this: assume uncertainty func(
  58. # logits)=-abs(logits), a sampled point between two coarse
  59. # predictions with -1 and 1 logits has 0 logits, and therefore 0
  60. # uncertainty value. However, if we calculate uncertainties for the
  61. # coarse predictions first, both will have -1 uncertainty,
  62. # and sampled point will get -1 uncertainty.
  63. point_uncertainties = get_uncertainty(point_logits, labels)
  64. num_uncertain_points = int(importance_sample_ratio * num_points)
  65. num_random_points = num_points - num_uncertain_points
  66. idx = torch.topk(
  67. point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
  68. shift = num_sampled * torch.arange(
  69. batch_size, dtype=torch.long, device=mask_preds.device)
  70. idx += shift[:, None]
  71. point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view(
  72. batch_size, num_uncertain_points, 2)
  73. if num_random_points > 0:
  74. rand_roi_coords = torch.rand(
  75. batch_size, num_random_points, 2, device=mask_preds.device)
  76. point_coords = torch.cat((point_coords, rand_roi_coords), dim=1)
  77. return point_coords