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_gamma.py 10 kB

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