|
| 1 | +import tensorflow as tf |
| 2 | +import numpy as np |
| 3 | +import shutil |
| 4 | +import os |
| 5 | +from data_manager import DataManager |
| 6 | +from model import Model |
| 7 | +from config import * |
| 8 | +import utils |
| 9 | +from datetime import datetime |
| 10 | +class Agent(object): |
| 11 | + def __init__(self,param): |
| 12 | + |
| 13 | + self.__sess=tf.Session() |
| 14 | + self.__Param=param |
| 15 | + self.init_datasets() #初始化数据管理器 |
| 16 | + self.model=Model(self.__sess,self.__Param) #建立模型 |
| 17 | + self.logger=utils.get_logger(param["Log_dir"]) |
| 18 | + def run(self): |
| 19 | + if self.__Param["mode"] is "training": |
| 20 | + train_mode= self.__Param["train_mode"] |
| 21 | + self.train(train_mode) |
| 22 | + elif self.__Param["mode"] is "testing": |
| 23 | + self.test() |
| 24 | + elif self.__Param["mode"] is "savePb": |
| 25 | + raise Exception(" this mode is incomplete ") |
| 26 | + else: |
| 27 | + print("got a unexpected mode ,please set the mode 'training', 'testing' or 'savePb' ") |
| 28 | + |
| 29 | + def init_datasets(self): |
| 30 | + self.Positive_data_list,self.Negative_data_list=self.listData1(self.__Param["data_dir"]) |
| 31 | + if self.__Param["mode"] is "training": |
| 32 | + self.DataManager_train_Positive = DataManager(self.Positive_data_list, self.__Param) |
| 33 | + self.DataManager_train_Negative = DataManager(self.Negative_data_list, self.__Param) |
| 34 | + elif self.__Param["mode"] is "testing": |
| 35 | + self.DataManager_test_Positive = DataManager(self.Positive_data_list, self.__Param,shuffle=False) |
| 36 | + self.DataManager_test_Negative = DataManager(self.Negative_data_list, self.__Param,shuffle=False) |
| 37 | + elif self.__Param["mode"] is "savePb": |
| 38 | + pass |
| 39 | + else: |
| 40 | + raise Exception('got a unexpected mode ') |
| 41 | + |
| 42 | + def train(self,mode): |
| 43 | + if mode not in ["segment","decision","total"]: |
| 44 | + raise Exception('got a unexpected training mode ,options :{segment,decision}') |
| 45 | + with self.__sess.as_default(): |
| 46 | + self.logger.info('start training {} net'.format(mode)) |
| 47 | + for i in range(self.model.step, self.__Param["epochs_num"] + self.model.step): |
| 48 | + #epoch start |
| 49 | + iter_loss = 0 |
| 50 | + for batch in range(self.DataManager_train_Positive.number_batch): |
| 51 | + #batch start |
| 52 | + for index in range(2): |
| 53 | + #corss training the positive sample and negative sample |
| 54 | + if index==0 : |
| 55 | + img_batch, label_pixel_batch,label_batch, file_name_batch, = self.__sess.run(self.DataManager_train_Positive.next_batch) |
| 56 | + else: |
| 57 | + img_batch, label_pixel_batch, label_batch, file_name_batch, = self.__sess.run(self.DataManager_train_Negative.next_batch) |
| 58 | + loss_value_batch=0 |
| 59 | + |
| 60 | + if mode == "segment": |
| 61 | + _, loss_value_batch = self.__sess.run([self.model.optimize_segment,self.model.loss_pixel], |
| 62 | + feed_dict={self.model.Image: img_batch, |
| 63 | + self.model.PixelLabel: label_pixel_batch}) |
| 64 | + elif mode =="decision": |
| 65 | + _, loss_value_batch = self.__sess.run([self.model.optimize_decision, self.model.loss_class], |
| 66 | + feed_dict={self.model.Image: img_batch, |
| 67 | + self.model.Label: label_batch}) |
| 68 | + elif mode == "total": |
| 69 | + _, loss_value_batch = self.__sess.run([self.model.optimize_total, self.model.loss_total], |
| 70 | + feed_dict={self.model.Image: img_batch, |
| 71 | + self.model.PixelLabel: label_pixel_batch, |
| 72 | + self.model.Label: label_batch}) |
| 73 | + iter_loss+= loss_value_batch |
| 74 | + #可视化 |
| 75 | + if i % self.__Param["valid_frequency"] == 0 and i>0: |
| 76 | + mask_batch = self.__sess.run(self.model.mask, feed_dict={self.model.Image: img_batch}) |
| 77 | + save_dir = "./visualization/training_epoch-{}".format(i) |
| 78 | + self.visualization(img_batch, label_pixel_batch, mask_batch, file_name_batch,save_dir) |
| 79 | + self.logger.info('epoch:[{}] ,train_mode:{}, loss: {}'.format(self.model.step, mode,iter_loss)) |
| 80 | + #保存模型 |
| 81 | + if i % self.__Param["save_frequency"] == 0 or i==self.__Param["epochs_num"] + self.model.step-1: |
| 82 | + self.model.save() |
| 83 | + # #验证 |
| 84 | + # if i % self.__Param["valid_frequency"] == 0 and i>0: |
| 85 | + # self.valid() |
| 86 | + self.model.step += 1 |
| 87 | + |
| 88 | + |
| 89 | + def test(self): |
| 90 | + #anew a floder to save visualization |
| 91 | + visualization_dir="./visualization/test" |
| 92 | + if not os.path.exists(visualization_dir): |
| 93 | + os.makedirs(visualization_dir) |
| 94 | + with self.__sess.as_default(): |
| 95 | + self.logger.info('start testing') |
| 96 | + count=0 |
| 97 | + count_TP = 0 # 真正例 |
| 98 | + count_FP = 0 # 假正例 |
| 99 | + count_TN = 0 # 真反例 |
| 100 | + count_FN = 0 # 假反例 |
| 101 | + DataManager=[self.DataManager_test_Positive,self.DataManager_test_Negative] |
| 102 | + for index in range(2): |
| 103 | + for batch in range(DataManager[index].number_batch): |
| 104 | + img_batch, label_pixel_batch,label_batch, file_name_batch, = self.__sess.run(DataManager[index].next_batch) |
| 105 | + mask_batch ,output_batch= self.__sess.run([self.model.mask,self.model.output_class], |
| 106 | + feed_dict={self.model.Image: img_batch,}) |
| 107 | + self.visualization(img_batch, label_pixel_batch,mask_batch, file_name_batch,save_dir=visualization_dir) |
| 108 | + for i, filename in enumerate(file_name_batch): |
| 109 | + count +=1 |
| 110 | + if label_batch[i] == 1 and output_batch[i] == 1: |
| 111 | + count_TP += 1 |
| 112 | + elif label_batch[i] == 1: |
| 113 | + count_FN += 1 |
| 114 | + elif output_batch[i] == 1: |
| 115 | + count_FP += 1 |
| 116 | + else: |
| 117 | + count_TN += 1 |
| 118 | + # 准确率 |
| 119 | + accuracy = (count_TP + count_TN) / count |
| 120 | + # 查准率 |
| 121 | + prescision = count_TP / (count_TP + count_FP) |
| 122 | + # 查全率 |
| 123 | + recall = count_TP / (count_TP + count_FN) |
| 124 | + self.logger.info(" total number of samples = {}".format(count)) |
| 125 | + self.logger.info("positive = {}".format(count_TP + count_FN)) |
| 126 | + self.logger.info("negative = {}".format(count_FP + count_TN)) |
| 127 | + self.logger.info("TP = {}".format(count_TP )) |
| 128 | + self.logger.info("NP = {}".format(count_FP)) |
| 129 | + self.logger.info("TN = {}".format(count_TN )) |
| 130 | + self.logger.info("FN = {}".format(count_FN )) |
| 131 | + self.logger.info("accuracy(准确率) = {:.4f}".format((count_TP + count_TN) / count)) |
| 132 | + self.logger.info("prescision(查准率) = {:.4f}".format(prescision)) |
| 133 | + self.logger.info("recall(查全率) = {:.4f}".format(recall)) |
| 134 | + self.logger.info("the visualization saved in {}".format(visualization_dir)) |
| 135 | + def valid(self): |
| 136 | + pass |
| 137 | + |
| 138 | + def visualization(self,img_batch,label_pixel_batch,mask_batch,filenames,save_dir="./visualization"): |
| 139 | + #anew a floder to save visualization |
| 140 | + if not os.path.exists(save_dir): |
| 141 | + os.makedirs(save_dir) |
| 142 | + for i, filename in enumerate(filenames): |
| 143 | + filename = str(filename).split("'")[-2].replace("/","_") |
| 144 | + mask=np.array(mask_batch[i]).squeeze(2)*255 |
| 145 | + image=np.array(img_batch[i]).squeeze(2) |
| 146 | + label_pixel = np.array(label_pixel_batch[i]).squeeze(2)*255 |
| 147 | + img_visual=utils.concatImage([image,label_pixel,mask]) |
| 148 | + visualization_path = os.path.join(save_dir,filename) |
| 149 | + img_visual.save(visualization_path) |
| 150 | + |
| 151 | + |
| 152 | + def listData(self,data_dir): |
| 153 | + """# list the files of the currtent floder of 'data_dir' ,subfoders are not included. |
| 154 | + :param data_dir: |
| 155 | + :return: list of files |
| 156 | + """ |
| 157 | + data_list=os.listdir(data_dir) |
| 158 | + data_list=[x[2] for x in os.walk(data_dir)][0] |
| 159 | + data_size=len(data_list) |
| 160 | + return data_list,data_size |
| 161 | + |
| 162 | + def listData1(self,data_dir,test_ratio=0.4,positive_index=POSITIVE_KolektorSDD): |
| 163 | + """ this function is designed for the Dataset of KolektorSDD, |
| 164 | + the positive samples and negative samples will be divided into two lists |
| 165 | + :param data_dir: the data folder of KolektorSDD |
| 166 | + :param test_ratio: the proportion of test set |
| 167 | + :param positive_index: the list of index of every subfolders' positive samples |
| 168 | + :return: the list of the positive samples and the list of negative samples |
| 169 | + """ |
| 170 | + example_dirs = [x[1] for x in os.walk(data_dir)][0] |
| 171 | + example_lists = {os.path.basename(x[0]): x[2] for x in os.walk(data_dir)} |
| 172 | + train_test_offset=np.floor(len(example_lists)*(1-test_ratio)) |
| 173 | + Positive_examples_train = [] |
| 174 | + Negative_examples_train = [] |
| 175 | + Positive_examples_valid = [] |
| 176 | + Negative_examples_valid = [] |
| 177 | + for i in range(len(example_dirs)): |
| 178 | + example_dir = example_dirs[i] |
| 179 | + example_list = example_lists[example_dir] |
| 180 | + # 过滤label图片 |
| 181 | + example_list = [item for item in example_list if "label" not in item] |
| 182 | + # 训练数据 |
| 183 | + if i < train_test_offset: |
| 184 | + for j in range(len(example_list)): |
| 185 | + example_image = example_dir + '/' + example_list[j] |
| 186 | + example_label = example_image.split(".")[0] + "_label.bmp" |
| 187 | + # 判断是否是正样本 |
| 188 | + index = example_list[j].split(".")[0][-1] |
| 189 | + if index in positive_index[i]: |
| 190 | + Positive_examples_train.append([example_image, example_label]) |
| 191 | + else: |
| 192 | + Negative_examples_train.append([example_image, example_label]) |
| 193 | + else: |
| 194 | + for j in range(len(example_list)): |
| 195 | + example_image = example_dir + '/' + example_list[j] |
| 196 | + example_label = example_image.split(".")[0] + "_label.bmp" |
| 197 | + index=example_list[j].split(".")[0][-1] |
| 198 | + if index in positive_index[i]: |
| 199 | + Positive_examples_valid.append([example_image, example_label]) |
| 200 | + else: |
| 201 | + Negative_examples_valid.append([example_image, example_label]) |
| 202 | + if self.__Param["mode"] is "training": |
| 203 | + return Positive_examples_train,Negative_examples_train |
| 204 | + if self.__Param["mode"] is "testing": |
| 205 | + return Positive_examples_valid,Negative_examples_valid |
| 206 | + |
| 207 | + |
| 208 | + |
0 commit comments