val.py 5.2 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 20 21 22
#
# 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

from paddle.fluid.dygraph.base import to_variable
import numpy as np
import paddle.fluid as fluid

C
chenguowei01 已提交
23
from datasets import Dataset
C
chenguowei01 已提交
24 25 26 27 28 29 30 31 32 33 34
import transforms as T
import models
import utils.logging as logging
from utils import get_environ_info
from utils import ConfusionMatrix


def parse_args():
    parser = argparse.ArgumentParser(description='Model training')

    # params of model
C
chenguowei01 已提交
35 36 37 38 39
    parser.add_argument('--model_name',
                        dest='model_name',
                        help="Model type for traing, which is one of ('UNet')",
                        type=str,
                        default='UNet')
C
chenguowei01 已提交
40 41

    # params of dataset
C
chenguowei01 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55
    parser.add_argument('--data_dir',
                        dest='data_dir',
                        help='The root directory of dataset',
                        type=str)
    parser.add_argument('--val_list',
                        dest='val_list',
                        help='Val list file of dataset',
                        type=str,
                        default=None)
    parser.add_argument('--num_classes',
                        dest='num_classes',
                        help='Number of classes',
                        type=int,
                        default=2)
C
chenguowei01 已提交
56 57

    # params of evaluate
C
chenguowei01 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    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('--batch_size',
                        dest='batch_size',
                        help='Mini batch size',
                        type=int,
                        default=2)
    parser.add_argument('--model_dir',
                        dest='model_dir',
                        help='The path of model for evaluation',
                        type=str,
                        default=None)
C
chenguowei01 已提交
74 75 76 77 78 79 80 81 82 83 84

    return parser.parse_args()


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

C
chenguowei01 已提交
90 91
    data_generator = eval_dataset.generator(batch_size=batch_size,
                                            drop_last=True)
C
chenguowei01 已提交
92 93 94 95 96 97 98 99
    total_steps = math.ceil(eval_dataset.num_samples * 1.0 / batch_size)
    conf_mat = ConfusionMatrix(num_classes, streaming=True)

    logging.info(
        "Start to evaluating(total_samples={}, total_steps={})...".format(
            eval_dataset.num_samples, total_steps))
    for step, data in enumerate(data_generator()):
        images = np.array([d[0] for d in data])
C
chenguowei01 已提交
100
        labels = np.array([d[2] for d in data]).astype('int64')
C
chenguowei01 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        images = to_variable(images)
        pred, _ = model(images, labels, mode='eval')

        pred = pred.numpy()
        mask = labels != ignore_index

        conf_mat.calculate(pred=pred, label=labels, ignore=mask)
        _, iou = conf_mat.mean_iou()

        logging.info("[EVAL] Epoch={}, Step={}/{}, iou={}".format(
            epoch_id, step + 1, total_steps, iou))

    category_iou, miou = conf_mat.mean_iou()
    category_acc, macc = conf_mat.accuracy()
    logging.info("[EVAL] #image={} acc={:.4f} IoU={:.4f}".format(
        eval_dataset.num_samples, macc, miou))
    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()))


def main(args):
C
chenguowei01 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    with fluid.dygraph.guard(places):
        eval_transforms = T.Compose([T.Resize(args.input_size), T.Normalize()])
        eval_dataset = Dataset(data_dir=args.data_dir,
                               file_list=args.val_list,
                               transforms=eval_transforms,
                               num_workers='auto',
                               buffer_size=100,
                               parallel_method='thread',
                               shuffle=False)

        if args.model_name == 'UNet':
            model = models.UNet(num_classes=args.num_classes)

        evaluate(model,
                 eval_dataset,
                 model_dir=args.model_dir,
                 num_classes=args.num_classes,
                 batch_size=args.batch_size)
C
chenguowei01 已提交
141 142 143 144 145 146 147 148 149


if __name__ == '__main__':
    args = parse_args()
    env_info = get_environ_info()
    if env_info['place'] == 'cpu':
        places = fluid.CPUPlace()
    else:
        places = fluid.CUDAPlace(0)
C
chenguowei01 已提交
150
    main(args)