fluid.metrics¶
Accuracy¶

class
paddle.fluid.metrics.
Accuracy
(name=None)[source] This interface is used to calculate the mean accuracy over multiple batches. Accuracy object has two state: value and weight. The definition of Accuracy is available at https://en.wikipedia.org/wiki/Accuracy_and_precision
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
Examples
import paddle.fluid as fluid #suppose we have batch_size = 128 batch_size=128 accuracy_manager = fluid.metrics.Accuracy() #suppose the accuracy is 0.9 for the 1st batch batch1_acc = 0.9 accuracy_manager.update(value = batch1_acc, weight = batch_size) print("expect accuracy: %.2f, get accuracy: %.2f" % (batch1_acc, accuracy_manager.eval())) #suppose the accuracy is 0.8 for the 2nd batch batch2_acc = 0.8 accuracy_manager.update(value = batch2_acc, weight = batch_size) #the joint acc for batch1 and batch2 is (batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2 print("expect accuracy: %.2f, get accuracy: %.2f" % ((batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2, accuracy_manager.eval())) #reset the accuracy_manager accuracy_manager.reset() #suppose the accuracy is 0.8 for the 3rd batch batch3_acc = 0.8 accuracy_manager.update(value = batch3_acc, weight = batch_size) print("expect accuracy: %.2f, get accuracy: %.2f" % (batch3_acc, accuracy_manager.eval()))

update
(value, weight) This function takes the minibatch states (value, weight) as input, to accumulate and update the corresponding status of the Accuracy object. The update method is as follows:
\[\begin{split}\\ \begin{array}{l}{\text { self. value }+=\text { value } * \text { weight }} \\ {\text { self. weight }+=\text { weight }}\end{array} \\\end{split}\] Parameters
value (floatnumpy.array) – accuracy of one minibatch.
weight (intfloat) – minibatch size.

eval
() This function returns the mean accuracy (float or numpy.array) for all accumulated minibatches.
 Returns
mean accuracy for all accumulated minibatches.
 Return type
float or numpy.array

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None
Auc¶

class
paddle.fluid.metrics.
Auc
(name, curve='ROC', num_thresholds=4095)[source] The auc metric is for binary classification. Refer to https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve. Please notice that the auc metric is implemented with python, which may be a little bit slow. If you concern the speed, please use the fluid.layers.auc instead.
The auc function creates four local variables, true_positives, true_negatives, false_positives and false_negatives that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROCcurve is therefore computed using the height of the recall values by the false positive rate, while the area under the PRcurve is the computed using the height of the precision values by the recall.
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
curve (str) – Specifies the name of the curve to be computed, ‘ROC’ [default] or ‘PR’ for the PrecisionRecallcurve.
“NOTE: only implement the ROC curve type via Python now.”
Examples
import paddle.fluid as fluid import numpy as np # init the auc metric auc_metric = fluid.metrics.Auc("ROC") # suppose that batch_size is 128 batch_num = 100 batch_size = 128 for batch_id in range(batch_num): class0_preds = np.random.random(size = (batch_size, 1)) class1_preds = 1  class0_preds preds = np.concatenate((class0_preds, class1_preds), axis=1) labels = np.random.randint(2, size = (batch_size, 1)) auc_metric.update(preds = preds, labels = labels) # shall be some score closing to 0.5 as the preds are randomly assigned print("auc for iteration %d is %.2f" % (batch_id, auc_metric.eval()))

update
(preds, labels) Update the auc curve with the given predictions and labels.
 Parameters
preds (numpy.array) – an numpy array in the shape of (batch_size, 2), preds[i][j] denotes the probability of classifying the instance i into the class j.
labels (numpy.array) – an numpy array in the shape of (batch_size, 1), labels[i] is either o or 1, representing the label of the instance i.

eval
() Return the area (a float score) under auc curve
 Returns
the area under auc curve
 Return type
float

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None
ChunkEvaluator¶

