metrics.py 22.9 KB
Newer Older
C
chenxuyi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 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.
C
chenxuyi 已提交
14
"""predefined metrics"""
C
chenxuyi 已提交
15 16 17

import sys
import os
C
chenxuyi 已提交
18 19
import six

C
chenxuyi 已提交
20 21 22 23 24 25 26 27
import numpy as np
import itertools
import logging

import paddle.fluid as F
import paddle.fluid.layers as L
import sklearn.metrics

M
Meiyim 已提交
28 29
from propeller.paddle.train import distribution  #import allgather, status, DistributionMode

C
chenxuyi 已提交
30 31 32 33 34 35 36 37
log = logging.getLogger(__name__)

__all__ = [
    'Metrics', 'F1', 'Recall', 'Precision', 'Mrr', 'Mean', 'Acc', 'ChunkF1',
    'RecallAtPrecision'
]


M
Meiyim 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
def _allgather_2dim(*args):
    log.info('distribution.status.mode : {}'.format(distribution.status.mode))
    if distribution.status.mode == distribution.DistributionMode.LOCAL:
        return args

    if distribution.status.num_replica == 1:
        return args

    for a in args:
        if len(a.shape) > 2:
            log.warn(
                'Metrics:%s have shape %s, cannot not be allgathered, will return to single card evaluation'
                % (a, a.shape))
        else:
            pass
            #log.debug('broadcast %s' % a)
    ret = [distribution.allgather(a) if len(a.shape) <= 2 else a for a in args]
    return ret


C
chenxuyi 已提交
58
class Metrics(object):
C
chenxuyi 已提交
59 60
    """Metrics base class"""

C
chenxuyi 已提交
61
    def __init__(self):
C
chenxuyi 已提交
62
        """doc"""
C
chenxuyi 已提交
63
        self.saver = []
M
Meiyim 已提交
64
        self.tensor = None
C
chenxuyi 已提交
65 66

    def update(self, *args):
C
chenxuyi 已提交
67
        """doc"""
C
chenxuyi 已提交
68 69 70
        pass

    def eval(self):
C
chenxuyi 已提交
71
        """doc"""
C
chenxuyi 已提交
72 73 74 75
        pass


class Mean(Metrics):
C
chenxuyi 已提交
76 77
    """doc"""

C
chenxuyi 已提交
78
    def __init__(self, t):
C
chenxuyi 已提交
79
        """doc"""
M
Meiyim 已提交
80
        self.t = _allgather_2dim(t)
C
chenxuyi 已提交
81 82 83
        self.reset()

    def reset(self):
C
chenxuyi 已提交
84
        """doc"""
C
chenxuyi 已提交
85 86 87 88
        self.saver = np.array([])

    @property
    def tensor(self):
C
chenxuyi 已提交
89
        """doc"""
M
Meiyim 已提交
90
        return self.t
C
chenxuyi 已提交
91 92

    def update(self, args):
C
chenxuyi 已提交
93
        """doc"""
C
chenxuyi 已提交
94 95 96 97 98
        t, = args
        t = t.reshape([-1])
        self.saver = np.concatenate([self.saver, t])

    def eval(self):
C
chenxuyi 已提交
99
        """doc"""
M
Meiyim 已提交
100
        log.debug(self.saver.shape)
C
chenxuyi 已提交
101 102 103 104
        return self.saver.mean()


class Ppl(Mean):
C
chenxuyi 已提交
105 106
    """doc"""

C
chenxuyi 已提交
107
    def eval(self):
C
chenxuyi 已提交
108
        """doc"""
C
chenxuyi 已提交
109 110 111 112
        return np.exp(self.saver.mean())


class Acc(Mean):
C
chenxuyi 已提交
113 114
    """doc"""

C
chenxuyi 已提交
115
    def __init__(self, label, pred):
C
chenxuyi 已提交
116
        """doc"""
M
Meiyim 已提交
117 118 119 120
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))
M
Meiyim 已提交
121
        self.eq = _allgather_2dim(L.cast(L.equal(pred, label), 'int64'))
