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"""evaluation metric.""" 16 17from mindspore.communication.management import GlobalComm 18from mindspore.ops import operations as P 19import mindspore.nn as nn 20import mindspore.common.dtype as mstype 21 22 23class ClassifyCorrectCell(nn.Cell): 24 r""" 25 Cell that returns correct count of the prediction in classification network. 26 This Cell accepts a network as arguments. 27 It returns orrect count of the prediction to calculate the metrics. 28 29 Args: 30 network (Cell): The network Cell. 31 32 Inputs: 33 - **data** (Tensor) - Tensor of shape :math:`(N, \ldots)`. 34 - **label** (Tensor) - Tensor of shape :math:`(N, \ldots)`. 35 36 Outputs: 37 Tuple, containing a scalar correct count of the prediction 38 39 Examples: 40 >>> # For a defined network Net without loss function 41 >>> net = Net() 42 >>> eval_net = nn.ClassifyCorrectCell(net) 43 """ 44 45 def __init__(self, network): 46 super(ClassifyCorrectCell, self).__init__(auto_prefix=False) 47 self._network = network 48 self.argmax = P.Argmax() 49 self.equal = P.Equal() 50 self.cast = P.Cast() 51 self.reduce_sum = P.ReduceSum() 52 self.allreduce = P.AllReduce(P.ReduceOp.SUM, GlobalComm.WORLD_COMM_GROUP) 53 54 def construct(self, data, label): 55 outputs = self._network(data) 56 y_pred = self.argmax(outputs) 57 y_pred = self.cast(y_pred, mstype.int32) 58 y_correct = self.equal(y_pred, label) 59 y_correct = self.cast(y_correct, mstype.float32) 60 y_correct = self.reduce_sum(y_correct) 61 total_correct = self.allreduce(y_correct) 62 return (total_correct,) 63 64 65class DistAccuracy(nn.Metric): 66 r""" 67 Calculates the accuracy for classification data in distributed mode. 68 The accuracy class creates two local variables, correct number and total number that are used to compute the 69 frequency with which predictions matches labels. This frequency is ultimately returned as the accuracy: an 70 idempotent operation that simply divides correct number by total number. 71 72 .. math:: 73 74 \text{accuracy} =\frac{\text{true_positive} + \text{true_negative}} 75 76 {\text{true_positive} + \text{true_negative} + \text{false_positive} + \text{false_negative}} 77 78 Args: 79 eval_type (str): Metric to calculate the accuracy over a dataset, for classification (single-label). 80 81 Examples: 82 >>> y_correct = Tensor(np.array([20])) 83 >>> metric = nn.DistAccuracy(batch_size=3, device_num=8) 84 >>> metric.clear() 85 >>> metric.update(y_correct) 86 >>> accuracy = metric.eval() 87 """ 88 89 def __init__(self, batch_size, device_num): 90 super(DistAccuracy, self).__init__() 91 self.clear() 92 self.batch_size = batch_size 93 self.device_num = device_num 94 95 def clear(self): 96 """Clears the internal evaluation result.""" 97 self._correct_num = 0 98 self._total_num = 0 99 100 def update(self, *inputs): 101 """ 102 Updates the internal evaluation result :math:`y_{pred}` and :math:`y`. 103 104 Args: 105 inputs: Input `y_correct`. `y_correct` is a `scalar Tensor`. 106 `y_correct` is the right prediction count that gathered from all devices 107 it's a scalar in float type 108 109 Raises: 110 ValueError: If the number of the input is not 1. 111 """ 112 113 if len(inputs) != 1: 114 raise ValueError('Distribute accuracy needs 1 input (y_correct), but got {}'.format(len(inputs))) 115 y_correct = self._convert_data(inputs[0]) 116 self._correct_num += y_correct 117 self._total_num += self.batch_size * self.device_num 118 119 def eval(self): 120 """ 121 Computes the accuracy. 122 123 Returns: 124 Float, the computed result. 125 126 Raises: 127 RuntimeError: If the sample size is 0. 128 """ 129 130 if self._total_num == 0: 131 raise RuntimeError('Accuracy can not be calculated, because the number of samples is 0.') 132 return self._correct_num / self._total_num 133