pairwise_pn.py 3.8 KB
Newer Older
M
malin10 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import math

import numpy as np
import paddle.fluid as fluid

from paddlerec.core.metric import Metric
from paddle.fluid.initializer import Constant
from paddle.fluid.layer_helper import LayerHelper
M
malin10 已提交
23
from paddle.fluid.layers.tensor import Variable
M
malin10 已提交
24 25 26 27 28 29 30 31 32 33


class PosNegRatio(Metric):
    """
    Metric For Fluid Model
    """

    def __init__(self, **kwargs):
        """ """
        helper = LayerHelper("PaddleRec_PosNegRatio", **kwargs)
M
malin10 已提交
34 35 36
        if "pos_score" not in kwargs or "neg_score" not in kwargs:
            raise ValueError(
                "PosNegRatio expect pos_score and neg_score as inputs.")
M
malin10 已提交
37 38 39
        pos_score = kwargs.get('pos_score')
        neg_score = kwargs.get('neg_score')

M
malin10 已提交
40 41 42 43 44 45 46
        if not isinstance(pos_score, Variable):
            raise ValueError("pos_score must be Variable, but received %s" %
                             type(pos_score))
        if not isinstance(neg_score, Variable):
            raise ValueError("neg_score must be Variable, but received %s" %
                             type(neg_score))

M
malin10 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
        wrong = fluid.layers.cast(
            fluid.layers.less_equal(pos_score, neg_score), dtype='float32')
        wrong_cnt = fluid.layers.reduce_sum(wrong)
        right = fluid.layers.cast(
            fluid.layers.less_than(neg_score, pos_score), dtype='float32')
        right_cnt = fluid.layers.reduce_sum(right)

        global_right_cnt, _ = helper.create_or_get_global_variable(
            name="right_cnt", persistable=True, dtype='float32', shape=[1])
        global_wrong_cnt, _ = helper.create_or_get_global_variable(
            name="wrong_cnt", persistable=True, dtype='float32', shape=[1])

        for var in [global_right_cnt, global_wrong_cnt]:
            helper.set_variable_initializer(
                var, Constant(
                    value=0.0, force_cpu=True))

        helper.append_op(
            type="elementwise_add",
            inputs={"X": [global_right_cnt],
                    "Y": [right_cnt]},
            outputs={"Out": [global_right_cnt]})
        helper.append_op(
            type="elementwise_add",
            inputs={"X": [global_wrong_cnt],
                    "Y": [wrong_cnt]},
            outputs={"Out": [global_wrong_cnt]})
        self.pn = (global_right_cnt + 1.0) / (global_wrong_cnt + 1.0)

M
update  
malin10 已提交
76 77 78 79 80
        self._global_communicate_var = dict()
        self._global_communicate_var['right_cnt'] = (global_right_cnt.name,
                                                     "float32")
        self._global_communicate_var['wrong_cnt'] = (global_wrong_cnt.name,
                                                     "float32")
M
malin10 已提交
81 82

        self.metrics = dict()
M
update  
malin10 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95
        self.metrics['WrongCnt'] = global_wrong_cnt
        self.metrics['RightCnt'] = global_right_cnt
        self.metrics['PN'] = self.pn

    def calculate(self, global_metrics):
        for key in self._global_communicate_var:
            if key not in global_metrics:
                raise ValueError("%s not existed" % key)
        pn = (global_metrics['right_cnt'][0] + 1.0) / (
            global_metrics['wrong_cnt'][0] + 1.0)
        return "RightCnt=%s WrongCnt=%s PN=%s" % (
            str(global_metrics['right_cnt'][0]),
            str(global_metrics['wrong_cnt'][0]), str(pn))
M
malin10 已提交
96 97 98

    def get_result(self):
        return self.metrics