C
chenxuyi 已提交
122 123 124 125
        self.reset()

    @property
    def tensor(self):
C
chenxuyi 已提交
126
        """doc"""
M
Meiyim 已提交
127
        return self.eq
C
chenxuyi 已提交
128 129 130


class MSE(Mean):
C
chenxuyi 已提交
131 132
    """doc"""

C
chenxuyi 已提交
133
    def __init__(self, label, pred):
C
chenxuyi 已提交
134
        """doc"""
M
Meiyim 已提交
135 136 137 138 139
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

C
chenxuyi 已提交
140 141 142 143 144 145
        diff = pred - label
        self.mse = diff * diff
        self.reset()

    @property
    def tensor(self):
C
chenxuyi 已提交
146
        """doc"""
C
chenxuyi 已提交
147 148 149 150
        return self.mse,


class Cosine(Mean):
C
chenxuyi 已提交
151 152
    """doc"""

C
chenxuyi 已提交
153
    def __init__(self, label, pred):
C
chenxuyi 已提交
154
        """doc"""
M
Meiyim 已提交
155 156 157 158 159
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

C
chenxuyi 已提交
160 161 162 163 164
        self.cos = L.cos_sim(label, pred)
        self.reset()

    @property
    def tensor(self):
C
chenxuyi 已提交
165
        """doc"""
C
chenxuyi 已提交
166 167 168
        return self.cos,


M
Meiyim 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
class MacroF1(Metrics):
    """doc"""

    def __init__(self, label, pred):
        """doc"""
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

        self.label = label
        self.pred = pred
        self.reset()

    def reset(self):
        """doc"""
        self.label_saver = np.array([], dtype=np.bool)
        self.pred_saver = np.array([], dtype=np.bool)

    @property
    def tensor(self):
        """doc"""
M
Meiyim 已提交
191
        return [self.label, self.pred]
M
Meiyim 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    def update(self, args):
        """doc"""
        label, pred = args
        label = label.reshape([-1]).astype(np.bool)
        pred = pred.reshape([-1]).astype(np.bool)
        if label.shape != pred.shape:
            raise ValueError(
                'Metrics precesion: input not match: label:%s pred:%s' %
                (label, pred))
        self.label_saver = np.concatenate([self.label_saver, label])
        self.pred_saver = np.concatenate([self.pred_saver, pred])

    def eval(self):
        """doc"""
        return sklearn.metrics.f1_score(
            self.label_saver, self.pred_saver, average='macro')


C
chenxuyi 已提交
211
class Precision(Metrics):
C
chenxuyi 已提交
212 213
    """doc"""

C
chenxuyi 已提交
214
    def __init__(self, label, pred):
C
chenxuyi 已提交
215
        """doc"""
M
Meiyim 已提交
216 217 218 219 220
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

C
chenxuyi 已提交
221 222 223
        self.label = label
        self.pred = pred
        self.reset()
M
Meiyim 已提交
224
        self.tensor = _allgather_2dim(self.pred, self.label)
C
chenxuyi 已提交
225 226

    def reset(self):
C
chenxuyi 已提交
227
        """doc"""
C
chenxuyi 已提交
228 229 230 231
        self.label_saver = np.array([], dtype=np.bool)
        self.pred_saver = np.array([], dtype=np.bool)

    def update(self, args):
C
chenxuyi 已提交
232
        """doc"""
M
Meiyim 已提交
233
        pred, label = args
C
chenxuyi 已提交
234 235 236 237 238 239 240 241 242 243
        label = label.reshape([-1]).astype(np.bool)
        pred = pred.reshape([-1]).astype(np.bool)
        if label.shape != pred.shape:
            raise ValueError(
                'Metrics precesion: input not match: label:%s pred:%s' %
                (label, pred))
        self.label_saver = np.concatenate([self.label_saver, label])
        self.pred_saver = np.concatenate([self.pred_saver, pred])

    def eval(self):
C
chenxuyi 已提交
244
        """doc"""
C
chenxuyi 已提交
245
        tp = (self.label_saver & self.pred_saver).astype(np.int64).sum()
