base_component.py 19.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2020 VisualDL Authors. All Rights Reserve.
#
# 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 numpy as np
from PIL import Image

C
chenjian 已提交
18 19
from visualdl.proto.record_pb2 import Record

20

C
chenjian 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
def scalars(main_tag, tag_scalar_dict, step, walltime=None):
    """Package data to scalars

    Args:
        main_tag (string): Data identifier
        tag_scalar_dict (dict): A dict to provide multi-values with tags
        step (int): Step of scalar
        walltime (int): Wall time of scalar

    Return:
        Package with format of record_pb2.Record
    """
    for sub_tag, value in tag_scalar_dict.items():
        value = float(value)
        yield Record(values=[
            Record.Value(
                id=step,
                tag=main_tag,
                timestamp=walltime,
                tag_value=Record.TagValue(tag=sub_tag, value=value))
        ])


44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
def scalar(tag, value, step, walltime=None):
    """Package data to one scalar.
    Args:
        tag (string): Data identifier
        value (float): Value of scalar
        step (int): Step of scalar
        walltime (int): Wall time of scalar

    Return:
        Package with format of record_pb2.Record
    """
    value = float(value)
    return Record(values=[
        Record.Value(id=step, tag=tag, timestamp=walltime, value=value)
    ])


走神的阿圆's avatar
走神的阿圆 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
def meta_data(tag='meta_data_tag', display_name="", step=0, walltime=None):
    """Package data to one meta_data.

    Meta data is info for one record file, include `display_name` etc.

    Args:
        tag (string): Data identifier
        display_name (string): Replace
        step (int): Step of scalar
        walltime (int): Wall time of scalar

    Return:
        Package with format of record_pb2.Record
    """
    meta = Record.MetaData(display_name=display_name)
    return Record(values=[
C
chenjian 已提交
77
        Record.Value(id=step, tag=tag, timestamp=walltime, meta_data=meta)
走神的阿圆's avatar
走神的阿圆 已提交
78 79 80
    ])


81 82 83 84
def imgarray2bytes(np_array):
    """Convert image ndarray to bytes.

    Args:
85
        np_array (np.ndarray): Array to converte.
86 87 88 89

    Returns:
        Binary bytes of np_array.
    """
90 91 92 93 94 95 96 97 98 99 100 101
    try:
        import cv2

        np_array = cv2.cvtColor(np_array, cv2.COLOR_BGR2RGB)
        ret, buf = cv2.imencode(".png", np_array)
        img_bin = Image.fromarray(np.uint8(buf)).tobytes("raw")
    except ImportError:
        import io
        im = Image.fromarray(np_array)
        with io.BytesIO() as fp:
            im.save(fp, format='png')
            img_bin = fp.getvalue()
102 103 104
    return img_bin


P
Peter Pan 已提交
105
def make_grid(I, ncols=8):  # noqa: E741
C
chenjian 已提交
106 107
    assert isinstance(I,
                      np.ndarray), 'plugin error, should pass numpy array here'
走神的阿圆's avatar
走神的阿圆 已提交
108
    if I.shape[1] == 1:
P
Peter Pan 已提交
109
        I = np.concatenate([I, I, I], 1)  # noqa: E741
走神的阿圆's avatar
走神的阿圆 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    assert I.ndim == 4 and I.shape[1] == 3 or I.shape[1] == 4
    nimg = I.shape[0]
    H = I.shape[2]
    W = I.shape[3]
    ncols = min(nimg, ncols)
    nrows = int(np.ceil(float(nimg) / ncols))
    canvas = np.zeros((I.shape[1], H * nrows, W * ncols), dtype=I.dtype)
    i = 0
    for y in range(nrows):
        for x in range(ncols):
            if i >= nimg:
                break
            canvas[:, y * H:(y + 1) * H, x * W:(x + 1) * W] = I[i]
            i = i + 1
    return canvas


def convert_to_HWC(tensor, input_format):
    """Convert `NCHW`, `HWC`, `HW` to `HWC`

    Args:
131
        tensor (np.ndarray): Value of image
走神的阿圆's avatar
走神的阿圆 已提交
132 133 134 135 136
        input_format (string): Format of image

    Return:
        Image of format `HWC`.
    """
C
chenjian 已提交
137 138
    assert (len(set(input_format)) == len(input_format)
            ), "You can not use the same dimension shordhand twice. \
走神的阿圆's avatar
走神的阿圆 已提交
139
        input_format: {}".format(input_format)
