metric.py 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#   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.
X
xujiaqi01 已提交
14 15 16
"""Fleet Metrics"""

import math
17

X
xujiaqi01 已提交
18
import numpy as np
19

20
import paddle
21
from paddle.static import Variable
X
xujiaqi01 已提交
22

23 24
__all__ = []

X
xujiaqi01 已提交
25

T
tangwei12 已提交
26
def sum(input, scope=None, util=None):
X
xujiaqi01 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
    """
    distributed sum in fleet

    Args:
        input(numpy.array|Variable|string): output of a layer
        scope(Scope): specific scope

    Returns:
        global_metric(numpy.array): sum array

    Example:
        .. code-block:: python

          # in model.py
          input = fluid.layers.cast(some_input, dtype='float32')
42
          cnt = paddle.sum(input)
43
          global_cnt = paddle.static.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
H
HongyuJia 已提交
44
          tmp = paddle.add(cnt, global_cnt)
X
xujiaqi01 已提交
45
          fluid.layers.assign(tmp, global_cnt)
46

X
xujiaqi01 已提交
47 48
          # in train.py, after train or infer
          res = np.array(scope.find_var(global_cnt.name).get_tensor())
49
          print("sum array: ", paddle.distributed.fleet.sum(res))
X
xujiaqi01 已提交
50 51
    """
    if scope is None:
52
        scope = paddle.static.global_scope()
T
tangwei12 已提交
53
    if util is None:
54
        util = paddle.distributed.fleet.util
X
xujiaqi01 已提交
55 56 57 58 59 60
    if isinstance(input, Variable):
        input = np.array(scope.find_var(input.name).get_tensor())
    elif isinstance(input, str):
        input = np.array(scope.find_var(input).get_tensor())
    old_shape = np.array(input.shape)
    output = np.copy(input) * 0
T
tangwei12 已提交
61
    output = util.all_reduce(input, "sum")
X
xujiaqi01 已提交
62 63 64 65
    output = output.reshape(old_shape)
    return output


T
tangwei12 已提交
66
def max(input, scope=None, util=None):
X
xujiaqi01 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    """
    distributed max in fleet

    Args:
        input(numpy.array|Variable|string): output of a layer
        scope(Scope): specific scope

    Returns:
        global_metric(numpy.array): max array

    Example:
        .. code-block:: python

          # in model.py
          input = fluid.layers.cast(some_input, dtype='float32')
82
          cnt = paddle.sum(input)
83
          global_cnt = paddle.static.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
84
          tmp = paddle.maximum(cnt, global_cnt)
X
xujiaqi01 已提交
85 86 87 88
          fluid.layers.assign(tmp, global_cnt)

          # in train.py, after train or infer
          res = np.array(scope.find_var(global_cnt.name).get_tensor())
89
          print("max array: ", paddle.distributed.fleet.max(res))
X
xujiaqi01 已提交
90 91
    """
    if scope is None:
92
        scope = paddle.static.global_scope()
T
tangwei12 已提交
93
    if util is None:
94
        util = paddle.distributed.fleet.util
X
xujiaqi01 已提交
95 96 97 98 99 100
    if isinstance(input, Variable):
        input = np.array(scope.find_var(input.name).get_tensor())
    elif isinstance(input, str):
        input = np.array(scope.find_var(input).get_tensor())
    old_shape = np.array(input.shape)
    output = np.copy(input) * 0
T
tangwei12 已提交
101
    output = util.all_reduce(input, "max")
X
xujiaqi01 已提交
102 103 104 105
    output = output.reshape(old_shape)
    return output


T
tangwei12 已提交
106
def min(input, scope=None, util=None):
X
xujiaqi01 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    """
    distributed min in fleet

    Args:
        input(numpy.array|Variable|string): output of a layer
        scope(Scope): specific scope

    Returns:
        global_metric(numpy.array): min array

    Example:
        .. code-block:: python

          # in model.py
          input = fluid.layers.cast(some_input, dtype='float32')
122
          cnt = paddle.sum(input)
123
          global_cnt = paddle.static.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
H
HongyuJia 已提交
124
          tmp = paddle.minimum(cnt, global_cnt)
X
xujiaqi01 已提交
125 126 127 128
          fluid.layers.assign(tmp, global_cnt)

          # in train.py, after train or infer
          res = np.array(scope.find_var(global_cnt.name).get_tensor())
129
          print("min array: ", paddle.distributed.fleet.min(res))
X
xujiaqi01 已提交
130 131
    """
    if scope is None:
132
        scope = paddle.static.global_scope()
T
tangwei12 已提交
133
    if util is None:
134
        util = paddle.distributed.fleet.util