J
Jason N 已提交
246 247
        p = self.pred_saver.astype(np.int64).sum()
        return tp / p
C
chenxuyi 已提交
248 249 250


class Recall(Precision):
C
chenxuyi 已提交
251 252
    """doc"""

C
chenxuyi 已提交
253
    def eval(self):
C
chenxuyi 已提交
254
        """doc"""
C
chenxuyi 已提交
255
        tp = (self.label_saver & self.pred_saver).astype(np.int64).sum()
J
Jason N 已提交
256 257
        t = (self.label_saver).astype(np.int64).sum()
        return tp / t
C
chenxuyi 已提交
258 259 260


class F1(Precision):
C
chenxuyi 已提交
261 262
    """doc"""

C
chenxuyi 已提交
263
    def eval(self):
C
chenxuyi 已提交
264
        """doc"""
C
chenxuyi 已提交
265 266 267
        tp = (self.label_saver & self.pred_saver).astype(np.int64).sum()
        t = self.label_saver.astype(np.int64).sum()
        p = self.pred_saver.astype(np.int64).sum()
J
Jason N 已提交
268 269
        precision = tp / (p + 1.e-6)
        recall = tp / (t + 1.e-6)
C
chenxuyi 已提交
270 271 272
        return 2 * precision * recall / (precision + recall + 1.e-6)


M
Meiyim 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
class MicroF1(Precision):
    """doc"""

    def update(self, args):
        """doc"""
        label, pred = args
        label = label.reshape([-1])
        pred = pred.reshape([-1])
        if label.shape != pred.shape:
            raise ValueError('Metrics f1: input not match: label:%s pred:%s' %
                             (label, pred))
        self.label_saver = np.concatenate([self.label_saver, label])
        self.pred_saver = np.concatenate([self.pred_saver, pred])

    def eval(self):
        """doc"""
        return sklearn.metrics.f1_score(
            self.label_saver, self.pred_saver, average='micro')


class MacroF1(Precision):
    def eval(self):
        """doc"""
        return sklearn.metrics.f1_score(
            self.label_saver, self.pred_saver, average='macro')


class MCC(Precision):
    """mathew corelation coefitient"""

    def eval(self):
        """doc"""
        return sklearn.metrics.matthews_corrcoef(self.label_saver,
                                                 self.pred_saver)


class PCC(Metrics):
    """pearson corelation coefitient"""

    def __init__(self, label, pred):
        """doc"""
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

        from scipy.stats import pearsonr
        self.pearsonr = pearsonr
        self.label = label
        self.pred = pred
        self.tensor = _allgather_2dim(self.pred, self.label)
        self.reset()

    def reset(self):
        """doc"""
        self.label_saver = np.array([], dtype=np.float)
        self.pred_saver = np.array([], dtype=np.float)

    def update(self, args):
        """doc"""
        pred, label = args
        label = label.reshape([-1]).astype(np.float)
        pred = pred.reshape([-1]).astype(np.float)
        if label.shape != pred.shape:
            raise ValueError('input not match: label:%s pred:%s' %
                             (label, pred))
        self.label_saver = np.concatenate([self.label_saver, label])
        self.pred_saver = np.concatenate([self.pred_saver, pred])

    def eval(self):
        """doc"""
        p, _ = self.pearsonr(self.label_saver, self.pred_saver)
        return p


C
chenxuyi 已提交
348
class Auc(Metrics):
C
chenxuyi 已提交
349 350
    """doc"""

C
chenxuyi 已提交
351
    def __init__(self, label, pred):
C
chenxuyi 已提交
352
        """doc"""
M
Meiyim 已提交
353 354 355 356 357
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

C
chenxuyi 已提交
358 359
        self.pred = pred
        self.label = label
M
Meiyim 已提交
360
        self.tensor = _allgather_2dim(self.pred, self.label)
C
chenxuyi 已提交
361 362 363
        self.reset()

    def reset(self):
C
chenxuyi 已提交
364
        """doc"""
