1# Copyright 2021 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 categorical distribution""" 16 17import pytest 18import numpy as np 19import mindspore.context as context 20import mindspore.nn as nn 21import mindspore.nn.probability.distribution as msd 22from mindspore import Tensor 23from mindspore import dtype as ms 24 25context.set_context(mode=context.GRAPH_MODE, device_target="GPU") 26 27def generate_probs(seed, shape): 28 np.random.seed(seed) 29 probs = np.random.dirichlet(np.ones(shape[3]), size=1) 30 for _ in range(shape[0] - 1): 31 for _ in range(shape[1] - 1): 32 for _ in range(shape[2] - 1): 33 probs = np.vstack(((np.random.dirichlet(np.ones(shape[3]), size=1)), probs)) 34 probs = np.array([probs, probs]) 35 probs = np.array([probs, probs]) 36 return probs 37 38 39class CategoricalProb(nn.Cell): 40 def __init__(self, probs, seed=10, dtype=ms.int32, name='Categorical'): 41 super().__init__() 42 self.b = msd.Categorical(probs, seed, dtype, name) 43 44 def construct(self, value, probs=None): 45 out1 = self.b.prob(value, probs) 46 out2 = self.b.log_prob(value, probs) 47 out3 = self.b.cdf(value, probs) 48 out4 = self.b.log_cdf(value, probs) 49 out5 = self.b.survival_function(value, probs) 50 out6 = self.b.log_survival(value, probs) 51 return out1, out2, out3, out4, out5, out6 52 53 54 55@pytest.mark.level1 56@pytest.mark.platform_x86_gpu_training 57@pytest.mark.env_onecard 58def test_probability_categorical_prob_cdf_probs_none(): 59 probs = None 60 probs1 = generate_probs(3, shape=(2, 2, 1, 64)) 61 value = np.random.randint(0, 63, size=(64)).astype(np.float32) 62 net = CategoricalProb(probs) 63 net(Tensor(value), Tensor(probs1)) 64