X
xujiaqi01 已提交
135 136 137 138 139 140
    if isinstance(input, Variable):
        input = np.array(scope.find_var(input.name).get_tensor())
    elif isinstance(input, str):
        input = np.array(scope.find_var(input).get_tensor())
    old_shape = np.array(input.shape)
    output = np.copy(input) * 0
T
tangwei12 已提交
141
    output = util.all_reduce(input, "min")
X
xujiaqi01 已提交
142 143 144 145
    output = output.reshape(old_shape)
    return output


T
tangwei12 已提交
146
def auc(stat_pos, stat_neg, scope=None, util=None):
X
xujiaqi01 已提交
147 148 149 150
    """
    distributed auc in fleet

    Args:
151 152
        stat_pos(numpy.array|Variable|string): stat_pos in output of paddle.static.auc
        stat_neg(numpy.array|Variable|string): stat_neg in output of paddle.static.auc
X
xujiaqi01 已提交
153 154 155 156 157 158 159 160 161
        scope(Scope): specific scope

    Returns:
        auc_value(float): auc value

    Example:
        .. code-block:: python

          # in model.py
162
          similarity_norm = fluid.layers.sigmoid(paddle.clip(output, min=-15.0, max=15.0))
X
xujiaqi01 已提交
163
          binary_predict = fluid.layers.concat(
H
HongyuJia 已提交
164
              input=[paddle.subtract(fluid.layers.ceil(similarity_norm), similarity_norm), similarity_norm], axis=1)
X
xujiaqi01 已提交
165
          self.auc, batch_auc, [batch_stat_pos, batch_stat_neg, stat_pos, stat_neg] =
166
              paddle.static.auc(input=binary_predict, label=label, curve='ROC', num_thresholds=4096)
X
xujiaqi01 已提交
167 168 169 170

          # in train.py, after train or infer
          pos = np.array(scope.find_var(stat_pos.name).get_tensor())
          neg = np.array(scope.find_var(stat_neg.name).get_tensor())
171
          print("auc: ", paddle.distributed.fleet.auc(pos, neg))
X
xujiaqi01 已提交
172 173
    """
    if scope is None:
174
        scope = paddle.static.global_scope()
T
tangwei12 已提交
175
    if util is None:
176
        util = paddle.distributed.fleet.util
T
tangwei12 已提交
177

X
xujiaqi01 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191
    if isinstance(stat_pos, Variable):
        stat_pos = np.array(scope.find_var(stat_pos.name).get_tensor())
    elif isinstance(stat_pos, str):
        stat_pos = np.array(scope.find_var(stat_pos).get_tensor())
    if isinstance(stat_neg, Variable):
        stat_neg = np.array(scope.find_var(stat_neg.name).get_tensor())
    elif isinstance(stat_neg, str):
        stat_neg = np.array(scope.find_var(stat_neg).get_tensor())
    # auc pos bucket shape
    old_pos_shape = np.array(stat_pos.shape)
    # reshape to one dim
    stat_pos = stat_pos.reshape(-1)
    global_pos = np.copy(stat_pos) * 0
    # mpi allreduce
T
tangwei12 已提交
192
    global_pos = util.all_reduce(stat_pos, "sum")
X
xujiaqi01 已提交
193 194 195 196 197 198
    global_pos = global_pos.reshape(old_pos_shape)

    # auc neg bucket
    old_neg_shape = np.array(stat_neg.shape)
    stat_neg = stat_neg.reshape(-1)
    global_neg = np.copy(stat_neg) * 0
T
tangwei12 已提交
199
    global_neg = util.all_reduce(stat_neg, "sum")
X
xujiaqi01 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    global_neg = global_neg.reshape(old_neg_shape)

    # calculate auc
    num_bucket = len(global_pos[0])
    area = 0.0
    pos = 0.0
    neg = 0.0
    new_pos = 0.0
    new_neg = 0.0
    total_ins_num = 0
    for i in range(num_bucket):
        index = num_bucket - 1 - i
        new_pos = pos + global_pos[0][index]
        total_ins_num += global_pos[0][index]
        new_neg = neg + global_neg[0][index]
        total_ins_num += global_neg[0][index]
        area += (new_neg - neg) * (pos + new_pos) / 2
        pos = new_pos
        neg = new_neg

    auc_value = None
    if pos * neg == 0 or total_ins_num == 0:
        auc_value = 0.5
    else:
        auc_value = area / (pos * neg)

    return auc_value


T
tangwei12 已提交
229
def mae(abserr, total_ins_num, scope=None, util=None):
X
xujiaqi01 已提交
230 231 232 233 234
    """
    distributed mae in fleet

    Args:
        abserr(numpy.array|Variable|string): abserr in output of fluid.contrib.layers.ctr_metric_bundle
235
        total_ins_num(numpy.array|Variable|string): total variable
X
xujiaqi01 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
        scope(Scope): specific scope

    Returns:
        mae(float): mae value

    Example:
        .. code-block:: python

          # in model.py
          sqrerr, abserr, prob, q, pos, total = fluid.contrib.layers.ctr_metric_bundle(similarity_norm, fluid.layers.cast(x=label, dtype='float32'))

          # in train.py, after train or infer
          res = np.array(scope.find_var(abserr.name).get_tensor())
249
          print("mae: ", paddle.distributed.fleet.mae(res, total_ins_num))
X
xujiaqi01 已提交
250 251
    """
    if scope is None:
252
        scope = paddle.static.global_scope()
T
tangwei12 已提交
253
    if util is None:
254
        util = paddle.distributed.fleet.util
T
tangwei12 已提交
255

X
xujiaqi01 已提交
256 257 258 259
    if isinstance(abserr, Variable):
        abserr = np.array(scope.find_var(abserr.name).get_tensor())
    elif isinstance(abserr, str):
        abserr = np.array(scope.find_var(abserr).get_tensor())
260 261
    if isinstance(total_ins_num, Variable):
        total_ins_num = np.array(
262 263
            scope.find_var(total_ins_num.name).get_tensor()
        )
264 265
    elif isinstance(total_ins_num, str):
        total_ins_num = np.array(scope.find_var(total_ins_num).get_tensor())
T
tangwei12 已提交
266

X
xujiaqi01 已提交
267 268 269
    old_metric_shape = np.array(abserr.shape)
    abserr = abserr.reshape(-1)
    global_metric = np.copy(abserr) * 0
T
tangwei12 已提交
270 271

    global_metric = util.all_reduce(abserr, "sum")
X
xujiaqi01 已提交
272
    global_metric = global_metric.reshape(old_metric_shape)
273
    global_total_num = util.all_reduce(total_ins_num, "sum")
T
tangwei12 已提交
274

275
    mae_value = float(global_metric[0]) / float(global_total_num[0])
X
xujiaqi01 已提交
276 277 278
    return mae_value


T
tangwei12 已提交
279
def rmse(sqrerr, total_ins_num, scope=None, util=None):
X
xujiaqi01 已提交
280 281 282 283 284
    """
    distributed rmse in fleet

    Args:
        sqrerr(numpy.array|Variable|string): sqrerr in output of fluid.contrib.layers.ctr_metric_bundle
285
        total_ins_num(numpy.array|Variable|string): total variable
X
xujiaqi01 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298
        scope(Scope): specific scope

    Returns:
        rmse(float): rmse value

    Example:
        .. code-block:: python

          # in model.py
          sqrerr, abserr, prob, q, pos, total = fluid.contrib.layers.ctr_metric_bundle(similarity_norm, fluid.layers.cast(x=label, dtype='float32'))

          # in train.py, after train or infer
          res = np.array(scope.find_var(sqrerr.name).get_tensor())
299
          print("rmse: ", paddle.distributed.fleet.rmse(res, total_ins_num))
X
xujiaqi01 已提交
300 301
    """
    if scope is None:
302
        scope = paddle.static.global_scope()
T
tangwei12 已提交
303
    if util is None:
304
        util = paddle.distributed.fleet.util
T
tangwei12 已提交
305

X
xujiaqi01 已提交
306 307 308 309
    if isinstance(sqrerr, Variable):
        sqrerr = np.array(scope.find_var(sqrerr.name).get_tensor())
    elif isinstance(sqrerr, str):
        sqrerr = np.array(scope.find_var(sqrerr).get_tensor())
310 311
    if isinstance(total_ins_num, Variable):
        total_ins_num = np.array(
312 313
            scope.find_var(total_ins_num.name).get_tensor()
        )
314 315
    elif isinstance(total_ins_num, str):
        total_ins_num = np.array(scope.find_var(total_ins_num).get_tensor())
X
xujiaqi01 已提交
316 317 318
    old_metric_shape = np.array(sqrerr.shape)
    sqrerr = sqrerr.reshape(-1)
    global_metric = np.copy(sqrerr) * 0
T
tangwei12 已提交
319 320

    global_metric = util.all_reduce(sqrerr, "sum")
X
xujiaqi01 已提交
321
    global_metric = global_metric.reshape(old_metric_shape)
322 323 324
    global_total_num = util.all_reduce(total_ins_num, "sum")

    rmse_value = math.sqrt(float(global_metric[0]) / float(global_total_num[0]))
T
tangwei12 已提交
325

X
xujiaqi01 已提交
326 327 328
    return rmse_value