C
chenxuyi 已提交
365 366 367 368
        self.pred_saver = np.array([], dtype=np.float32)
        self.label_saver = np.array([], dtype=np.bool)

    def update(self, args):
C
chenxuyi 已提交
369
        """doc"""
C
chenxuyi 已提交
370 371 372 373 374 375 376
        pred, label = args
        pred = pred.reshape([-1]).astype(np.float32)
        label = label.reshape([-1]).astype(np.bool)
        self.pred_saver = np.concatenate([self.pred_saver, pred])
        self.label_saver = np.concatenate([self.label_saver, label])

    def eval(self):
C
chenxuyi 已提交
377
        """doc"""
M
Meiyim 已提交
378
        log.debug(self.pred_saver.shape)
C
chenxuyi 已提交
379 380 381 382 383 384
        fpr, tpr, thresholds = sklearn.metrics.roc_curve(
            self.label_saver.astype(np.int64), self.pred_saver)
        auc = sklearn.metrics.auc(fpr, tpr)
        return auc


M
Meiyim 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
class BestAcc(Auc):
    """doc"""

    def eval(self):
        """doc"""
        thres = np.unique(self.pred_saver)
        best_thre = -1
        best_acc = -1

        num = 10000
        gap = len(thres) // num
        if gap > 0:
            thres = thres[::gap]

        for thre in thres:
            acc = 1. * np.sum(
                (self.pred_saver > thre
                 ) == self.label_saver.astype(np.bool)) / len(self.pred_saver)
            if acc > best_acc:
                best_thre = thre
                best_acc = acc
        return best_acc


C
chenxuyi 已提交
409
class RecallAtPrecision(Auc):
C
chenxuyi 已提交
410 411
    """doc"""

C
chenxuyi 已提交
412
    def __init__(self, label, pred, precision=0.9):
C
chenxuyi 已提交
413
        """doc"""
C
chenxuyi 已提交
414 415 416 417
        super(RecallAtPrecision, self).__init__(label, pred)
        self.precision = precision

    def eval(self):
C
chenxuyi 已提交
418
        """doc"""
C
chenxuyi 已提交
419 420 421 422 423 424 425 426 427 428
        self.pred_saver = self.pred_saver.reshape(
            [self.label_saver.size, -1])[:, -1]
        precision, recall, thresholds = sklearn.metrics.precision_recall_curve(
            self.label_saver, self.pred_saver)
        for p, r in zip(precision, recall):
            if p > self.precision:
                return r


class PrecisionAtThreshold(Auc):
C
chenxuyi 已提交
429 430
    """doc"""

C
chenxuyi 已提交
431
    def __init__(self, label, pred, threshold=0.5):
C
chenxuyi 已提交
432
        """doc"""
C
chenxuyi 已提交
433 434 435 436
        super().__init__(label, pred)
        self.threshold = threshold

    def eval(self):
C
chenxuyi 已提交
437
        """doc"""
C
chenxuyi 已提交
438 439 440 441 442 443 444
        infered = self.pred_saver > self.threshold
        correct_num = np.array(infered & self.label_saver).sum()
        infer_num = infered.sum()
        return correct_num / (infer_num + 1.e-6)


class Mrr(Metrics):
C
chenxuyi 已提交
445 446
    """doc"""

C
chenxuyi 已提交
447
    def __init__(self, qid, label, pred):
C
chenxuyi 已提交
448
        """doc"""
M
Meiyim 已提交
449 450 451 452 453
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

C
chenxuyi 已提交
454 455 456 457 458 459
        self.qid = qid
        self.label = label
        self.pred = pred
        self.reset()

    def reset(self):
C
chenxuyi 已提交
460
        """doc"""
C
chenxuyi 已提交
461 462 463 464 465 466
        self.qid_saver = np.array([], dtype=np.int64)
        self.label_saver = np.array([], dtype=np.int64)
        self.pred_saver = np.array([], dtype=np.float32)

    @property
    def tensor(self):
C
chenxuyi 已提交
467
        """doc"""
C
chenxuyi 已提交
468 469 470
        return [self.qid, self.label, self.pred]

    def update(self, args):