C
chenjian 已提交
140 141
    assert (len(tensor.shape) == len(input_format)
            ), "size of input tensor and input format are different. \
走神的阿圆's avatar
走神的阿圆 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154
        tensor shape: {}, input_format: {}".format(tensor.shape, input_format)
    input_format = input_format.upper()

    if len(input_format) == 4:
        index = [input_format.find(c) for c in 'NCHW']
        tensor_NCHW = tensor.transpose(index)
        tensor_CHW = make_grid(tensor_NCHW)
        return tensor_CHW.transpose(1, 2, 0)

    if len(input_format) == 3:
        index = [input_format.find(c) for c in 'HWC']
        tensor_HWC = tensor.transpose(index)
        if tensor_HWC.shape[2] == 1:
C
chenjian 已提交
155 156
            tensor_HWC = np.concatenate([tensor_HWC, tensor_HWC, tensor_HWC],
                                        2)
走神的阿圆's avatar
走神的阿圆 已提交
157 158 159 160 161 162 163 164 165
        return tensor_HWC

    if len(input_format) == 2:
        index = [input_format.find(c) for c in 'HW']
        tensor = tensor.transpose(index)
        tensor = np.stack([tensor, tensor, tensor], 2)
        return tensor


166 167 168 169 170 171 172 173 174 175 176 177 178 179
def denormalization(image_array):
    """Renormalise ndarray matrix.

    Args:
        image_array(np.ndarray): Value of image

    Return:
        Matrix after renormalising.
    """
    if image_array.max() <= 1 and image_array.min() >= 0:
        image_array *= 255
    return image_array.astype(np.uint8)


走神的阿圆's avatar
走神的阿圆 已提交
180
def image(tag, image_array, step, walltime=None, dataformats="HWC"):
181 182 183 184
    """Package data to one image.

    Args:
        tag (string): Data identifier
185
        image_array (np.ndarray): Value of image
186 187
        step (int): Step of image
        walltime (int): Wall time of image
188
        dataformats (string): Format of image
189 190 191 192

    Return:
        Package with format of record_pb2.Record
    """
193
    image_array = denormalization(image_array)
走神的阿圆's avatar
走神的阿圆 已提交
194
    image_array = convert_to_HWC(image_array, dataformats)
195 196 197 198 199 200 201
    image_bytes = imgarray2bytes(image_array)
    image = Record.Image(encoded_image_string=image_bytes)
    return Record(values=[
        Record.Value(id=step, tag=tag, timestamp=walltime, image=image)
    ])


202
def embedding(tag, labels, hot_vectors, step, labels_meta=None, walltime=None):
203 204 205 206
    """Package data to one embedding.

    Args:
        tag (string): Data identifier
207
        labels (list): A list of labels.
208
        hot_vectors (np.array or list): A matrix which each row is
209 210 211 212 213 214 215 216 217
            feature of labels.
        step (int): Step of embeddings.
        walltime (int): Wall time of embeddings.

    Return:
        Package with format of record_pb2.Record
    """
    embeddings = Record.Embeddings()

218 219 220 221 222 223 224 225 226 227 228
    if labels_meta:
        embeddings.label_meta.extend(labels_meta)

    if isinstance(labels[0], list):
        temp = []
        for index in range(len(labels[0])):
            temp.append([label[index] for label in labels])
        labels = temp
    for label, hot_vector in zip(labels, hot_vectors):
        if not isinstance(label, list):
            label = [label]
C
chenjian 已提交
229 230
        embeddings.embeddings.append(
            Record.Embedding(label=label, vectors=hot_vector))
231 232 233 234 235 236 237 238 239 240 241 242

    return Record(values=[
        Record.Value(
            id=step, tag=tag, timestamp=walltime, embeddings=embeddings)
    ])


def audio(tag, audio_array, sample_rate, step, walltime):
    """Package data to one audio.

    Args:
        tag (string): Data identifier
243
        audio_array (np.ndarray or list): audio represented by a np.array
244 245 246 247 248 249 250
        sample_rate (int): Sample rate of audio
        step (int): Step of audio
        walltime (int): Wall time of audio

    Return:
        Package with format of record_pb2.Record
    """
走神的阿圆's avatar
走神的阿圆 已提交
251 252 253 254 255 256 257 258
    audio_array = audio_array.squeeze()
    if abs(audio_array).max() > 1:
        print('warning: audio amplitude out of range, auto clipped.')
        audio_array = audio_array.clip(-1, 1)
    assert (audio_array.ndim == 1), 'input tensor should be 1 dimensional.'

    audio_array = [int(32767.0 * x) for x in audio_array]

259 260
    import io
    import wave
走神的阿圆's avatar
走神的阿圆 已提交
261
    import struct
