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_uniform.py 8.5 kB

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