class
paddle.fluid.metrics.
ChunkEvaluator
(name=None)[source] Accumulate counter numbers output by chunk_eval from minibatches and compute the precision recall and F1score using the accumulated counter numbers. ChunkEvaluator has three states: num_infer_chunks, num_label_chunks and num_correct_chunks, which correspond to the number of chunks, the number of labeled chunks, and the number of correctly identified chunks. For some basics of chunking, please refer to Chunking with Support Vector Machines . ChunkEvalEvaluator computes the precision, recall, and F1score of chunk detection, and supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes.
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
Examples
import paddle.fluid as fluid # init the chuncklevel evaluation manager metric = fluid.metrics.ChunkEvaluator() # suppose the model predict 10 chuncks, while 8 ones are correct and the ground truth has 9 chuncks. num_infer_chunks = 10 num_label_chunks = 9 num_correct_chunks = 8 metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks) numpy_precision, numpy_recall, numpy_f1 = metric.eval() print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1)) # the next batch, predicting 3 prefectly correct chuncks. num_infer_chunks = 3 num_label_chunks = 3 num_correct_chunks = 3 metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks) numpy_precision, numpy_recall, numpy_f1 = metric.eval() print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1))

update
(num_infer_chunks, num_label_chunks, num_correct_chunks) This function takes (num_infer_chunks, num_label_chunks, num_correct_chunks) as input, to accumulate and update the corresponding status of the ChunkEvaluator object. The update method is as follows:
\[\begin{split}\\ \begin{array}{l}{\text { self. num_infer_chunks }+=\text { num_infer_chunks }} \\ {\text { self. num_Label_chunks }+=\text { num_label_chunks }} \\ {\text { self. num_correct_chunks }+=\text { num_correct_chunks }}\end{array} \\\end{split}\] Parameters
num_infer_chunks (intnumpy.array) – The number of chunks in Inference on the given minibatch.
num_label_chunks (intnumpy.array) – The number of chunks in Label on the given minibatch.
num_correct_chunks (intfloatnumpy.array) – The number of chunks both in Inference and Label on the given minibatch.

eval
() This function returns the mean precision, recall and f1 score for all accumulated minibatches.
 Returns
mean precision, recall and f1 score.
 Return type
float

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None
CompositeMetric¶

class
paddle.fluid.metrics.
CompositeMetric
(name=None)[source] This op creates a container that contains the union of all the added metrics. After the metrics added in, calling eval() method will compute all the contained metrics automatically. CAUTION: only metrics with the SAME argument list can be added in a CompositeMetric instance.
Inherit from: MetricBase
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
Examples

add_metric
(metric) Add a new metric to container. Noted that the argument list of the added one should be consistent with existed ones.
 Parameters
metric (MetricBase) – a instance of MetricBase

update
(preds, labels) Update the metrics of this container.
 Parameters
preds (numpy.array) – predicted results of current minibatch, the shape and dtype of which should meet the requirements of the corresponded metric.
labels (numpy.array) – ground truth of current minibatch, the shape and dtype of which should meet the requirements of the corresponded metric.

eval
() Calculate the results of all metrics sequentially.
 Returns
results of all added metrics. The shape and dtype of each result depend on the defination of its metric.
 Return type
list

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None
DetectionMAP¶

class
paddle.fluid.metrics.
DetectionMAP
(input, gt_label, gt_box, gt_difficult=None, class_num=None, background_label=0, overlap_threshold=0.5, evaluate_difficult=True, ap_version='integral')[source] Calculate the detection mean average precision (mAP).
The general steps are as follows:
calculate the true positive and false positive according to the input of detection and labels.
calculate mAP value, support two versions: ‘11 point’ and ‘integral’. 11point: the 11point interpolated average precision. integral: the natural integral of the precisionrecall curve.
Please get more information from the following articles:
 Parameters
