utils_numpy.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import numpy as np
  2. def sigmoid(x):
  3. return 1. / (1 + np.exp(-x))
  4. def softmax(x, axis=-1, copy=True):
  5. """
  6. Args:
  7. copy: Copy x or not.
  8. Referneces:
  9. `from sklearn.utils.extmath import softmax`
  10. """
  11. if copy:
  12. x = np.copy(x)
  13. max_val = np.max(x, axis=axis, keepdims=True)
  14. x -= max_val
  15. np.exp(x, x)
  16. sum_exp = np.sum(x, axis=axis, keepdims=True)
  17. x /= sum_exp
  18. return x
  19. def log_sum_exp(x, axis=-1, keepdims=False):
  20. """
  21. References:
  22. numpy.logaddexp
  23. numpy.logaddexp2
  24. scipy.misc.logsumexp
  25. """
  26. max_val = np.max(x, axis=axis, keepdims=True)
  27. x -= max_val
  28. np.exp(x, x)
  29. sum_exp = np.sum(x, axis=axis, keepdims=keepdims)
  30. lse = np.log(sum_exp, sum_exp)
  31. if not keepdims:
  32. max_val = np.squeeze(max_val, axis=axis)
  33. return max_val + lse
  34. def l2_normalize(x, axis=0, epsilon=1e-12, copy=True):
  35. """L2 normalize an array along an axis.
  36. Args:
  37. x : array_like of floats
  38. Input data.
  39. axis : None or int or tuple of ints, optional
  40. Axis or axes along which to operate.
  41. epsilon: float, optional
  42. A small value such as to avoid division by zero.
  43. copy : bool, optional
  44. Copy X or not.
  45. """
  46. if copy:
  47. x = np.copy(x)
  48. x /= np.maximum(np.linalg.norm(x, axis=axis, keepdims=True), epsilon)
  49. return x
  50. def minmax_normalize(x, axis=0, copy=True):
  51. """minmax normalize an array along a given axis.
  52. Args:
  53. x : array_like of floats
  54. Input data.
  55. axis : None or int or tuple of ints, optional
  56. Axis or axes along which to operate.
  57. copy : bool, optional
  58. Copy X or not.
  59. """
  60. if copy:
  61. x = np.copy(x)
  62. minval = np.min(x, axis=axis, keepdims=True)
  63. maxval = np.max(x, axis=axis, keepdims=True)
  64. maxval -= minval
  65. maxval = np.maximum(maxval, 1e-5)
  66. x -= minval
  67. x /= maxval
  68. return x
  69. def get_order_of_magnitude(number):
  70. number = np.where(number == 0, 1, number)
  71. oom = np.floor(np.log10(np.abs(number)))
  72. return oom.astype(np.int32)