You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

histogram.py 8.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Histogram data."""
  16. import math
  17. from mindinsight.utils.exceptions import ParamValueError
  18. from mindinsight.datavisual.utils.utils import calc_histogram_bins
  19. def mask_invalid_number(num):
  20. """Mask invalid number to 0."""
  21. if math.isnan(num) or math.isinf(num):
  22. return type(num)(0)
  23. return num
  24. class Bucket:
  25. """
  26. Bucket data class.
  27. Args:
  28. left (double): Left edge of the histogram bucket.
  29. width (double): Width of the histogram bucket.
  30. count (int): Count of numbers fallen in the histogram bucket.
  31. """
  32. def __init__(self, left, width, count):
  33. self._left = left
  34. self._width = width
  35. self._count = count
  36. @property
  37. def left(self):
  38. """Gets left edge of the histogram bucket."""
  39. return self._left
  40. @property
  41. def count(self):
  42. """Gets count of numbers fallen in the histogram bucket."""
  43. return self._count
  44. @property
  45. def width(self):
  46. """Gets width of the histogram bucket."""
  47. return self._width
  48. @property
  49. def right(self):
  50. """Gets right edge of the histogram bucket."""
  51. return self._left + self._width
  52. def as_tuple(self):
  53. """Gets the bucket as tuple."""
  54. return self._left, self._width, self._count
  55. def __repr__(self):
  56. """Returns repr(self)."""
  57. return "Bucket(left={}, width={}, count={})".format(self._left, self._width, self._count)
  58. class Histogram:
  59. """
  60. Histogram data class.
  61. Args:
  62. buckets (tuple[Bucket])
  63. """
  64. # Max quantity of original buckets.
  65. MAX_ORIGINAL_BUCKETS_COUNT = 90
  66. def __init__(self, buckets, max_val, min_val, count):
  67. self._visual_max = max_val
  68. self._visual_min = min_val
  69. self._count = count
  70. self._original_buckets = buckets
  71. # default bin number
  72. self._visual_bins = calc_histogram_bins(count)
  73. # Note that tuple is immutable, so sharing tuple is often safe.
  74. self._re_sampled_buckets = ()
  75. @property
  76. def original_buckets_count(self):
  77. """Gets original buckets quantity."""
  78. return len(self._original_buckets)
  79. def set_visual_range(self, max_val: float, min_val: float, bins: int) -> None:
  80. """
  81. Sets visual range for later re-sampling.
  82. It's caller's duty to ensure input is valid.
  83. Why we need visual range for histograms? Aligned buckets between steps can help users know about the trend of
  84. tensors. Miss aligned buckets between steps might miss-lead users about the trend of a tensor. Because for
  85. given tensor, if you have thinner buckets, count of every bucket will get lower, however, if you have
  86. thicker buckets, count of every bucket will get higher. When they are displayed together, user might think
  87. the histogram with thicker buckets has more values. This is miss-leading. So we need to unify buckets across
  88. steps. Visual range for histogram is a technology for unifying buckets.
  89. Args:
  90. max_val (float): Max value for visual histogram.
  91. min_val (float): Min value for visual histogram.
  92. bins (int): Bins number for visual histogram.
  93. """
  94. if max_val < min_val:
  95. raise ParamValueError(
  96. "Invalid input. max_val({}) is less or equal than min_val({}).".format(max_val, min_val))
  97. if bins < 1:
  98. raise ParamValueError("Invalid input bins({}). Must be greater than 0.".format(bins))
  99. self._visual_max = max_val
  100. self._visual_min = min_val
  101. self._visual_bins = bins
  102. # mark _re_sampled_buckets to empty
  103. self._re_sampled_buckets = ()
  104. def _calc_intersection_len(self, max1, min1, max2, min2):
  105. """Calculates intersection length of [min1, max1] and [min2, max2]."""
  106. if max1 < min1:
  107. raise ParamValueError(
  108. "Invalid input. max1({}) is less than min1({}).".format(max1, min1))
  109. if max2 < min2:
  110. raise ParamValueError(
  111. "Invalid input. max2({}) is less than min2({}).".format(max2, min2))
  112. if min1 <= min2:
  113. if max1 <= min2:
  114. # return value must be calculated by max1.__sub__
  115. return max1 - max1
  116. if max1 <= max2:
  117. return max1 - min2
  118. # max1 > max2
  119. return max2 - min2
  120. # min1 > min2
  121. if max2 <= min1:
  122. return max2 - max2
  123. if max2 <= max1:
  124. return max2 - min1
  125. return max1 - min1
  126. def _re_sample_buckets(self):
  127. """Re-samples buckets according to visual_max, visual_min and visual_bins."""
  128. if self._visual_max == self._visual_min:
  129. # Adjust visual range if max equals min.
  130. self._visual_max += 0.5
  131. self._visual_min -= 0.5
  132. width = (self._visual_max - self._visual_min) / self._visual_bins
  133. if not self._count:
  134. self._re_sampled_buckets = tuple(
  135. Bucket(self._visual_min + width * i, width, 0)
  136. for i in range(self._visual_bins))
  137. return
  138. re_sampled = []
  139. original_pos = 0
  140. original_bucket = self._original_buckets[original_pos]
  141. for i in range(self._visual_bins):
  142. cur_left = self._visual_min + width * i
  143. cur_right = cur_left + width
  144. cur_estimated_count = 0.0
  145. # Skip no bucket range.
  146. if cur_right <= original_bucket.left:
  147. re_sampled.append(Bucket(cur_left, width, math.ceil(cur_estimated_count)))
  148. continue
  149. # Skip no intersect range.
  150. while cur_left >= original_bucket.right:
  151. original_pos += 1
  152. if original_pos >= len(self._original_buckets):
  153. break
  154. original_bucket = self._original_buckets[original_pos]
  155. # entering with this condition: cur_right > original_bucket.left and cur_left < original_bucket.right
  156. while True:
  157. if original_pos >= len(self._original_buckets):
  158. break
  159. original_bucket = self._original_buckets[original_pos]
  160. intersection = self._calc_intersection_len(
  161. min1=cur_left, max1=cur_right,
  162. min2=original_bucket.left, max2=original_bucket.right)
  163. if not original_bucket.width:
  164. estimated_count = original_bucket.count
  165. else:
  166. estimated_count = (intersection / original_bucket.width) * original_bucket.count
  167. cur_estimated_count += estimated_count
  168. if cur_right > original_bucket.right:
  169. # Need to sample next original bucket to this visual bucket.
  170. original_pos += 1
  171. else:
  172. # Current visual bucket has taken all intersect buckets into account.
  173. break
  174. re_sampled.append(Bucket(cur_left, width, math.ceil(cur_estimated_count)))
  175. self._re_sampled_buckets = tuple(re_sampled)
  176. def buckets(self, convert_to_tuple=True):
  177. """
  178. Get visual buckets instead of original buckets.
  179. Args:
  180. convert_to_tuple (bool): Whether convert bucket object to tuple.
  181. Returns:
  182. tuple, contains buckets.
  183. """
  184. if not self._re_sampled_buckets:
  185. self._re_sample_buckets()
  186. if not convert_to_tuple:
  187. return self._re_sampled_buckets
  188. return tuple(bucket.as_tuple() for bucket in self._re_sampled_buckets)