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.

utils.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. """Utils for optimizer."""
  16. import string
  17. import numpy as np
  18. _DEFAULT_HISTOGRAM_BINS = 5
  19. def calc_histogram(np_value: np.ndarray, bins=_DEFAULT_HISTOGRAM_BINS):
  20. """
  21. Calculates histogram.
  22. This is a simple wrapper around the error-prone np.histogram() to improve robustness.
  23. """
  24. ma_value = np.ma.masked_invalid(np_value)
  25. valid_cnt = ma_value.count()
  26. if not valid_cnt:
  27. max_val = 0
  28. min_val = 0
  29. else:
  30. # Note that max of a masked array with dtype np.float16 returns inf (numpy issue#15077).
  31. if np.issubdtype(np_value.dtype, np.floating):
  32. max_val = ma_value.max(fill_value=np.NINF)
  33. min_val = ma_value.min(fill_value=np.PINF)
  34. else:
  35. max_val = ma_value.max()
  36. min_val = ma_value.min()
  37. range_left = min_val
  38. range_right = max_val
  39. default_half_range = 0.5
  40. if range_left >= range_right:
  41. range_left -= default_half_range
  42. range_right += default_half_range
  43. with np.errstate(invalid='ignore'):
  44. # if don't ignore state above, when np.nan exists,
  45. # it will occur RuntimeWarning: invalid value encountered in less_equal
  46. counts, edges = np.histogram(np_value, bins=bins, range=(range_left, range_right))
  47. histogram_bins = [None] * len(counts)
  48. for ind, count in enumerate(counts):
  49. histogram_bins[ind] = [float(edges[ind]), float(edges[ind + 1] - edges[ind]), float(count)]
  50. return histogram_bins
  51. def is_simple_numpy_number(dtype):
  52. """Verify if it is simple number."""
  53. if np.issubdtype(dtype, np.integer):
  54. return True
  55. if np.issubdtype(dtype, np.floating):
  56. return True
  57. return False
  58. def get_nested_message(info: dict, out_err_msg=""):
  59. """Get error message from the error dict generated by schema validation."""
  60. if not isinstance(info, dict):
  61. if isinstance(info, list):
  62. info = info[0]
  63. return f'Error in {out_err_msg}: {info}'
  64. for key in info:
  65. if isinstance(key, str) and key != '_schema':
  66. if out_err_msg:
  67. out_err_msg = f'{out_err_msg}.{key}'
  68. else:
  69. out_err_msg = key
  70. return get_nested_message(info[key], out_err_msg)
  71. def is_number(uchar):
  72. """If it is a number, return True."""
  73. if uchar in string.digits:
  74. return True
  75. return False
  76. def is_alphabet(uchar):
  77. """If it is a alphabet, return True."""
  78. if uchar in string.ascii_letters:
  79. return True
  80. return False
  81. def is_allowed_symbols(uchar):
  82. """If it is a allowed symbol, return True."""
  83. if uchar in ['_']:
  84. return True
  85. return False
  86. def is_param_name_valid(param_name: str):
  87. """If parameter name only contains number or alphabet."""
  88. for uchar in param_name:
  89. if not is_number(uchar) and not is_alphabet(uchar) and not is_allowed_symbols(uchar):
  90. return False
  91. return True