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 loss""" 16import numpy as np 17import pytest 18 19from mindspore import Tensor 20from mindspore.nn.metrics import Loss 21 22 23def test_loss_inputs_error(): 24 loss = Loss() 25 with pytest.raises(ValueError): 26 loss(np.array(1), np.array(2)) 27 28 29def test_loss_shape_error(): 30 loss = Loss() 31 inp = np.ones(shape=[2, 2]) 32 with pytest.raises(ValueError): 33 loss.update(inp) 34 35 36def test_loss(): 37 """test_loss""" 38 num = 5 39 inputs = np.random.rand(num) 40 41 loss = Loss() 42 for k in range(num): 43 loss.update(Tensor(np.array([inputs[k]]))) 44 45 assert inputs.mean() == loss.eval() 46 47 loss.clear() 48 with pytest.raises(RuntimeError): 49 loss.eval() 50