262 263 264 265 266 267

    fio = io.BytesIO()
    wave_writer = wave.open(fio, 'wb')
    wave_writer.setnchannels(1)
    wave_writer.setsampwidth(2)
    wave_writer.setframerate(sample_rate)
走神的阿圆's avatar
走神的阿圆 已提交
268 269 270
    audio_enc = b''
    audio_enc += struct.pack("<" + "h" * len(audio_array), *audio_array)
    wave_writer.writeframes(audio_enc)
271 272 273 274 275 276 277 278 279 280 281 282
    wave_writer.close()
    audio_string = fio.getvalue()
    fio.close()
    audio_data = Record.Audio(
        sample_rate=sample_rate,
        num_channels=1,
        length_frames=len(audio_array),
        encoded_audio_string=audio_string,
        content_type='audio/wav')
    return Record(values=[
        Record.Value(id=step, tag=tag, timestamp=walltime, audio=audio_data)
    ])
283 284


走神的阿圆's avatar
走神的阿圆 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
def text(tag, text_string, step, walltime=None):
    """Package data to one image.
    Args:
        tag (string): Data identifier
        text_string (string): Value of text
        step (int): Step of text
        walltime (int): Wall time of text
    Return:
        Package with format of record_pb2.Record
    """
    _text = Record.Text(encoded_text_string=text_string)
    return Record(values=[
        Record.Value(id=step, tag=tag, timestamp=walltime, text=_text)
    ])


301
def histogram(tag, hist, bin_edges, step, walltime):
走神的阿圆's avatar
走神的阿圆 已提交
302 303 304 305
    """Package data to one histogram.

    Args:
        tag (string): Data identifier
306 307
        hist (np.ndarray or list): The values of the histogram
        bin_edges (np.ndarray or list): The bin edges
走神的阿圆's avatar
走神的阿圆 已提交
308 309 310 311 312 313
        step (int): Step of histogram
        walltime (int): Wall time of histogram

    Return:
        Package with format of record_pb2.Record
    """
314 315 316 317 318
    histogram = Record.Histogram(hist=hist, bin_edges=bin_edges)
    return Record(values=[
        Record.Value(
            id=step, tag=tag, timestamp=walltime, histogram=histogram)
    ])
走神的阿圆's avatar
走神的阿圆 已提交
319 320


走神的阿圆's avatar
走神的阿圆 已提交
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 348 349 350 351 352
def hparam(name, hparam_dict, metric_list, walltime):
    """Package data to one histogram.

    Args:
        name (str): Name of hparam.
        hparam_dict (dictionary): Each key-value pair in the dictionary is the
              name of the hyper parameter and it's corresponding value. The type of the value
              can be one of `bool`, `string`, `float`, `int`, or `None`.
        metric_list (list): Name of all metrics.
        walltime (int): Wall time of hparam.

    Return:
        Package with format of record_pb2.Record
    """

    hm = Record.HParam()
    hm.name = name
    for k, v in hparam_dict.items():
        if v is None:
            continue
        hparamInfo = Record.HParam.HparamInfo()
        hparamInfo.name = k
        if isinstance(v, int):
            hparamInfo.int_value = v
            hm.hparamInfos.append(hparamInfo)
        elif isinstance(v, float):
            hparamInfo.float_value = v
            hm.hparamInfos.append(hparamInfo)
        elif isinstance(v, str):
            hparamInfo.string_value = v
            hm.hparamInfos.append(hparamInfo)
        else:
C
chenjian 已提交
353 354
            print("The value of %s must be int, float or str, not %s" %
                  (k, str(type(v))))
走神的阿圆's avatar
走神的阿圆 已提交
355 356 357 358 359 360 361
    for metric in metric_list:
        metricInfo = Record.HParam.HparamInfo()
        metricInfo.name = metric
        metricInfo.float_value = 0
        hm.metricInfos.append(metricInfo)

    return Record(values=[
C
chenjian 已提交
362
        Record.Value(id=1, tag="hparam", timestamp=walltime, hparam=hm)
走神的阿圆's avatar
走神的阿圆 已提交
363 364 365
    ])


走神的阿圆's avatar
走神的阿圆 已提交
366 367 368 369
def compute_curve(labels, predictions, num_thresholds=None, weights=None):
    """ Compute precision-recall curve data by labels and predictions.

    Args:
370 371
        labels (np.ndarray or list): Binary labels for each element.
        predictions (np.ndarray or list): The probability that an element be
走神的阿圆's avatar
走神的阿圆 已提交
372 373 374 375
            classified as true.
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    """
376 377 378 379
    if isinstance(labels, list):
        labels = np.array(labels)
    if isinstance(predictions, list):
        predictions = np.array(predictions)