C
chenxuyi 已提交
471
        """doc"""
C
chenxuyi 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484
        qid, label, pred = args
        if not (qid.shape[0] == label.shape[0] == pred.shape[0]):
            raise ValueError(
                'Mrr dimention not match: qid[%s] label[%s], pred[%s]' %
                (qid.shape, label.shape, pred.shape))
        self.qid_saver = np.concatenate(
            [self.qid_saver, qid.reshape([-1]).astype(np.int64)])
        self.label_saver = np.concatenate(
            [self.label_saver, label.reshape([-1]).astype(np.int64)])
        self.pred_saver = np.concatenate(
            [self.pred_saver, pred.reshape([-1]).astype(np.float32)])

    def eval(self):
C
chenxuyi 已提交
485 486 487
        """doc"""

        def _key_func(tup):
C
chenxuyi 已提交
488 489
            return tup[0]

C
chenxuyi 已提交
490
        def _calc_func(tup):
C
chenxuyi 已提交
491 492 493 494 495 496
            ranks = [
                1. / (rank + 1.)
                for rank, (_, l, p) in enumerate(
                    sorted(
                        tup, key=lambda t: t[2], reverse=True)) if l != 0
            ]
C
chenxuyi 已提交
497 498 499 500
            if len(ranks):
                return ranks[0]
            else:
                return 0.
C
chenxuyi 已提交
501 502

        mrr_for_qid = [
C
chenxuyi 已提交
503
            _calc_func(tup)
C
chenxuyi 已提交
504 505 506
            for _, tup in itertools.groupby(
                sorted(
                    zip(self.qid_saver, self.label_saver, self.pred_saver),
C
chenxuyi 已提交
507 508
                    key=_key_func),
                key=_key_func)
C
chenxuyi 已提交
509 510 511 512 513 514
        ]
        mrr = np.float32(sum(mrr_for_qid) / len(mrr_for_qid))
        return mrr


class ChunkF1(Metrics):
C
chenxuyi 已提交
515 516
    """doc"""

C
chenxuyi 已提交
517
    def __init__(self, label, pred, seqlen, num_label):
C
chenxuyi 已提交
518
        """doc"""
C
chenxuyi 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
        self.label = label
        self.pred = pred
        self.seqlen = seqlen
        self.null_index = num_label - 1
        self.label_cnt = 0
        self.pred_cnt = 0
        self.correct_cnt = 0

    def _extract_bio_chunk(self, seq):
        chunks = []
        cur_chunk = None

        for index in range(len(seq)):
            tag = seq[index]
            tag_type = tag // 2
            tag_pos = tag % 2

            if tag == self.null_index:
                if cur_chunk is not None:
                    chunks.append(cur_chunk)
                    cur_chunk = None
                continue

            if tag_pos == 0:
                if cur_chunk is not None:
                    chunks.append(cur_chunk)
                    cur_chunk = {}
                cur_chunk = {"st": index, "en": index + 1, "type": tag_type}
            else:
                if cur_chunk is None:
                    cur_chunk = {
                        "st": index,
                        "en": index + 1,
                        "type": tag_type
                    }
                    continue

                if cur_chunk["type"] == tag_type:
                    cur_chunk["en"] = index + 1
                else:
                    chunks.append(cur_chunk)
                    cur_chunk = {
                        "st": index,
                        "en": index + 1,
                        "type": tag_type
                    }

        if cur_chunk is not None:
            chunks.append(cur_chunk)
        return chunks

    def reset(self):
C
chenxuyi 已提交
571
        """doc"""
C
chenxuyi 已提交
572 573 574 575 576 577
        self.label_cnt = 0
        self.pred_cnt = 0
        self.correct_cnt = 0

    @property
    def tensor(self):
C
chenxuyi 已提交
578
        """doc"""
C
chenxuyi 已提交
579 580 581
        return [self.pred, self.label, self.seqlen]

    def update(self, args):
C
chenxuyi 已提交
582
        """doc"""
