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_beta.py 8.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 Beta 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 Beta distribution.
  28. """
  29. def __init__(self):
  30. super(Prob, self).__init__()
  31. self.b = msd.Beta(np.array([3.0]), np.array([1.0]), dtype=dtype.float32)
  32. def construct(self, x_):
  33. return self.b.prob(x_)
  34. def test_pdf():
  35. """
  36. Test pdf.
  37. """
  38. beta_benchmark = stats.beta(np.array([3.0]), np.array([1.0]))
  39. expect_pdf = beta_benchmark.pdf([0.25, 0.75]).astype(np.float32)
  40. pdf = Prob()
  41. output = pdf(Tensor([0.25, 0.75], 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 Beta distribution.
  47. """
  48. def __init__(self):
  49. super(LogProb, self).__init__()
  50. self.b = msd.Beta(np.array([3.0]), np.array([1.0]), dtype=dtype.float32)
  51. def construct(self, x_):
  52. return self.b.log_prob(x_)
  53. def test_log_likelihood():
  54. """
  55. Test log_pdf.
  56. """
  57. beta_benchmark = stats.beta(np.array([3.0]), np.array([1.0]))
  58. expect_logpdf = beta_benchmark.logpdf([0.25, 0.75]).astype(np.float32)
  59. logprob = LogProb()
  60. output = logprob(Tensor([0.25, 0.75], 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 Beta distribution.
  66. """
  67. def __init__(self):
  68. super(KL, self).__init__()
  69. self.b = msd.Beta(np.array([3.0]), np.array([4.0]), dtype=dtype.float32)
  70. def construct(self, x_, y_):
  71. return self.b.kl_loss('Beta', x_, y_)
  72. def test_kl_loss():
  73. """
  74. Test kl_loss.
  75. """
  76. concentration1_a = np.array([3.0]).astype(np.float32)
  77. concentration0_a = np.array([4.0]).astype(np.float32)
  78. concentration1_b = np.array([1.0]).astype(np.float32)
  79. concentration0_b = np.array([1.0]).astype(np.float32)
  80. total_concentration_a = concentration1_a + concentration0_a
  81. total_concentration_b = concentration1_b + concentration0_b
  82. log_normalization_a = np.log(special.beta(concentration1_a, concentration0_a))
  83. log_normalization_b = np.log(special.beta(concentration1_b, concentration0_b))
  84. expect_kl_loss = (log_normalization_b - log_normalization_a) \
  85. - (special.digamma(concentration1_a) * (concentration1_b - concentration1_a)) \
  86. - (special.digamma(concentration0_a) * (concentration0_b - concentration0_a)) \
  87. + (special.digamma(total_concentration_a) * (total_concentration_b - total_concentration_a))
  88. kl_loss = KL()
  89. concentration1 = Tensor(concentration1_b, dtype=dtype.float32)
  90. concentration0 = Tensor(concentration0_b, dtype=dtype.float32)
  91. output = kl_loss(concentration1, concentration0)
  92. tol = 1e-6
  93. assert (np.abs(output.asnumpy() - expect_kl_loss) < tol).all()
  94. class Basics(nn.Cell):
  95. """
  96. Test class: mean/sd/mode of Beta distribution.
  97. """
  98. def __init__(self):
  99. super(Basics, self).__init__()
  100. self.b = msd.Beta(np.array([3.0]), np.array([3.0]), dtype=dtype.float32)
  101. def construct(self):
  102. return self.b.mean(), self.b.sd(), self.b.mode()
  103. def test_basics():
  104. """
  105. Test mean/standard deviation/mode.
  106. """
  107. basics = Basics()
  108. mean, sd, mode = basics()
  109. beta_benchmark = stats.beta(np.array([3.0]), np.array([3.0]))
  110. expect_mean = beta_benchmark.mean().astype(np.float32)
  111. expect_sd = beta_benchmark.std().astype(np.float32)
  112. expect_mode = [0.5]
  113. tol = 1e-6
  114. assert (np.abs(mean.asnumpy() - expect_mean) < tol).all()
  115. assert (np.abs(mode.asnumpy() - expect_mode) < tol).all()
  116. assert (np.abs(sd.asnumpy() - expect_sd) < tol).all()
  117. class Sampling(nn.Cell):
  118. """
  119. Test class: sample of Beta distribution.
  120. """
  121. def __init__(self, shape, seed=0):
  122. super(Sampling, self).__init__()
  123. self.b = msd.Beta(np.array([3.0]), np.array([1.0]), seed=seed, dtype=dtype.float32)
  124. self.shape = shape
  125. def construct(self, concentration1=None, concentration0=None):
  126. return self.b.sample(self.shape, concentration1, concentration0)
  127. def test_sample():
  128. """
  129. Test sample.
  130. """
  131. shape = (2, 3)
  132. seed = 10
  133. concentration1 = Tensor([2.0], dtype=dtype.float32)
  134. concentration0 = Tensor([2.0, 2.0, 2.0], dtype=dtype.float32)
  135. sample = Sampling(shape, seed=seed)
  136. output = sample(concentration1, concentration0)
  137. assert output.shape == (2, 3, 3)
  138. class EntropyH(nn.Cell):
  139. """
  140. Test class: entropy of Beta distribution.
  141. """
  142. def __init__(self):
  143. super(EntropyH, self).__init__()
  144. self.b = msd.Beta(np.array([3.0]), np.array([1.0]), dtype=dtype.float32)
  145. def construct(self):
  146. return self.b.entropy()
  147. def test_entropy():
  148. """
  149. Test entropy.
  150. """
  151. beta_benchmark = stats.beta(np.array([3.0]), np.array([1.0]))
  152. expect_entropy = beta_benchmark.entropy().astype(np.float32)
  153. entropy = EntropyH()
  154. output = entropy()
  155. tol = 1e-6
  156. assert (np.abs(output.asnumpy() - expect_entropy) < tol).all()
  157. class CrossEntropy(nn.Cell):
  158. """
  159. Test class: cross entropy between Beta distributions.
  160. """
  161. def __init__(self):
  162. super(CrossEntropy, self).__init__()
  163. self.b = msd.Beta(np.array([3.0]), np.array([1.0]), dtype=dtype.float32)
  164. def construct(self, x_, y_):
  165. entropy = self.b.entropy()
  166. kl_loss = self.b.kl_loss('Beta', x_, y_)
  167. h_sum_kl = entropy + kl_loss
  168. cross_entropy = self.b.cross_entropy('Beta', x_, y_)
  169. return h_sum_kl - cross_entropy
  170. def test_cross_entropy():
  171. """
  172. Test cross_entropy.
  173. """
  174. cross_entropy = CrossEntropy()
  175. concentration1 = Tensor([3.0], dtype=dtype.float32)
  176. concentration0 = Tensor([2.0], dtype=dtype.float32)
  177. diff = cross_entropy(concentration1, concentration0)
  178. tol = 1e-6
  179. assert (np.abs(diff.asnumpy() - np.zeros(diff.shape)) < tol).all()
  180. class Net(nn.Cell):
  181. """
  182. Test class: expand single distribution instance to multiple graphs
  183. by specifying the attributes.
  184. """
  185. def __init__(self):
  186. super(Net, self).__init__()
  187. self.beta = msd.Beta(np.array([3.0]), np.array([1.0]), dtype=dtype.float32)
  188. def construct(self, x_, y_):
  189. kl = self.beta.kl_loss('Beta', x_, y_)
  190. prob = self.beta.prob(kl)
  191. return prob
  192. def test_multiple_graphs():
  193. """
  194. Test multiple graphs case.
  195. """
  196. prob = Net()
  197. concentration1_a = np.array([3.0]).astype(np.float32)
  198. concentration0_a = np.array([1.0]).astype(np.float32)
  199. concentration1_b = np.array([2.0]).astype(np.float32)
  200. concentration0_b = np.array([1.0]).astype(np.float32)
  201. ans = prob(Tensor(concentration1_b), Tensor(concentration0_b))
  202. total_concentration_a = concentration1_a + concentration0_a
  203. total_concentration_b = concentration1_b + concentration0_b
  204. log_normalization_a = np.log(special.beta(concentration1_a, concentration0_a))
  205. log_normalization_b = np.log(special.beta(concentration1_b, concentration0_b))
  206. expect_kl_loss = (log_normalization_b - log_normalization_a) \
  207. - (special.digamma(concentration1_a) * (concentration1_b - concentration1_a)) \
  208. - (special.digamma(concentration0_a) * (concentration0_b - concentration0_a)) \
  209. + (special.digamma(total_concentration_a) * (total_concentration_b - total_concentration_a))
  210. beta_benchmark = stats.beta(np.array([3.0]), np.array([1.0]))
  211. expect_prob = beta_benchmark.pdf(expect_kl_loss).astype(np.float32)
  212. tol = 1e-6
  213. assert (np.abs(ans.asnumpy() - expect_prob) < tol).all()