走神的阿圆's avatar
走神的阿圆 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    _MINIMUM_COUNT = 1e-7

    if weights is None:
        weights = 1.0

    bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1)))
    float_labels = labels.astype(np.float)
    histogram_range = (0, num_thresholds - 1)
    tp_buckets, _ = np.histogram(
        bucket_indices,
        bins=num_thresholds,
        range=histogram_range,
        weights=float_labels * weights)
    fp_buckets, _ = np.histogram(
        bucket_indices,
        bins=num_thresholds,
        range=histogram_range,
        weights=(1.0 - float_labels) * weights)

    # Obtain the reverse cumulative sum.
    tp = np.cumsum(tp_buckets[::-1])[::-1]
    fp = np.cumsum(fp_buckets[::-1])[::-1]
    tn = fp[0] - fp
    fn = tp[0] - tp
    precision = tp / np.maximum(_MINIMUM_COUNT, tp + fp)
    recall = tp / np.maximum(_MINIMUM_COUNT, tp + fn)
    data = {
        'tp': tp.astype(int).tolist(),
        'fp': fp.astype(int).tolist(),
        'tn': tn.astype(int).tolist(),
        'fn': fn.astype(int).tolist(),
        'precision': precision.astype(float).tolist(),
        'recall': recall.astype(float).tolist()
    }
    return data


C
chenjian 已提交
417 418 419 420 421 422
def pr_curve(tag,
             labels,
             predictions,
             step,
             walltime,
             num_thresholds=127,
走神的阿圆's avatar
走神的阿圆 已提交
423 424 425 426 427
             weights=None):
    """Package data to one pr_curve.

    Args:
        tag (string): Data identifier
428 429
        labels (np.ndarray or list): Binary labels for each element.
        predictions (np.ndarray or list): The probability that an element be
走神的阿圆's avatar
走神的阿圆 已提交
430 431 432 433 434 435 436 437 438 439 440 441
            classified as true.
        step (int): Step of pr_curve
        walltime (int): Wall time of pr_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.

    Return:
        Package with format of record_pb2.Record
    """
    num_thresholds = min(num_thresholds, 127)
    prcurve_map = compute_curve(labels, predictions, num_thresholds, weights)

C
chenjian 已提交
442 443 444 445 446 447 448 449 450 451
    return pr_curve_raw(
        tag=tag,
        tp=prcurve_map['tp'],
        fp=prcurve_map['fp'],
        tn=prcurve_map['tn'],
        fn=prcurve_map['fn'],
        precision=prcurve_map['precision'],
        recall=prcurve_map['recall'],
        step=step,
        walltime=walltime)
走神的阿圆's avatar
走神的阿圆 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488


def pr_curve_raw(tag, tp, fp, tn, fn, precision, recall, step, walltime):
    """Package raw data to one pr_curve.

    Args:
        tag (string): Data identifier
        tp (list): True Positive.
        fp (list): False Positive.
        tn (list): True Negative.
        fn (list): False Negative.
        precision (list): The fraction of retrieved documents that are relevant
            to the query:
        recall (list): The fraction of the relevant documents that are
            successfully retrieved.
        step (int): Step of pr_curve
        walltime (int): Wall time of pr_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.

    Return:
        Package with format of record_pb2.Record
    """
    """
    if isinstance(tp, np.ndarray):
        tp = tp.astype(int).tolist()
    if isinstance(fp, np.ndarray):
        fp = fp.astype(int).tolist()
    if isinstance(tn, np.ndarray):
        tn = tn.astype(int).tolist()
    if isinstance(fn, np.ndarray):
        fn = fn.astype(int).tolist()
    if isinstance(precision, np.ndarray):
        precision = precision.astype(int).tolist()
    if isinstance(recall, np.ndarray):
        recall = recall.astype(int).tolist()
    """
C
chenjian 已提交
489 490
    prcurve = Record.PRCurve(
        TP=tp, FP=fp, TN=tn, FN=fn, precision=precision, recall=recall)
走神的阿圆's avatar
走神的阿圆 已提交
491
    return Record(values=[
C
chenjian 已提交
492
        Record.Value(id=step, tag=tag, timestamp=walltime, pr_curve=prcurve)
走神的阿圆's avatar
走神的阿圆 已提交
493
    ])
P
Peter Pan 已提交
494 495