C
chenxuyi 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
        pred, label, seqlen = args
        pred = pred.reshape([-1]).astype(np.int32).tolist()
        label = label.reshape([-1]).astype(np.int32).tolist()
        seqlen = seqlen.reshape([-1]).astype(np.int32).tolist()

        max_len = 0
        for l in seqlen:
            max_len = max(max_len, l)

        for i in range(len(seqlen)):
            seq_st = i * max_len + 1
            seq_en = seq_st + (seqlen[i] - 2)
            pred_chunks = self._extract_bio_chunk(pred[seq_st:seq_en])
            label_chunks = self._extract_bio_chunk(label[seq_st:seq_en])
            self.pred_cnt += len(pred_chunks)
            self.label_cnt += len(label_chunks)

            pred_index = 0
            label_index = 0
            while label_index < len(label_chunks) and pred_index < len(
                    pred_chunks):
                if pred_chunks[pred_index]['st'] < label_chunks[label_index][
                        'st']:
                    pred_index += 1
                elif pred_chunks[pred_index]['st'] > label_chunks[label_index][
                        'st']:
                    label_index += 1
                else:
                    if pred_chunks[pred_index]['en'] == label_chunks[label_index]['en'] \
                            and pred_chunks[pred_index]['type'] == label_chunks[label_index]['type']:
                        self.correct_cnt += 1
                    pred_index += 1
                    label_index += 1

    def eval(self):
C
chenxuyi 已提交
618
        """doc"""
C
chenxuyi 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
        if self.pred_cnt == 0:
            precision = 0.0
        else:
            precision = 1.0 * self.correct_cnt / self.pred_cnt

        if self.label_cnt == 0:
            recall = 0.0
        else:
            recall = 1.0 * self.correct_cnt / self.label_cnt

        if self.correct_cnt == 0:
            f1 = 0.0
        else:
            f1 = 2 * precision * recall / (precision + recall)

        return np.float32(f1)


class PNRatio(Metrics):
C
chenxuyi 已提交
638 639
    """doc"""

C
chenxuyi 已提交
640
    def __init__(self, qid, label, pred):
C
chenxuyi 已提交
641
        """doc"""
M
Meiyim 已提交
642 643 644 645 646
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

M
Meiyim 已提交
647
        self.qid, self.label, self.pred = _allgather_2dim(qid, label, pred)
C
chenxuyi 已提交
648 649 650
        self.saver = {}

    def reset(self):
C
chenxuyi 已提交
651
        """doc"""
C
chenxuyi 已提交
652 653 654 655
        self.saver = {}

    @property
    def tensor(self):
C
chenxuyi 已提交
656
        """doc"""
C
chenxuyi 已提交
657 658 659
        return [self.qid, self.label, self.pred]

    def update(self, args):
C
chenxuyi 已提交
660
        """doc"""
C
chenxuyi 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674
        qid, label, pred = args
        if not (qid.shape[0] == label.shape[0] == pred.shape[0]):
            raise ValueError('dimention not match: qid[%s] label[%s], pred[%s]'
                             % (qid.shape, label.shape, pred.shape))
        qid = qid.reshape([-1]).tolist()
        label = label.reshape([-1]).tolist()
        pred = pred.reshape([-1]).tolist()
        assert len(qid) == len(label) == len(pred)
        for q, l, p in zip(qid, label, pred):
            if q not in self.saver:
                self.saver[q] = []
            self.saver[q].append((l, p))

    def eval(self):
C
chenxuyi 已提交
675
        """doc"""
C
chenxuyi 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        p = 0
        n = 0
        for qid, outputs in self.saver.items():
            for i in range(0, len(outputs)):
                l1, p1 = outputs[i]
                for j in range(i + 1, len(outputs)):
                    l2, p2 = outputs[j]
                    if l1 > l2:
                        if p1 > p2:
                            p += 1
                        elif p1 < p2:
                            n += 1
                    elif l1 < l2:
                        if p1 < p2:
                            p += 1
                        elif p1 > p2:
                            n += 1
M
Meiyim 已提交
693
        pn = 1. * p / n if n > 0 else 0.0
C
chenxuyi 已提交
694 695 696 697
        return np.float32(pn)


