(main_prog, start_prog, phase=ModelPhase.TRAIN)
| 111 | |
| 112 | |
| 113 | def build_model(main_prog, start_prog, phase=ModelPhase.TRAIN): |
| 114 | if not ModelPhase.is_valid_phase(phase): |
| 115 | raise ValueError("ModelPhase {} is not valid!".format(phase)) |
| 116 | if ModelPhase.is_train(phase): |
| 117 | width = cfg.DATAAUG.CROP_SIZE |
| 118 | height = cfg.DATAAUG.CROP_SIZE |
| 119 | else: |
| 120 | width = cfg.TEST.CROP_SIZE |
| 121 | height = cfg.TEST.CROP_SIZE |
| 122 | |
| 123 | image_shape = [cfg.DATASET.DATA_DIM, height, width] |
| 124 | grt_shape = [1, height, width] |
| 125 | class_num = cfg.DATASET.NUM_CLASSES |
| 126 | |
| 127 | with fluid.program_guard(main_prog, start_prog): |
| 128 | with fluid.unique_name.guard(): |
| 129 | # 在导出模型的时候,增加图像标准化预处理,减小预测部署时图像的处理流程 |
| 130 | # 预测部署时只须对输入图像增加batch_size维度即可 |
| 131 | if ModelPhase.is_predict(phase): |
| 132 | origin_image = fluid.layers.data(name='image', |
| 133 | shape=[ -1, 1, 1, cfg.DATASET.DATA_DIM], |
| 134 | dtype='float32', |
| 135 | append_batch_size=False) |
| 136 | image = fluid.layers.transpose(origin_image, [0, 3, 1, 2]) |
| 137 | origin_shape = fluid.layers.shape(image)[-2:] |
| 138 | mean = np.array(cfg.MEAN).reshape(1, len(cfg.MEAN), 1, 1) |
| 139 | mean = fluid.layers.assign(mean.astype('float32')) |
| 140 | std = np.array(cfg.STD).reshape(1, len(cfg.STD), 1, 1) |
| 141 | std = fluid.layers.assign(std.astype('float32')) |
| 142 | image = (image/255 - mean)/std |
| 143 | image = fluid.layers.resize_bilinear(image, |
| 144 | out_shape=[height, width], align_corners=False, align_mode=0) |
| 145 | else: |
| 146 | image = fluid.layers.data( name='image', shape=image_shape, dtype='float32') |
| 147 | label = fluid.layers.data( name='label', shape=grt_shape, dtype='int32') |
| 148 | mask = fluid.layers.data( name='mask', shape=grt_shape, dtype='int32') |
| 149 | |
| 150 | # use PyReader when doing traning and evaluation |
| 151 | if ModelPhase.is_train(phase) or ModelPhase.is_eval(phase): |
| 152 | iterable = True if ModelPhase.is_eval(phase) else False |
| 153 | print("iterable: ", iterable) |
| 154 | py_reader = fluid.io.PyReader( |
| 155 | feed_list=[image, label, mask], |
| 156 | capacity=cfg.DATALOADER.BUF_SIZE, |
| 157 | iterable=iterable, |
| 158 | use_double_buffer=True, |
| 159 | return_list=False) |
| 160 | |
| 161 | model_name = map_model_name(cfg.MODEL.MODEL_NAME) |
| 162 | model_func = get_func("modeling." + model_name) |
| 163 | |
| 164 | loss_type = cfg.SOLVER.LOSS |
| 165 | if not isinstance(loss_type, list): |
| 166 | loss_type = list(loss_type) |
| 167 | |
| 168 | # dice_loss或bce_loss只适用两类分割中 |
| 169 | if class_num > 2 and (("dice_loss" in loss_type) or ("bce_loss" in loss_type)): |
| 170 | raise Exception("dice loss and bce loss is only applicable to binary classfication") |
no test coverage detected