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.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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]): The buckets of histogram data.
  63. max_val (number): The max value of histogram data.
  64. min_val (number): The min value of histogram data.
  65. count (int): The count of histogram data.
  66. """
  67. # Max quantity of original buckets.
  68. MAX_ORIGINAL_BUCKETS_COUNT = 90
  69. def __init__(self, buckets, max_val, min_val, count):
  70. self._visual_max = max_val
  71. self._visual_min = min_val
  72. self._count = count
  73. self._original_buckets = buckets
  74. # default bin number
  75. self._visual_bins = calc_histogram_bins(count)
  76. # Note that tuple is immutable, so sharing tuple is often safe.
  77. self._re_sampled_buckets = ()
  78. @property
  79. def original_buckets_count(self):
  80. """Gets original buckets quantity."""
  81. return len(self._original_buckets)
  82. def set_visual_range(self, max_val: float, min_val: float, bins: int) -> None:
  83. """
  84. Sets visual range for later re-sampling.
  85. It's caller's duty to ensure input is valid.
  86. Why we need visual range for histograms? Aligned buckets between steps can help users know about the trend of
  87. tensors. Miss aligned buckets between steps might miss-lead users about the trend of a tensor. Because for
  88. given tensor, if you have thinner buckets, count of every bucket will get lower, however, if you have
  89. thicker buckets, count of every bucket will get higher. When they are displayed together, user might think
  90. the histogram with thicker buckets has more values. This is miss-leading. So we need to unify buckets across
  91. steps. Visual range for histogram is a technology for unifying buckets.
  92. Args:
  93. max_val (float): Max value for visual histogram.
  94. min_val (float): Min value for visual histogram.
  95. bins (int): Bins number for visual histogram.
  96. """
  97. if max_val < min_val:
  98. raise ParamValueError(
  99. "Invalid input. max_val({}) is less or equal than min_val({}).".format(max_val, min_val))
  100. if bins < 1:
  101. raise ParamValueError("Invalid input bins({}). Must be greater than 0.".format(bins))
  102. self._visual_max = max_val
  103. self._visual_min = min_val
  104. self._visual_bins = bins
  105. # mark _re_sampled_buckets to empty
  106. self._re_sampled_buckets = ()
  107. def _calc_intersection_len(self, max1, min1, max2, min2):
  108. """Calculates intersection length of [min1, max1] and [min2, max2]."""
  109. if max1 < min1:
  110. raise ParamValueError(
  111. "Invalid input. max1({}) is less than min1({}).".format(max1, min1))
  112. if max2 < min2:
  113. raise ParamValueError(
  114. "Invalid input. max2({}) is less than min2({}).".format(max2, min2))
  115. if min1 <= min2:
  116. if max1 <= min2:
  117. # return value must be calculated by max1.__sub__
  118. return max1 - max1
  119. if max1 <= max2:
  120. return max1 - min2
  121. # max1 > max2
  122. return max2 - min2
  123. # min1 > min2
  124. if max2 <= min1:
  125. return max2 - max2
  126. if max2 <= max1:
  127. return max2 - min1
  128. return max1 - min1
  129. def _re_sample_buckets(self):
  130. """Re-samples buckets according to visual_max, visual_min and visual_bins."""
  131. if self._visual_max == self._visual_min:
  132. # Adjust visual range if max equals min.
  133. self._visual_max += 0.5
  134. self._visual_min -= 0.5
  135. width = (self._visual_max - self._visual_min) / self._visual_bins
  136. if not self._count:
  137. self._re_sampled_buckets = tuple(
  138. Bucket(self._visual_min + width * i, width, 0)
  139. for i in range(self._visual_bins))
  140. return
  141. re_sampled = []
  142. original_pos = 0
  143. original_bucket = self._original_buckets[original_pos]
  144. for i in range(self._visual_bins):
  145. cur_left = self._visual_min + width * i
  146. cur_right = cur_left + width
  147. cur_estimated_count = 0.0
  148. # Skip no bucket range.
  149. if cur_right <= original_bucket.left:
  150. re_sampled.append(Bucket(cur_left, width, math.ceil(cur_estimated_count)))
  151. continue
  152. # Skip no intersect range.
  153. while cur_left >= original_bucket.right:
  154. original_pos += 1
  155. if original_pos >= len(self._original_buckets):
  156. break
  157. original_bucket = self._original_buckets[original_pos]
  158. # entering with this condition: cur_right > original_bucket.left and cur_left < original_bucket.right
  159. while True:
  160. if original_pos >= len(self._original_buckets):
  161. break
  162. original_bucket = self._original_buckets[original_pos]
  163. intersection = self._calc_intersection_len(
  164. min1=cur_left, max1=cur_right,
  165. min2=original_bucket.left, max2=original_bucket.right)
  166. if not original_bucket.width:
  167. estimated_count = original_bucket.count
  168. else:
  169. estimated_count = (intersection / original_bucket.width) * original_bucket.count
  170. cur_estimated_count += estimated_count
  171. if cur_right > original_bucket.right:
  172. # Need to sample next original bucket to this visual bucket.
  173. original_pos += 1
  174. else:
  175. # Current visual bucket has taken all intersect buckets into account.
  176. break
  177. re_sampled.append(Bucket(cur_left, width, math.ceil(cur_estimated_count)))
  178. self._re_sampled_buckets = tuple(re_sampled)
  179. def buckets(self, convert_to_tuple=True):
  180. """
  181. Get visual buckets instead of original buckets.
  182. Args:
  183. convert_to_tuple (bool): Whether convert bucket object to tuple.
  184. Returns:
  185. tuple, contains buckets.
  186. """
  187. if not self._re_sampled_buckets:
  188. self._re_sample_buckets()
  189. if not convert_to_tuple:
  190. return self._re_sampled_buckets
  191. return tuple(bucket.as_tuple() for bucket in self._re_sampled_buckets)