T
tangwei12 已提交
329
def mse(sqrerr, total_ins_num, scope=None, util=None):
X
xujiaqi01 已提交
330 331 332 333 334
    """
    distributed mse in fleet

    Args:
        sqrerr(numpy.array|Variable|string): sqrerr in output of fluid.contrib.layers.ctr_metric_bundle
335
        total_ins_num(numpy.array|Variable|string): total variable
X
xujiaqi01 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348
        scope(Scope): specific scope

    Returns:
        mse(float): mse value

    Example:
        .. code-block:: python

          # in model.py
          sqrerr, abserr, prob, q, pos, total = fluid.contrib.layers.ctr_metric_bundle(similarity_norm, fluid.layers.cast(x=label, dtype='float32'))

          # in train.py, after train or infer
          metric = np.array(scope.find_var(sqrerr.name).get_tensor())
349
          print("mse: ", paddle.distributed.fleet.mse(metric, total_ins_num))
X
xujiaqi01 已提交
350 351
    """
    if scope is None:
352
        scope = paddle.static.global_scope()
T
tangwei12 已提交
353
    if util is None:
354
        util = paddle.distributed.fleet.util
T
tangwei12 已提交
355

X
xujiaqi01 已提交
356 357 358 359
    if isinstance(sqrerr, Variable):
        sqrerr = np.array(scope.find_var(sqrerr.name).get_tensor())
    elif isinstance(sqrerr, str):
        sqrerr = np.array(scope.find_var(sqrerr).get_tensor())
360 361
    if isinstance(total_ins_num, Variable):
        total_ins_num = np.array(
362 363
            scope.find_var(total_ins_num.name).get_tensor()
        )
364 365
    elif isinstance(total_ins_num, str):
        total_ins_num = np.array(scope.find_var(total_ins_num).get_tensor())
X
xujiaqi01 已提交
366 367 368
    old_metric_shape = np.array(sqrerr.shape)
    sqrerr = sqrerr.reshape(-1)
    global_metric = np.copy(sqrerr) * 0
T
tangwei12 已提交
369 370

    global_metric = util.all_reduce(sqrerr, "sum")
X
xujiaqi01 已提交
371
    global_metric = global_metric.reshape(old_metric_shape)
372
    global_total_num = util.all_reduce(total_ins_num, "sum")
T
tangwei12 已提交
373

374
    mse_value = float(global_metric[0]) / float(global_total_num[0])
X
xujiaqi01 已提交
375 376 377
    return mse_value


T
tangwei12 已提交
378
def acc(correct, total, scope=None, util=None):
X
xujiaqi01 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    """
    distributed accuracy in fleet

    Args:
        correct(numpy.array|Variable|string): correct Variable
        total(numpy.array|Variable): total Variable
        scope(Scope): specific scope

    Returns:
        acc(float): accuracy value

    Example:
        .. code-block:: python

          # in model.py
394 395
          correct = paddle.static.create_global_var(dtype='float32', shape=[1], value=0)
          total = paddle.static.create_global_var(dtype='float32', shape=[1], value=0)
X
xujiaqi01 已提交
396 397
          acc = fluid.layers.acc(predict, label, k=1, correct=correct, total=total)

398
          global_correct = paddle.static.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
H
HongyuJia 已提交
399
          tmp1 = paddle.minimum(correct, global_correct)
X
xujiaqi01 已提交
400 401
          fluid.layers.assign(tmp1, global_correct)

402
          global_total = paddle.static.create_global_var(persistable=True, dtype='float32', shape=[1], value=0)
H
HongyuJia 已提交
403
          tmp2 = paddle.minimum(total, global_total)
X
xujiaqi01 已提交
404 405 406 407 408
          fluid.layers.assign(tmp2, global_total)

          # in train.py, after train or infer
          correct_num = np.array(scope.find_var(correct.name).get_tensor())
          total_num = np.array(scope.find_var(total.name).get_tensor())
409
          print("accuracy: ", paddle.distributed.fleet.acc(correct_num, total_num))
X
xujiaqi01 已提交
410 411
    """
    if scope is None:
412
        scope = paddle.static.global_scope()
T
tangwei12 已提交
413
    if util is None:
414
        util = paddle.distributed.fleet.util
T
tangwei12 已提交
415

X
xujiaqi01 已提交
416 417 418 419 420 421 422 423
    if isinstance(correct, Variable):
        correct = np.array(scope.find_var(correct.name).get_tensor())
    elif isinstance(correct, str):
        correct = np.array(scope.find_var(correct).get_tensor())
    if isinstance(total, Variable):
        total = np.array(scope.find_var(total.name).get_tensor())
    elif isinstance(total, str):
        total = np.array(scope.find_var(total).get_tensor())
T
tangwei12 已提交
424

X
xujiaqi01 已提交
425 426
    global_correct_num = np.copy(correct) * 0
    global_total_num = np.copy(total) * 0
T
tangwei12 已提交
427 428 429 430

    global_correct_num = util.all_reduce(correct, "sum")
    global_total_num = util.all_reduce(total, "sum")

X
xujiaqi01 已提交
431
    return float(global_correct_num[0]) / float(global_total_num[0])