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

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