input (Variable) – LoDTensor, The detection results, which is a LoDTensor with shape [M, 6]. The layout is [label, confidence, xmin, ymin, xmax, ymax]. The data type is float32 or float64.
gt_label (Variable) – LoDTensor, The ground truth label index, which is a LoDTensor with shape [N, 1].The data type is float32 or float64.
gt_box (Variable) – LoDTensor, The ground truth bounding box (bbox), which is a LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax]. The data type is float32 or float64.
gt_difficult (VariableNone) – LoDTensor, Whether this ground truth is a difficult bounding bbox, which can be a LoDTensor [N, 1] or not set. If None, it means all the ground truth labels are not difficult bbox.The data type is int.
class_num (int) – The class number.
background_label (int) – The index of background label, the background label will be ignored. If set to 1, then all categories will be considered, 0 by default.
overlap_threshold (float) – The threshold for deciding true/false positive, 0.5 by default.
evaluate_difficult (bool) – Whether to consider difficult ground truth for evaluation, True by default. This argument does not work when gt_difficult is None.
ap_version (str) – The average precision calculation ways, it must be ‘integral’ or ‘11point’. Please check https://sanchom.wordpress.com/tag/averageprecision/ for details.
Examples
import paddle.fluid as fluid batch_size = None # can be any size image_boxs_num = 10 bounding_bboxes_num = 21 pb = fluid.data(name='prior_box', shape=[image_boxs_num, 4], dtype='float32') pbv = fluid.data(name='prior_box_var', shape=[image_boxs_num, 4], dtype='float32') loc = fluid.data(name='target_box', shape=[batch_size, bounding_bboxes_num, 4], dtype='float32') scores = fluid.data(name='scores', shape=[batch_size, bounding_bboxes_num, image_boxs_num], dtype='float32') nmsed_outs = fluid.layers.detection_output(scores=scores, loc=loc, prior_box=pb, prior_box_var=pbv) gt_box = fluid.data(name="gt_box", shape=[batch_size, 4], dtype="float32") gt_label = fluid.data(name="gt_label", shape=[batch_size, 1], dtype="float32") difficult = fluid.data(name="difficult", shape=[batch_size, 1], dtype="float32") exe = fluid.Executor(fluid.CUDAPlace(0)) map_evaluator = fluid.metrics.DetectionMAP(nmsed_outs, gt_label, gt_box, difficult, class_num = 3) cur_map, accum_map = map_evaluator.get_map_var()

get_map_var
()  Returns: mAP variable of current minibatch and
accumulative mAP variable cross minibatches.

reset
(executor, reset_program=None) Reset metric states at the begin of each pass/user specified batch. :param executor: a executor for executing
the reset_program.
 Parameters
reset_program (ProgramNone) – a single Program for reset process. If None, will create a Program.
EditDistance¶

class
paddle.fluid.metrics.
EditDistance
(name)[source] This API is for the management of edit distances. Editing distance is a method to quantify the degree of dissimilarity between two strings, such as words, by calculating the minimum editing operand (add, delete or replace) required to convert one string into another. Refer to https://en.wikipedia.org/wiki/Edit_distance.
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
Examples
import paddle.fluid as fluid import numpy as np # suppose that batch_size is 128 batch_size = 128 # init the edit distance manager distance_evaluator = fluid.metrics.EditDistance("EditDistance") # generate the edit distance across 128 sequence pairs, the max distance is 10 here edit_distances_batch0 = np.random.randint(low = 0, high = 10, size = (batch_size, 1)) seq_num_batch0 = batch_size distance_evaluator.update(edit_distances_batch0, seq_num_batch0) avg_distance, wrong_instance_ratio = distance_evaluator.eval() print("the average edit distance for batch0 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio)) edit_distances_batch1 = np.random.randint(low = 0, high = 10, size = (batch_size, 1)) seq_num_batch1 = batch_size distance_evaluator.update(edit_distances_batch1, seq_num_batch1) avg_distance, wrong_instance_ratio = distance_evaluator.eval() print("the average edit distance for batch0 and batch1 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio)) distance_evaluator.reset() edit_distances_batch2 = np.random.randint(low = 0, high = 10, size = (batch_size, 1)) seq_num_batch2 = batch_size distance_evaluator.update(edit_distances_batch2, seq_num_batch2) avg_distance, wrong_instance_ratio = distance_evaluator.eval() print("the average edit distance for batch2 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))

update
(distances, seq_num) Update the overall edit distance
 Parameters
distances (numpy.array) – a (batch_size, 1) numpy.array, each element represents the edit distance between two sequences.
seq_num (intfloat) – standing for the number of sequence pairs.

eval
() Return two floats: avg_distance: the average distance for all sequence pairs updated using the update function. avg_instance_error: the ratio of sequence pairs whose edit distance is not zero.

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None
MetricBase¶

class
paddle.fluid.metrics.
MetricBase
(name)[source] In many cases, we usually have to split the test data into minibatches for evaluating deep neural networks, therefore we need to collect the evaluation results of each minibatch and aggregate them into the final result. The paddle.fluid.metrics is designed for a convenient way of deep neural network evaluation.
The paddle.fluid.metrics contains serval different evaluation metrics like precision and recall, and most of them have the following functions:
1. take the prediction result and the corresponding labels of a minibatch as input, then compute the evaluation result for the input minibatch.
aggregate the existing evaluation results as the overall performance.
The class Metric is the base class for all classes in paddle.fluid.metrics, it defines the fundmental APIs for all metrics classes, including:
1. update(preds, labels): given the prediction results (preds) and the labels (labels) of some minibatch, compute the evaluation result of that minibatch, and memorize the evaluation result.
2. eval(): aggregate all existing evaluation result in the memory, and return the overall performance across different minibatches.
reset(): empty the memory.

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