class BinaryPNRatio(PNRatio):
C
chenxuyi 已提交
698 699
    """doc"""

C
chenxuyi 已提交
700
    def __init__(self, qid, label, pred):
C
chenxuyi 已提交
701
        """doc"""
C
chenxuyi 已提交
702 703 704
        super(BinaryPNRatio, self).__init__(qid, label, pred)

    def eval(self):
C
chenxuyi 已提交
705
        """doc"""
C
chenxuyi 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
        p = 0
        n = 0
        for qid, outputs in self.saver.items():
            pos_set = []
            neg_set = []
            for label, score in outputs:
                if label == 1:
                    pos_set.append(score)
                else:
                    neg_set.append(score)

            for ps in pos_set:
                for ns in neg_set:
                    if ps > ns:
                        p += 1
                    elif ps < ns:
                        n += 1
                    else:
                        continue
        pn = p / n if n > 0 else 0.0
        return np.float32(pn)


class PrecisionAtK(Metrics):
C
chenxuyi 已提交
730 731
    """doc"""

C
chenxuyi 已提交
732
    def __init__(self, qid, label, pred, k=1):
C
chenxuyi 已提交
733
        """doc"""
M
Meiyim 已提交
734 735 736 737 738
        if label.shape != pred.shape:
            raise ValueError(
                'expect label shape == pred shape, got: label.shape=%s, pred.shape = %s'
                % (repr(label), repr(pred)))

C
chenxuyi 已提交
739 740 741 742 743 744 745
        self.qid = qid
        self.label = label
        self.pred = pred
        self.k = k
        self.saver = {}

    def reset(self):
C
chenxuyi 已提交
746
        """doc"""
C
chenxuyi 已提交
747 748 749 750
        self.saver = {}

    @property
    def tensor(self):
C
chenxuyi 已提交
751
        """doc"""
C
chenxuyi 已提交
752 753 754
        return [self.qid, self.label, self.pred]

    def update(self, args):
C
chenxuyi 已提交
755
        """doc"""
C
chenxuyi 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
        qid, label, pred = args
        if not (qid.shape[0] == label.shape[0] == pred.shape[0]):
            raise ValueError('dimention not match: qid[%s] label[%s], pred[%s]'
                             % (qid.shape, label.shape, pred.shape))
        qid = qid.reshape([-1]).tolist()
        label = label.reshape([-1]).tolist()
        pred = pred.reshape([-1]).tolist()

        assert len(qid) == len(label) == len(pred)
        for q, l, p in zip(qid, label, pred):
            if q not in self.saver:
                self.saver[q] = []
            self.saver[q].append((l, p))

    def eval(self):
C
chenxuyi 已提交
771
        """doc"""
C
chenxuyi 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
        right = 0
        total = 0
        for v in self.saver.values():
            v = sorted(v, key=lambda x: x[1], reverse=True)
            k = min(self.k, len(v))
            for i in range(k):
                if v[i][0] == 1:
                    right += 1
                    break
            total += 1

        return np.float32(1.0 * right / total)


#class SemanticRecallMetrics(Metrics):
#    def __init__(self, qid, vec, type_id):
#        self.qid = qid
#        self.vec = vec
#        self.type_id = type_id
#        self.reset()
#
#    def reset(self):
#        self.saver = []
#
#    @property
#    def tensor(self):
#        return [self.qid, self.vec, self.type_id]
#
#    def update(self, args):
#        qid, vec, type_id = args
#        self.saver.append((qid, vec, type_id))
#
#    def eval(self):
#        dic = {}
#        for qid, vec, type_id in self.saver():
#            dic.setdefault(i, {}).setdefault(k, []).append(vec)
#        
#        for qid in dic:
#            assert len(dic[qid]) == 3
#            qvec = np.arrray(dic[qid][0])
#            assert len(qvec) == 1
#            ptvec = np.array(dic[qid][1])
#            ntvec = np.array(dic[qid][2])
#
#            np.matmul(qvec, np.transpose(ptvec))
#            np.matmul(qvec, np.transpose(ntvec))
#