P
Peter Pan 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 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
def compute_roc_curve(labels, predictions, num_thresholds=None, weights=None):
    """ Compute ROC curve data by labels and predictions.
    Args:
        labels (numpy.ndarray or list): Binary labels for each element.
        predictions (numpy.ndarray or list): The probability that an element be
            classified as true.
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    """
    if isinstance(labels, list):
        labels = np.array(labels)
    if isinstance(predictions, list):
        predictions = np.array(predictions)
    _MINIMUM_COUNT = 1e-7

    if weights is None:
        weights = 1.0

    bucket_indices = np.int32(np.floor(predictions * (num_thresholds - 1)))
    float_labels = labels.astype(np.float)
    histogram_range = (0, num_thresholds - 1)
    tp_buckets, _ = np.histogram(
        bucket_indices,
        bins=num_thresholds,
        range=histogram_range,
        weights=float_labels * weights)
    fp_buckets, _ = np.histogram(
        bucket_indices,
        bins=num_thresholds,
        range=histogram_range,
        weights=(1.0 - float_labels) * weights)

    # Obtain the reverse cumulative sum.
    tp = np.cumsum(tp_buckets[::-1])[::-1]
    fp = np.cumsum(fp_buckets[::-1])[::-1]
    tn = fp[0] - fp
    fn = tp[0] - tp
    tpr = tp / np.maximum(_MINIMUM_COUNT, tn + fp)
    fpr = fp / np.maximum(_MINIMUM_COUNT, tn + fp)
    data = {
        'tp': tp.astype(int).tolist(),
        'fp': fp.astype(int).tolist(),
        'tn': tn.astype(int).tolist(),
        'fn': fn.astype(int).tolist(),
        'tpr': tpr.astype(float).tolist(),
        'fpr': fpr.astype(float).tolist()
    }
    return data


C
chenjian 已提交
546 547 548 549 550 551 552
def roc_curve(tag,
              labels,
              predictions,
              step,
              walltime,
              num_thresholds=127,
              weights=None):
P
Peter Pan 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566
    """Package data to one roc_curve.
    Args:
        tag (string): Data identifier
        labels (numpy.ndarray or list): Binary labels for each element.
        predictions (numpy.ndarray or list): The probability that an element be
            classified as true.
        step (int): Step of pr_curve
        walltime (int): Wall time of pr_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    Return:
        Package with format of record_pb2.Record
    """
    num_thresholds = min(num_thresholds, 127)
C
chenjian 已提交
567 568
    roc_curve_map = compute_roc_curve(labels, predictions, num_thresholds,
                                      weights)
P
Peter Pan 已提交
569

C
chenjian 已提交
570 571 572 573 574 575 576 577 578 579
    return roc_curve_raw(
        tag=tag,
        tp=roc_curve_map['tp'],
        fp=roc_curve_map['fp'],
        tn=roc_curve_map['tn'],
        fn=roc_curve_map['fn'],
        tpr=roc_curve_map['tpr'],
        fpr=roc_curve_map['fpr'],
        step=step,
        walltime=walltime)
P
Peter Pan 已提交
580 581 582 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


def roc_curve_raw(tag, tp, fp, tn, fn, tpr, fpr, step, walltime):
    """Package raw data to one roc_curve.
    Args:
        tag (string): Data identifier
        tp (list): True Positive.
        fp (list): False Positive.
        tn (list): True Negative.
        fn (list): False Negative.
        tpr (list): true positive rate:
        fpr (list): false positive rate.
        step (int): Step of roc_curve
        walltime (int): Wall time of roc_curve
        num_thresholds (int): Number of thresholds used to draw the curve.
        weights (float): Multiple of data to display on the curve.
    Return:
        Package with format of record_pb2.Record
    """
    """
    if isinstance(tp, np.ndarray):
        tp = tp.astype(int).tolist()
    if isinstance(fp, np.ndarray):
        fp = fp.astype(int).tolist()
    if isinstance(tn, np.ndarray):
        tn = tn.astype(int).tolist()
    if isinstance(fn, np.ndarray):
        fn = fn.astype(int).tolist()
    if isinstance(tpr, np.ndarray):
        tpr = tpr.astype(int).tolist()
    if isinstance(fpr, np.ndarray):
        fpr = fpr.astype(int).tolist()
    """
C
chenjian 已提交
613
    roc_curve = Record.ROC_Curve(TP=tp, FP=fp, TN=tn, FN=fn, tpr=tpr, fpr=fpr)
P
Peter Pan 已提交
614 615 616 617
    return Record(values=[
        Record.Value(
            id=step, tag=tag, timestamp=walltime, roc_curve=roc_curve)
    ])