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.

test_gumbel.py 9.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # Copyright 2019 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. """test cases for Gumbel distribution"""
  16. import numpy as np
  17. from scipy import stats
  18. from scipy import special
  19. import mindspore.context as context
  20. import mindspore.nn as nn
  21. import mindspore.nn.probability.distribution as msd
  22. from mindspore import Tensor
  23. from mindspore import dtype
  24. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  25. class Prob(nn.Cell):
  26. """
  27. Test class: probability of Gumbel distribution.
  28. """
  29. def __init__(self):
  30. super(Prob, self).__init__()
  31. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  32. def construct(self, x_):
  33. return self.gum.prob(x_)
  34. def test_pdf():
  35. """
  36. Test pdf.
  37. """
  38. loc = np.array([0.0]).astype(np.float32)
  39. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  40. gumbel_benchmark = stats.gumbel_r(loc, scale)
  41. value = np.array([1.0, 2.0]).astype(np.float32)
  42. expect_pdf = gumbel_benchmark.pdf(value).astype(np.float32)
  43. pdf = Prob()
  44. output = pdf(Tensor(value, dtype=dtype.float32))
  45. tol = 1e-6
  46. assert (np.abs(output.asnumpy() - expect_pdf) < tol).all()
  47. class LogProb(nn.Cell):
  48. """
  49. Test class: log probability of Gumbel distribution.
  50. """
  51. def __init__(self):
  52. super(LogProb, self).__init__()
  53. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  54. def construct(self, x_):
  55. return self.gum.log_prob(x_)
  56. def test_log_likelihood():
  57. """
  58. Test log_pdf.
  59. """
  60. loc = np.array([0.0]).astype(np.float32)
  61. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  62. gumbel_benchmark = stats.gumbel_r(loc, scale)
  63. expect_logpdf = gumbel_benchmark.logpdf([1.0, 2.0]).astype(np.float32)
  64. logprob = LogProb()
  65. output = logprob(Tensor([1.0, 2.0], dtype=dtype.float32))
  66. tol = 1e-6
  67. assert (np.abs(output.asnumpy() - expect_logpdf) < tol).all()
  68. class KL(nn.Cell):
  69. """
  70. Test class: kl_loss of Gumbel distribution.
  71. """
  72. def __init__(self):
  73. super(KL, self).__init__()
  74. self.gum = msd.Gumbel(np.array([0.0]), np.array([1.0, 2.0]), dtype=dtype.float32)
  75. def construct(self, loc_b, scale_b):
  76. return self.gum.kl_loss('Gumbel', loc_b, scale_b)
  77. def test_kl_loss():
  78. """
  79. Test kl_loss.
  80. """
  81. loc = np.array([0.0]).astype(np.float32)
  82. scale = np.array([1.0, 2.0]).astype(np.float32)
  83. loc_b = np.array([1.0]).astype(np.float32)
  84. scale_b = np.array([1.0, 2.0]).astype(np.float32)
  85. expect_kl_loss = np.log(scale_b) - np.log(scale) +\
  86. np.euler_gamma * (scale / scale_b - 1.) +\
  87. np.expm1((loc_b - loc) / scale_b + special.loggamma(scale / scale_b + 1.))
  88. kl_loss = KL()
  89. loc_b = Tensor(loc_b, dtype=dtype.float32)
  90. scale_b = Tensor(scale_b, dtype=dtype.float32)
  91. output = kl_loss(loc_b, scale_b)
  92. tol = 1e-5
  93. assert (np.abs(output.asnumpy() - expect_kl_loss) < tol).all()
  94. class Basics(nn.Cell):
  95. """
  96. Test class: mean/sd/mode of Gumbel distribution.
  97. """
  98. def __init__(self):
  99. super(Basics, self).__init__()
  100. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  101. def construct(self):
  102. return self.gum.mean(), self.gum.sd(), self.gum.mode()
  103. def test_basics():
  104. """
  105. Test mean/standard deviation/mode.
  106. """
  107. basics = Basics()
  108. mean, sd, mode = basics()
  109. loc = np.array([0.0]).astype(np.float32)
  110. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  111. gumbel_benchmark = stats.gumbel_r(loc, scale)
  112. expect_mean = gumbel_benchmark.mean().astype(np.float32)
  113. expect_sd = gumbel_benchmark.std().astype(np.float32)
  114. expect_mode = np.array([[0.0], [0.0]]).astype(np.float32)
  115. tol = 1e-6
  116. assert (np.abs(mean.asnumpy() - expect_mean) < tol).all()
  117. assert (np.abs(mode.asnumpy() - expect_mode) < tol).all()
  118. assert (np.abs(sd.asnumpy() - expect_sd) < tol).all()
  119. class Sampling(nn.Cell):
  120. """
  121. Test class: sample of Gumbel distribution.
  122. """
  123. def __init__(self, shape, seed=0):
  124. super(Sampling, self).__init__()
  125. self.gum = msd.Gumbel(np.array([0.0]), np.array([1.0, 2.0, 3.0]), dtype=dtype.float32, seed=seed)
  126. self.shape = shape
  127. def construct(self):
  128. return self.gum.sample(self.shape)
  129. def test_sample():
  130. """
  131. Test sample.
  132. """
  133. shape = (2, 3)
  134. seed = 10
  135. sample = Sampling(shape, seed=seed)
  136. output = sample()
  137. assert output.shape == (2, 3, 3)
  138. class CDF(nn.Cell):
  139. """
  140. Test class: cdf of Gumbel distribution.
  141. """
  142. def __init__(self):
  143. super(CDF, self).__init__()
  144. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  145. def construct(self, x_):
  146. return self.gum.cdf(x_)
  147. def test_cdf():
  148. """
  149. Test cdf.
  150. """
  151. loc = np.array([0.0]).astype(np.float32)
  152. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  153. gumbel_benchmark = stats.gumbel_r(loc, scale)
  154. expect_cdf = gumbel_benchmark.cdf([1.0, 2.0]).astype(np.float32)
  155. cdf = CDF()
  156. output = cdf(Tensor([1.0, 2.0], dtype=dtype.float32))
  157. tol = 2e-5
  158. assert (np.abs(output.asnumpy() - expect_cdf) < tol).all()
  159. class LogCDF(nn.Cell):
  160. """
  161. Test class: log_cdf of Gumbel distribution.
  162. """
  163. def __init__(self):
  164. super(LogCDF, self).__init__()
  165. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  166. def construct(self, x_):
  167. return self.gum.log_cdf(x_)
  168. def test_log_cdf():
  169. """
  170. Test log cdf.
  171. """
  172. loc = np.array([0.0]).astype(np.float32)
  173. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  174. gumbel_benchmark = stats.gumbel_r(loc, scale)
  175. expect_logcdf = gumbel_benchmark.logcdf([1.0, 2.0]).astype(np.float32)
  176. logcdf = LogCDF()
  177. output = logcdf(Tensor([1.0, 2.0], dtype=dtype.float32))
  178. tol = 1e-4
  179. assert (np.abs(output.asnumpy() - expect_logcdf) < tol).all()
  180. class SF(nn.Cell):
  181. """
  182. Test class: survival function of Gumbel distribution.
  183. """
  184. def __init__(self):
  185. super(SF, self).__init__()
  186. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  187. def construct(self, x_):
  188. return self.gum.survival_function(x_)
  189. def test_survival():
  190. """
  191. Test log_survival.
  192. """
  193. loc = np.array([0.0]).astype(np.float32)
  194. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  195. gumbel_benchmark = stats.gumbel_r(loc, scale)
  196. expect_survival = gumbel_benchmark.sf([1.0, 2.0]).astype(np.float32)
  197. survival_function = SF()
  198. output = survival_function(Tensor([1.0, 2.0], dtype=dtype.float32))
  199. tol = 2e-5
  200. assert (np.abs(output.asnumpy() - expect_survival) < tol).all()
  201. class LogSF(nn.Cell):
  202. """
  203. Test class: log survival function of Gumbel distribution.
  204. """
  205. def __init__(self):
  206. super(LogSF, self).__init__()
  207. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  208. def construct(self, x_):
  209. return self.gum.log_survival(x_)
  210. def test_log_survival():
  211. """
  212. Test log_survival.
  213. """
  214. loc = np.array([0.0]).astype(np.float32)
  215. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  216. gumbel_benchmark = stats.gumbel_r(loc, scale)
  217. expect_log_survival = gumbel_benchmark.logsf([1.0, 2.0]).astype(np.float32)
  218. log_survival = LogSF()
  219. output = log_survival(Tensor([1.0, 2.0], dtype=dtype.float32))
  220. tol = 5e-4
  221. assert (np.abs(output.asnumpy() - expect_log_survival) < tol).all()
  222. class EntropyH(nn.Cell):
  223. """
  224. Test class: entropy of Gumbel distribution.
  225. """
  226. def __init__(self):
  227. super(EntropyH, self).__init__()
  228. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  229. def construct(self):
  230. return self.gum.entropy()
  231. def test_entropy():
  232. """
  233. Test entropy.
  234. """
  235. loc = np.array([0.0]).astype(np.float32)
  236. scale = np.array([[1.0], [2.0]]).astype(np.float32)
  237. gumbel_benchmark = stats.gumbel_r(loc, scale)
  238. expect_entropy = gumbel_benchmark.entropy().astype(np.float32)
  239. entropy = EntropyH()
  240. output = entropy()
  241. tol = 1e-6
  242. assert (np.abs(output.asnumpy() - expect_entropy) < tol).all()
  243. class CrossEntropy(nn.Cell):
  244. """
  245. Test class: cross entropy between Gumbel distributions.
  246. """
  247. def __init__(self):
  248. super(CrossEntropy, self).__init__()
  249. self.gum = msd.Gumbel(np.array([0.0]), np.array([[1.0], [2.0]]), dtype=dtype.float32)
  250. def construct(self, x_, y_):
  251. entropy = self.gum.entropy()
  252. kl_loss = self.gum.kl_loss('Gumbel', x_, y_)
  253. h_sum_kl = entropy + kl_loss
  254. cross_entropy = self.gum.cross_entropy('Gumbel', x_, y_)
  255. return h_sum_kl - cross_entropy
  256. def test_cross_entropy():
  257. """
  258. Test cross_entropy.
  259. """
  260. cross_entropy = CrossEntropy()
  261. loc = Tensor([1.0], dtype=dtype.float32)
  262. scale = Tensor([1.0], dtype=dtype.float32)
  263. diff = cross_entropy(loc, scale)
  264. tol = 1e-6
  265. assert (np.abs(diff.asnumpy() - np.zeros(diff.shape)) < tol).all()