val.py 5.4 KB
Newer Older
C
chenguowei01 已提交
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
C
chenguowei01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# 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 argparse
import os
import math

import numpy as np
20 21 22
import tqdm
import cv2
from paddle.fluid.dygraph.base import to_variable
C
chenguowei01 已提交
23
import paddle.fluid as fluid
C
chenguowei01 已提交
24
from paddle.fluid.dygraph.parallel import ParallelEnv
C
chenguowei01 已提交
25
from paddle.fluid.io import DataLoader
C
chenguowei01 已提交
26
from paddle.fluid.dataloader import BatchSampler
C
chenguowei01 已提交
27

C
chenguowei01 已提交
28
from datasets import OpticDiscSeg, Cityscapes
C
chenguowei01 已提交
29
import transforms as T
C
chenguowei01 已提交
30
from models import MODELS
C
chenguowei01 已提交
31 32 33
import utils.logging as logging
from utils import get_environ_info
from utils import ConfusionMatrix
C
chenguowei01 已提交
34
from utils import Timer, calculate_eta
C
chenguowei01 已提交
35 36 37


def parse_args():
C
chenguowei01 已提交
38
    parser = argparse.ArgumentParser(description='Model evaluation')
C
chenguowei01 已提交
39 40

    # params of model
C
chenguowei01 已提交
41 42 43
    parser.add_argument(
        '--model_name',
        dest='model_name',
R
update  
root 已提交
44 45
        help='Model type for evaluation, which is one of {}'.format(
            str(list(MODELS.keys()))),
C
chenguowei01 已提交
46 47
        type=str,
        default='UNet')
C
chenguowei01 已提交
48 49

    # params of dataset
C
chenguowei01 已提交
50
    parser.add_argument(
C
chenguowei01 已提交
51 52
        '--dataset',
        dest='dataset',
C
chenguowei01 已提交
53 54
        help=
        "The dataset you want to evaluation, which is one of ('OpticDiscSeg', 'Cityscapes')",
C
chenguowei01 已提交
55
        type=str,
C
chenguowei01 已提交
56
        default='OpticDiscSeg')
C
chenguowei01 已提交
57 58

    # params of evaluate
C
chenguowei01 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71
    parser.add_argument(
        "--input_size",
        dest="input_size",
        help="The image size for net inputs.",
        nargs=2,
        default=[512, 512],
        type=int)
    parser.add_argument(
        '--model_dir',
        dest='model_dir',
        help='The path of model for evaluation',
        type=str,
        default=None)
C
chenguowei01 已提交
72 73 74 75 76 77 78 79 80 81

    return parser.parse_args()


def evaluate(model,
             eval_dataset=None,
             model_dir=None,
             num_classes=None,
             ignore_index=255,
             epoch_id=None):
C
chenguowei01 已提交
82
    ckpt_path = os.path.join(model_dir, 'model')
C
chenguowei01 已提交
83 84 85 86
    para_state_dict, opti_state_dict = fluid.load_dygraph(ckpt_path)
    model.set_dict(para_state_dict)
    model.eval()

87
    total_steps = len(eval_dataset)
C
chenguowei01 已提交
88 89 90 91
    conf_mat = ConfusionMatrix(num_classes, streaming=True)

    logging.info(
        "Start to evaluating(total_samples={}, total_steps={})...".format(
C
chenguowei01 已提交
92
            len(eval_dataset), total_steps))
C
chenguowei01 已提交
93 94
    timer = Timer()
    timer.start()
95 96 97
    for step, (im, im_info, label) in enumerate(eval_dataset):
        im = to_variable(im)
        pred, _ = model(im, mode='eval')
C
chenguowei01 已提交
98 99
        pred = pred.numpy().astype('float32')
        pred = np.squeeze(pred)
100 101 102 103 104 105 106 107 108 109 110
        for info in im_info[::-1]:
            if info[0] == 'resize':
                h, w = info[1][0], info[1][1]
                pred = cv2.resize(pred, (w, h), cv2.INTER_NEAREST)
            elif info[0] == 'padding':
                h, w = info[1][0], info[1][1]
                pred = pred[0:h, 0:w]
            else:
                raise Exception("Unexpected info '{}' in im_info".format(
                    info[0]))
        pred = pred[np.newaxis, :, :, np.newaxis]
C
chenguowei01 已提交
111
        pred = pred.astype('int64')
112 113 114
        mask = label != ignore_index

        conf_mat.calculate(pred=pred, label=label, ignore=mask)
C
chenguowei01 已提交
115 116
        _, iou = conf_mat.mean_iou()

C
chenguowei01 已提交
117 118 119
        time_step = timer.elapsed_time()
        remain_step = total_steps - step - 1
        logging.info(
C
chenguowei01 已提交
120
            "[EVAL] Epoch={}, Step={}/{}, iou={:4f}, sec/step={:.4f} | ETA {}".
C
chenguowei01 已提交
121 122 123
            format(epoch_id, step + 1, total_steps, iou, time_step,
                   calculate_eta(remain_step, time_step)))
        timer.restart()
C
chenguowei01 已提交
124 125 126 127

    category_iou, miou = conf_mat.mean_iou()
    category_acc, macc = conf_mat.accuracy()
    logging.info("[EVAL] #image={} acc={:.4f} IoU={:.4f}".format(
C
chenguowei01 已提交
128
        len(eval_dataset), macc, miou))
C
chenguowei01 已提交
129 130 131
    logging.info("[EVAL] Category IoU: " + str(category_iou))
    logging.info("[EVAL] Category Acc: " + str(category_acc))
    logging.info("[EVAL] Kappa:{:.4f} ".format(conf_mat.kappa()))
C
add vdl  
chenguowei01 已提交
132
    return miou, macc
C
chenguowei01 已提交
133 134 135


def main(args):
C
chenguowei01 已提交
136
    env_info = get_environ_info()
C
chenguowei01 已提交
137 138 139
    places = fluid.CUDAPlace(ParallelEnv().dev_id) \
        if env_info['place'] == 'cuda' and fluid.is_compiled_with_cuda() \
        else fluid.CPUPlace()
C
chenguowei01 已提交
140 141 142

    if args.dataset.lower() == 'opticdiscseg':
        dataset = OpticDiscSeg
C
chenguowei01 已提交
143 144
    elif args.dataset.lower() == 'cityscapes':
        dataset = Cityscapes
C
chenguowei01 已提交
145 146
    else:
        raise Exception(
C
chenguowei01 已提交
147 148
            "The --dataset set wrong. It should be one of ('OpticDiscSeg', 'Cityscapes')"
        )
C
chenguowei01 已提交
149

C
chenguowei01 已提交
150 151
    with fluid.dygraph.guard(places):
        eval_transforms = T.Compose([T.Resize(args.input_size), T.Normalize()])
C
chenguowei01 已提交
152
        eval_dataset = dataset(transforms=eval_transforms, mode='eval')
C
chenguowei01 已提交
153

C
chenguowei01 已提交
154 155 156 157 158
        if args.model_name not in MODELS:
            raise Exception(
                '--model_name is invalid. it should be one of {}'.format(
                    str(list(MODELS.keys()))))
        model = MODELS[args.model_name](num_classes=eval_dataset.num_classes)
C
chenguowei01 已提交
159

C
chenguowei01 已提交
160 161 162 163
        evaluate(
            model,
            eval_dataset,
            model_dir=args.model_dir,
164
            num_classes=eval_dataset.num_classes)
C
chenguowei01 已提交
165 166 167 168


if __name__ == '__main__':
    args = parse_args()
C
chenguowei01 已提交
169
    main(args)