update
(preds, labels) Given the prediction results (preds) and the labels (labels) of some minibatch, compute the evaluation result of that minibatch, and memorize the evaluation result. Please notice that the update function only memorizes the evaluation result but would not return the score. If you want to get the evaluation result, please call eval() function.
 Parameters
preds (numpy.array) – the predictions of current minibatch
labels (numpy.array) – the labels of current minibatch.
 Returns
None
 Return types:
None

eval
() Aggregate all existing evaluation results in the memory, and return the overall performance across different minibatches.
 Parameters
None –
 Returns
The overall performance across different minibatches.
 Return types:
floatlist(float)numpy.array: the metrics via Python.
Precision¶

class
paddle.fluid.metrics.
Precision
(name=None)[source] Precision (also called positive predictive value) is the fraction of relevant instances among the retrieved instances. Refer to https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers
Noted that this class mangages the precision score only for binary classification task.
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
Examples
import paddle.fluid as fluid import numpy as np metric = fluid.metrics.Precision() # generate the preds and labels preds = [[0.1], [0.7], [0.8], [0.9], [0.2], [0.2], [0.3], [0.5], [0.8], [0.6]] labels = [[0], [1], [1], [1], [1], [0], [0], [0], [0], [0]] preds = np.array(preds) labels = np.array(labels) metric.update(preds=preds, labels=labels) numpy_precision = metric.eval() print("expect precision: %.2f and got %.2f" % ( 3.0 / 5.0, numpy_precision))

update
(preds, labels) Update the precision based on the current minibatch prediction results .
 Parameters
preds (numpy.ndarray) – prediction results of current minibatch, the output of twoclass sigmoid function. Shape: [batch_size, 1]. Dtype: ‘float64’ or ‘float32’.
labels (numpy.ndarray) – ground truth (labels) of current minibatch, the shape should keep the same as preds. Shape: [batch_size, 1], Dtype: ‘int32’ or ‘int64’.

eval
() Calculate the final precision.
 Returns
Results of the calculated Precision. Scalar output with float dtype.
 Return type
float

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None
Recall¶

class
paddle.fluid.metrics.
Recall
(name=None)[source] Recall (also known as sensitivity) is the fraction of relevant instances that have been retrieved over the total amount of relevant instances
Refer to: https://en.wikipedia.org/wiki/Precision_and_recall
Noted that this class mangages the recall score only for binary classification task.
 Parameters
name (str, optional) – Metric name. For details, please refer to api_guide_Name. Default is None.
Examples
import paddle.fluid as fluid import numpy as np metric = fluid.metrics.Recall() # generate the preds and labels preds = [[0.1], [0.7], [0.8], [0.9], [0.2], [0.2], [0.3], [0.5], [0.8], [0.6]] labels = [[0], [1], [1], [1], [1], [0], [0], [0], [0], [0]] preds = np.array(preds) labels = np.array(labels) metric.update(preds=preds, labels=labels) numpy_recall = metric.eval() print("expect recall: %.2f and got %.2f" % ( 3.0 / 4.0, numpy_recall))

update
(preds, labels) Update the recall based on the current minibatch prediction results.
 Parameters
preds (numpy.array) – prediction results of current minibatch, the output of twoclass sigmoid function. Shape: [batch_size, 1]. Dtype: ‘float64’ or ‘float32’.
labels (numpy.array) – ground truth (labels) of current minibatch, the shape should keep the same as preds. Shape: [batch_size, 1], Dtype: ‘int32’ or ‘int64’.

eval
() Calculate the final recall.
 Returns
results of the calculated Recall. Scalar output with float dtype.
 Return type
float

get_config
() Get the metric and current states. The states are the members who do not has “_” prefix.
 Parameters
None –
 Returns
a python dict, which costains the inner states of the metric instance
 Return types:
a python dict

reset
() reset function empties the evaluation memory for previous minibatches.
 Parameters
None –
 Returns
None
 Return types:
None