|
conda install pytorch==1.8.0 torchvision==0.9.0 torchaudio==0.8.0 cudatoolkit=11.1 -c pytorch
1.오류 해결
-버전과 안 맞는 코드 수정 np.float -->float
-여백 레이블 배경 레이블로 설정 ,ignore index 값 12로 설정
-focal loss가중치 설정
가중치 설정-->논문과 같게 설정
0 2.7114885
1 6.237076
2 3.582358
3 8.316548
4 8.129169
5 8.6979065,
6 8.497886
7 4.312109
8 8.135018
9 0.
10 8.741297
11 8.662319
12 3.6
훈련 에러 해결 후 훈련 중
config.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | CKPT_DIR = "model_swift_real" class DefaultConfig(object): data_dir = './' train_img_dir = 'D:/jyn/samsung/open/train_source_image/' train_annot_dir = 'D:/jyn/samsung/open/train_source_gt/' valid_img_dir='D:/jyn/samsung/open/val_source_image/' valid_annot_dir='D:/jyn/samsung/open/val_source_gt/' train_with_ckpt = False logdir = "checkpoints/"+CKPT_DIR ckpt_name = "checkpoints/"+CKPT_DIR+"/ckpt" model_path = "checkpoints/"+CKPT_DIR+"/Model.pth" ckpt_path = "checkpoints/CKPT/6.pth" batch_size = 4 val_batch_size = 4 dataloader_num_worker = 0 class_num = 13 learning_rate = 4e-4 max_epoch = 200 crop = True crop_rate = 0.8 rand_ext = True ext_range = [0, 0, 0, 0.7, 0, 0] ext_param = [0, 0, 0, 0, 0, 0] rand_f = True f = 350 f_range = [200, 400] fish_size = [640, 640] mask_radius = 100 | cs |
main.ipynb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 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 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 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 489 490 491 492 493 494 495 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 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 | import torch import sys sys.path.append('./FisheyeSeg-master') from data.CityScape import CityScape from data.FishEyeGenerator import FishEyeGenerator from torchvision.transforms import ToTensor, ColorJitter, Normalize from PIL import Image import random import numpy as np from torch.utils.data import DataLoader from torch import nn from config import DefaultConfig from models.ERFPSPNet import ERFPSPNet from models.SwiftNet import SwiftNet, resnet18 import torch.nn.functional as F from torch import nn import math import segmentation_models_pytorch as smp import time from torch.utils.tensorboard import SummaryWriter import torchvision import os import sys from loss import FocalLoss2d, CrossEntropyLoss2d import cv2 from tqdm import tqdm def get_default_device(): if torch.cuda.is_available(): return torch.device('cuda') else: return torch.device('cpu') Config = DefaultConfig() MyDevice = get_default_device() MyCPU = torch.device('cpu') class MyTransform(object): def __init__(self, focal_len, shape=None): self._transformer = FishEyeGenerator(focal_len, shape) self._F_RAND_FLAG = False self._F_RANGE = [200, 400] self._EXT_RAND_FLAG = False self._EXT_PARAM_RANGE = [0, 0, 0, 0, 0, 0] self._transformer.set_ext_param_range(self._EXT_PARAM_RANGE) self._RAND_CROP = False self._rand_crop_rate = 0.8 self._NORMAL_SCALE = False self._scale_range = [0.5, 2] self._FISH_SCALE = False self._fish_scale_range = [0.5, 2] self._NORMAL_TRANSLATE = False self._trans_range = [-20,20] def set_crop(self,rand=True, rate=0.8): self._RAND_CROP = rand self._rand_crop_rate = rate def set_bkg(self, bkg_label=12, bkg_color=[0, 0, 0]): self._transformer.set_bkg(bkg_label, bkg_color) def set_ext_param_range(self, ext_param): self._EXT_PARAM_RANGE = list(ext_param) self._transformer.set_ext_param_range(self._EXT_PARAM_RANGE) def rand_ext_params(self): self._EXT_RAND_FLAG = True def set_ext_params(self, ext_params): self._transformer.set_ext_params(ext_params) self._EXT_RAND_FLAG = False def set_f(self, focal_len): self._transformer.set_f(focal_len) self._F_RAND_FLAG = False def rand_f(self, f_range=[200, 400]): self._F_RANGE = f_range self._F_RAND_FLAG = True def _rand_crop(self, image, annot): rows, cols, channels = image.shape new_rows = math.floor(rows*self._rand_crop_rate) new_cols = math.floor(cols*self._rand_crop_rate) row_start = math.floor((rows-new_rows)*random.random()) col_start = math.floor((cols-new_cols)*random.random()) crop_image = image[row_start:row_start+new_rows, col_start:col_start+new_cols] crop_annot = annot[row_start:row_start+new_rows, col_start:col_start+new_cols] return crop_image, crop_annot def _fish_scale(self, image, annot): borderValue = 20 rate = random.random()*(self._fish_scale_range[1]-self._fish_scale_range[0])+self._fish_scale_range[0] if rate == 1: return image, annot rows, cols = annot.shape image = cv2.resize(image, None,fx=rate,fy=rate) annot = cv2.resize(annot, None,fx=rate,fy=rate, interpolation=cv2.INTER_NEAREST) if rate <1: dst_image = np.ones((rows,cols,3),dtype=np.uint8)*0 dst_annot = np.ones((rows,cols),dtype=np.uint8)*borderValue row_start = rows//2-annot.shape[0]//2 col_start = cols//2-annot.shape[1]//2 dst_image[row_start:row_start+annot.shape[0], col_start:col_start+annot.shape[1]] = image dst_annot[row_start:row_start+annot.shape[0], col_start:col_start+annot.shape[1]] = annot return dst_image, dst_annot if rate>1: row_start = image.shape[0]//2-rows//2 col_start = image.shape[1]//2-cols//2 crop_image = image[row_start:row_start+rows, col_start:col_start+cols] crop_annot = annot[row_start:row_start+rows, col_start:col_start+cols] return crop_image, crop_annot def __call__(self, image, annot): if self._RAND_CROP: image, annot = self._rand_crop(image, annot) if self._NORMAL_SCALE: scale_rate = random.random()*(self._scale_range[1]-self._scale_range[0])+self._scale_range[0] image = cv2.resize(image, None, fx=scale_rate, fy=scale_rate) annot = cv2.resize(annot, None, fx=scale_rate, fy=scale_rate, interpolation=cv2.INTER_NEAREST) if self._F_RAND_FLAG: self._transformer.rand_f(self._F_RANGE) if self._EXT_RAND_FLAG: self._transformer.rand_ext_params() dst_image = self._transformer.transFromColor(image) dst_annot = self._transformer.transFromGray(annot, reuse=True) if self._NORMAL_TRANSLATE: x_shift = random.random()*(self._trans_range[1]-self._trans_range[0])+self._trans_range[0] y_shift = random.random()*(self._trans_range[1]-self._trans_range[0])+self._trans_range[0] M=np.array([[1,0, x_shift],[0,1,y_shift]], dtype=np.float32) sz = (dst_annot.shape[1], dst_annot.shape[0]) dst_image = cv2.warpAffine(dst_image, M, sz) dst_annot = cv2.warpAffine(dst_annot, M, sz, flags=cv2.INTER_NEAREST, borderValue=20) if self._FISH_SCALE: dst_image, dst_annot = self._fish_scale(dst_image, dst_annot) # dst_image = Image.fromarray(dst_image) # dst_annot = Image.fromarray(dst_annot) # 이미지 데이터의 데이터 형식과 채널 수를 확인하고 필요한 데이터 변환 또는 전처리를 수행합니다. dst_image = dst_image.astype(np.uint8) # 데이터 형식을 8비트 부호 없는 정수로 변환 dst_annot = dst_annot.astype(np.uint8) # 데이터 형식을 8비트 부호 없는 정수로 변환 # 데이터 범위를 [0, 255]로 정규화합니다 (이미지 데이터가 [0, 1] 범위인 경우는 생략 가능). dst_image = (dst_image * 255).astype(np.uint8) # 이미지 데이터를 PIL 이미지로 변환합니다. dst_image = Image.fromarray(dst_image) # 주석(레이블) 데이터를 PIL 이미지로 변환합니다. dst_annot = Image.fromarray(dst_annot) brightness, contrast, hue, saturation = 0.1, 0.1, 0.1, 0.1 dst_image = ColorJitter(brightness, contrast, saturation, hue)(dst_image) if (random.random() < 0.5): dst_image = dst_image.transpose(Image.FLIP_LEFT_RIGHT) dst_annot = dst_annot.transpose(Image.FLIP_LEFT_RIGHT) dst_annot = np.asarray(dst_annot) dst_annot = torch.from_numpy(dst_annot) dst_image = ToTensor()(dst_image) # image = Normalize(mean=[.485, .456, .406], std=[.229, .224, .225])(image) return dst_image, dst_annot class RandOneTransform(object): def __init__(self, focal_len, shape=None): self._transformer = FishEyeGenerator(focal_len, shape) self.F = 350 self._F_RANGE = [200, 400] self._EXT_PARAMS = [0, 0, 0, 0, 0, 0] self._EXT_PARAM_RANGE = [0, 0, 0, 0, 0, 0] self._transformer.set_ext_param_range(self._EXT_PARAM_RANGE) self._RAND_CROP = False self._rand_crop_rate = 0.8 self._NORMAL_SCALE = False self._scale_range = [0.5, 2] self._FISH_SCALE = True self._fish_scale_range = [0.5, 2] self._NORMAL_TRANSLATE = True self._trans_range = [-20,20] def set_crop(self,rand=True, rate=0.8): self._RAND_CROP = rand self._rand_crop_rate = rate def set_bkg(self, bkg_label=12, bkg_color=[0, 0, 0]): self._transformer.set_bkg(bkg_label, bkg_color) def set_ext_param_range(self, ext_param): self._EXT_PARAM_RANGE = list(ext_param) self._transformer.set_ext_param_range(self._EXT_PARAM_RANGE) def set_ext_params(self, ext_params): self._EXT_PARAMS = ext_params.copy() self._transformer.set_ext_params(ext_params) # self._EXT_RAND_FLAG = False def set_f(self, focal_len): self.F = focal_len self._transformer.set_f(focal_len) def set_f_range(self, f_range=[200, 400]): self._F_RANGE = f_range def _rand_crop(self, image, annot): rows, cols, channels = image.shape new_rows = math.floor(rows*self._rand_crop_rate) new_cols = math.floor(cols*self._rand_crop_rate) row_start = math.floor((rows-new_rows)*random.random()) col_start = math.floor((cols-new_cols)*random.random()) crop_image = image[row_start:row_start+new_rows, col_start:col_start+new_cols] crop_annot = annot[row_start:row_start+new_rows, col_start:col_start+new_cols] return crop_image, crop_annot def _fish_scale(self, image, annot): borderValue = 20 rate = random.random()*(self._fish_scale_range[1]-self._fish_scale_range[0])+self._fish_scale_range[0] if rate == 1: return image, annot rows, cols = annot.shape image = cv2.resize(image, None,fx=rate,fy=rate) annot = cv2.resize(annot, None,fx=rate,fy=rate, interpolation=cv2.INTER_NEAREST) if rate <1: dst_image = np.ones((rows,cols,3),dtype=np.uint8)*0 dst_annot = np.ones((rows,cols),dtype=np.uint8)*borderValue row_start = rows//2-annot.shape[0]//2 col_start = cols//2-annot.shape[1]//2 dst_image[row_start:row_start+annot.shape[0], col_start:col_start+annot.shape[1]] = image dst_annot[row_start:row_start+annot.shape[0], col_start:col_start+annot.shape[1]] = annot return dst_image, dst_annot if rate>1: row_start = image.shape[0]//2-rows//2 col_start = image.shape[1]//2-cols//2 crop_image = image[row_start:row_start+rows, col_start:col_start+cols] crop_annot = annot[row_start:row_start+rows, col_start:col_start+cols] return crop_image, crop_annot def __call__(self, image, annot): if self._RAND_CROP: image, annot = self._rand_crop(image, annot) if self._NORMAL_SCALE: scale_rate = random.random()*(self._scale_range[1]-self._scale_range[0])+self._scale_range[0] image = cv2.resize(image, None, fx=scale_rate, fy=scale_rate) annot = cv2.resize(annot, None, fx=scale_rate, fy=scale_rate, interpolation=cv2.INTER_NEAREST) # index = random.randint(0,2) # if index==0: # self._transformer.rand_f(self._F_RANGE) # self._transformer.set_ext_params(self._EXT_PARAMS) # elif index==1: # # 随机旋转 # self._transformer.set_f(self.F) # the_ex_range = self._EXT_PARAM_RANGE.copy() # the_ex_range[3:] = [0,0,0] # self._transformer.set_ext_param_range(the_ex_range) # self._transformer.rand_ext_params() # elif index==2: # # 随机平移 # self._transformer.set_f(self.F) # the_ex_range = self._EXT_PARAM_RANGE.copy() # the_ex_range[:3] = [0,0,0] # self._transformer.set_ext_param_range(the_ex_range) # self._transformer.rand_ext_params() dst_image = self._transformer.transFromColor(image) dst_annot = self._transformer.transFromGray(annot, reuse=True) if self._NORMAL_TRANSLATE: x_shift = random.random()*(self._trans_range[1]-self._trans_range[0])+self._trans_range[0] y_shift = random.random()*(self._trans_range[1]-self._trans_range[0])+self._trans_range[0] M=np.array([[1,0, x_shift],[0,1,y_shift]], dtype=np.float32) sz = (dst_annot.shape[1], dst_annot.shape[0]) dst_image = cv2.warpAffine(dst_image, M, sz) dst_annot = cv2.warpAffine(dst_annot, M, sz, flags=cv2.INTER_NEAREST, borderValue=20) if self._FISH_SCALE: dst_image, dst_annot = self._fish_scale(dst_image, dst_annot) dst_image = Image.fromarray(dst_image) dst_annot = Image.fromarray(dst_annot) brightness, contrast, hue, saturation = 0.1, 0.1, 0.1, 0.1 dst_image = ColorJitter(brightness, contrast, saturation, hue)(dst_image) if (random.random() < 0.5): dst_image = dst_image.transpose(Image.FLIP_LEFT_RIGHT) dst_annot = dst_annot.transpose(Image.FLIP_LEFT_RIGHT) dst_annot = np.asarray(dst_annot) dst_annot = torch.from_numpy(dst_annot) dst_image = ToTensor()(dst_image) # image = Normalize(mean=[.485, .456, .406], std=[.229, .224, .225])(image) return dst_image, dst_annot def val(model, dataloader, ignore_index=12, is_print=False): start_time = time.time() model.to(MyDevice) model.eval() precision_list = np.zeros(Config.class_num, dtype=float) recall_list = np.zeros(Config.class_num, dtype=float) iou_list = np.zeros(Config.class_num, dtype=float) pix_num_or = np.zeros(Config.class_num, dtype=float) pix_num_and = np.zeros(Config.class_num, dtype=float) pix_num_TPFP = np.zeros(Config.class_num, dtype=float) pix_num_TPFN = np.zeros(Config.class_num, dtype=float) val_iter_num = math.ceil(500 / Config.val_batch_size) with torch.no_grad(): for i, (image, annot) in enumerate(dataloader): tic = time.time() input = image.to(MyDevice) target = annot.to(MyDevice, dtype=torch.long) # batch_size*1*H*W predict = torch.argmax(model(input), 1, keepdim=True) predict_onehot = torch.zeros(predict.size( 0), Config.class_num, predict.size(2), predict.size(3)).cuda() predict_onehot = predict_onehot.scatter(1, predict, 1).float() target.unsqueeze_(1) target_onehot = torch.zeros(target.size( 0), Config.class_num, target.size(2), target.size(3)).cuda() target_onehot = target_onehot.scatter(1, target, 1).float() mask = (1 - target_onehot[:, ignore_index, :, :]). \ view(target.size(0), 1, target.size(2), target.size(3)) predict_onehot *= mask target_onehot *= mask area_and = predict_onehot * target_onehot area_or = predict_onehot + target_onehot - area_and pix_num_TPFP += torch.sum(predict_onehot, dim=(0, 2, 3)).cpu().numpy() pix_num_TPFN += torch.sum(target_onehot, dim=(0, 2, 3)).cpu().numpy() pix_num_and += torch.sum(area_and, dim=(0, 2, 3)).cpu().numpy() pix_num_or += torch.sum(area_or, dim=(0, 2, 3)).cpu().numpy() toc = time.time() print(f"validation step {i}/{val_iter_num-1}, {toc-tic} sec/step ...") precision_list = pix_num_and / (pix_num_TPFP + 1e-5) recall_list = pix_num_and / (pix_num_TPFN + 1e-5) iou_list = pix_num_and / (pix_num_or + 1e-5) precision_list[ignore_index] = 0 recall_list[ignore_index] = 0 iou_list[ignore_index] = 0 mean_precision = np.sum(precision_list) / (Config.class_num - 1) mean_recall = np.sum(recall_list) / (Config.class_num - 1) mean_iou = np.sum(iou_list) / (Config.class_num - 1) m_precision_19 = np.sum(precision_list[0:-1]) / (Config.class_num - 2) m_racall_19 = np.sum(recall_list[0:-1]) / (Config.class_num - 2) m_iou_19 = np.sum(iou_list[0:-1]) / (Config.class_num - 2) if is_print: print("==================RESULT====================") print("Mean precision:", mean_precision, '; Mean precision 19:', m_precision_19) print("Mean recall:", mean_recall, '; Mean recall 19:', m_racall_19) print("Mean iou:", mean_iou, '; Mean iou 19:', m_iou_19) print("各类精度:") print(precision_list) print("各类召回率:") print(recall_list) print("各类IOU:") print(iou_list) print(time.time()-start_time, "sec/validation") print("===================END======================") return mean_precision, mean_recall, mean_iou, m_precision_19, m_racall_19, m_iou_19 def val_distortion(model, dataloader, ignore_index=12, is_print=False): start_time = time.time() model.to(MyDevice) model.eval() precision_list = np.zeros(Config.class_num, dtype=float) recall_list = np.zeros(Config.class_num, dtype=float) iou_list = np.zeros(Config.class_num, dtype=float) pix_num_or = np.zeros(Config.class_num, dtype=float) pix_num_and = np.zeros(Config.class_num, dtype=float) pix_num_TPFP = np.zeros(Config.class_num, dtype=float) pix_num_TPFN = np.zeros(Config.class_num, dtype=float) val_iter_num = math.ceil(500 / Config.val_batch_size) mask_distortion = torch.ones(Config.fish_size, device=MyDevice) for i in range(Config.fish_size[0]): for j in range(Config.fish_size[1]): if (i-Config.fish_size[0]/2)**2+(j-Config.fish_size[1]/2)**2 < Config.mask_radius**2: mask_distortion[i,j]=0 with torch.no_grad(): for i, (image, annot) in enumerate(dataloader): tic = time.time() input = image.to(MyDevice) target = annot.to(MyDevice, dtype=torch.long) # batch_size*1*H*W predict = torch.argmax(model(input), 1, keepdim=True) predict_onehot = torch.zeros(predict.size( 0), Config.class_num, predict.size(2), predict.size(3)).cuda() predict_onehot = predict_onehot.scatter(1, predict, 1).float() target.unsqueeze_(1) target_onehot = torch.zeros(target.size( 0), Config.class_num, target.size(2), target.size(3)).cuda() target_onehot = target_onehot.scatter(1, target, 1).float() mask = (1 - target_onehot[:, ignore_index, :, :]). \ view(target.size(0), 1, target.size(2), target.size(3)) predict_onehot *= mask predict_onehot *= mask_distortion target_onehot *= mask target_onehot *= mask_distortion area_and = predict_onehot * target_onehot area_or = predict_onehot + target_onehot - area_and pix_num_TPFP += torch.sum(predict_onehot, dim=(0, 2, 3)).cpu().numpy() pix_num_TPFN += torch.sum(target_onehot, dim=(0, 2, 3)).cpu().numpy() pix_num_and += torch.sum(area_and, dim=(0, 2, 3)).cpu().numpy() pix_num_or += torch.sum(area_or, dim=(0, 2, 3)).cpu().numpy() toc = time.time() print(f"validation step {i}/{val_iter_num-1}, {toc-tic} sec/step ...") precision_list = pix_num_and / (pix_num_TPFP + 1e-5) recall_list = pix_num_and / (pix_num_TPFN + 1e-5) iou_list = pix_num_and / (pix_num_or + 1e-5) precision_list[ignore_index] = 0 recall_list[ignore_index] = 0 iou_list[ignore_index] = 0 mean_precision = np.sum(precision_list) / (Config.class_num - 1) mean_recall = np.sum(recall_list) / (Config.class_num - 1) mean_iou = np.sum(iou_list) / (Config.class_num - 1) m_precision_19 = np.sum(precision_list[0:-1]) / (Config.class_num - 2) m_racall_19 = np.sum(recall_list[0:-1]) / (Config.class_num - 2) m_iou_19 = np.sum(iou_list[0:-1]) / (Config.class_num - 2) if is_print: print("==================RESULT====================") print("Mean precision:", mean_precision, '; Mean precision 19:', m_precision_19) print("Mean recall:", mean_recall, '; Mean recall 19:', m_racall_19) print("Mean iou:", mean_iou, '; Mean iou 19:', m_iou_19) print("各类精度:") print(precision_list) print("各类召回率:") print(recall_list) print("各类IOU:") print(iou_list) print(time.time()-start_time, "sec/validation") print("===================END======================") return mean_precision, mean_recall, mean_iou, m_precision_19, m_racall_19, m_iou_19 def final_eval(): valid_path = ['\\val_200f','\\val_250f','\\val_300f','\\val_350f','\\val_400f'] # valid_path = ['\\val_200f','\\val_250f','\\val_300f','\\val_350f','\\val_400f'] # valid_path = ['\\val_rotate10'] valid_annot = [x+'_annot' for x in valid_path] # model = ERFPSPNet(shapeHW=[640, 640], num_classes=21) resnet = resnet18(pretrained=True) model = SwiftNet(resnet, num_classes=21) model.to(MyDevice) checkpoint = torch.load(Config.ckpt_path) print("Load",Config.ckpt_path) model.load_state_dict(checkpoint['model_state_dict']) model.eval() for i in range(len(valid_path)): validation_set = CityScape(Config.data_dir+valid_path[i], Config.data_dir+valid_annot[i]) validation_loader = DataLoader( validation_set, batch_size=Config.val_batch_size, shuffle=False) print('\n',valid_path[i]) val_distortion(model, validation_loader, is_print=True) def one_eval(model, ckpt_path, valid_path, valid_annot_path, is_distortion=False): model.to(MyDevice) checkpoint = torch.load(ckpt_path) model.load_state_dict(checkpoint['model_state_dict']) model.eval() validation_set = CityScape(Config.data_dir+valid_path, Config.data_dir+valid_annot_path) validation_loader = DataLoader( validation_set, batch_size=Config.val_batch_size, shuffle=False) print("ckpt_path", ckpt_path) print("valid_path",valid_path) if is_distortion: val_distortion(model, validation_loader, is_print=True) else: val(model, validation_loader, is_print=True) def all_eval(): resnet = resnet18(pretrained=True) model = SwiftNet(resnet, num_classes=21) ckpt_index = [x for x in range(22, 26)] # ckpt_index = [1, 4, 5, 6, 8, 9, 10, 11] ckpt = ["checkpoints/CKPT/"+str(x)+'.pth' for x in ckpt_index] # valid_path = ['\\val_400f'] # valid_path = ['\\val_200f','\\val_250f','\\val_300f','\\val_350f','\\val_400f','\\val_7DOF', '\\val_rotate10'] valid_path = ['\\val_200f','\\val_250f','\\val_300f','\\val_350f','\\val_400f'] for i in ckpt: for j in valid_path: one_eval(model, i, j, j+"_annot", is_distortion=True) def train(): train_transform = MyTransform(Config.f, Config.fish_size) train_transform.set_ext_params(Config.ext_param) train_transform.set_ext_param_range(Config.ext_range) if Config.rand_f: train_transform.rand_f(f_range=Config.f_range) if Config.rand_ext: train_transform.rand_ext_params() train_transform.set_bkg(bkg_label=12, bkg_color=[0, 0, 0]) train_transform.set_crop(rand=Config.crop, rate=Config.crop_rate) # train_transform = RandOneTransform(Config.f, Config.fish_size) # train_transform.set_ext_params(Config.ext_param) # train_transform.set_ext_param_range(Config.ext_range) # train_transform.set_f_range(Config.f_range) # train_transform.set_bkg(bkg_label=20, bkg_color=[0, 0, 0]) # train_transform.set_crop(rand=Config.crop, rate=Config.crop_rate) train_set = CityScape(Config.train_img_dir, Config.train_annot_dir, transform=train_transform) train_loader = DataLoader(train_set, batch_size=Config.batch_size, shuffle=True) # # 가져온 이미지와 주석 데이터를 출력합니다. # print("Sample Image Shape:", sample_image.shape) # 이미지의 모양을 출력합니다. # print("Sample Annotation Shape:", sample_annotation.shape) # 주석 데이터의 모양을 출력합니다. validation_set = CityScape(Config.valid_img_dir, Config.valid_annot_dir) validation_loader = DataLoader( validation_set, batch_size=Config.val_batch_size, shuffle=False) # for epoch in tqdm(range(50)): # 에폭 # train_set = CityScape(Config.train_img_dir, # Config.train_annot_dir, transform=train_transform) # # validation_set = CityScape(Config.valid_img_dir, Config.valid_annot_dir) # # train_set에서 첫 번째 항목을 가져옵니다. # model = ERFPSPNet(shapeHW=[640, 640], num_classes=13) resnet = resnet18(pretrained=True) model = SwiftNet(resnet, num_classes=13) model.to(MyDevice) # class_weights = torch.tensor([8.6979065, 8.497886 , 8.741297 , 5.983605 , 8.662319 , 8.681756 , # 8.683093 , 8.763641 , 8.576978 , 2.7114885, 6.237076 , 3.582358 , # 8.439253 , 8.316548 , 8.129169 , 4.312109 , 8.170293 , 6.91469 , # 8.135018 , 0. ,3.6]).cuda() class_weights = torch.tensor([ 2.7114885,6.237076 ,3.582358 ,8.316548 , 8.129169 , 8.6979065 , 8.497886 , 4.312109 , 8.135018 , 0 , 8.741297 , 8.662319 , 3.6 ]).cuda() # criterion = CrossEntropyLoss2d(weight=class_weights) criterion = FocalLoss2d(weight=class_weights) #criterion = smp.losses.FocalLoss(mode='multiclass') # criterion = CrossEntropyLoss2d() # lr = Config.learning_rate # Pretrained SwiftNet optimizer optimizer = torch.optim.Adam([{'params':model.random_init_params()}, {'params':model.fine_tune_params(), 'lr':1e-4, 'weight_decay':2.5e-5}], lr=4e-4, weight_decay=1e-4) # ERFNetPSP optimizer # optimizer = torch.optim.Adam(model.parameters(), # lr=1e-3, # betas=(0.9, 0.999), # eps=1e-08, # weight_decay=2e-4) # scheduler = torch.optim.lr_scheduler.StepLR( # optimizer, step_size=90, gamma=0.1) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 200, 1e-6) start_epoch = 0 step_per_epoch = math.ceil(2975 / Config.batch_size) writer = SummaryWriter(Config.logdir) # writer.add_graph(model) if Config.train_with_ckpt: checkpoint = torch.load(Config.ckpt_path) print("Load",Config.ckpt_path) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) start_epoch = checkpoint['epoch']+1 val(model, validation_loader, is_print=True) # loss = checkpoint['loss'] model.train() start_time = None for epoch in tqdm(range(start_epoch, Config.max_epoch)): for i, (image, annot) in enumerate(train_loader): if start_time is None: start_time = time.time() input = image.to(MyDevice) target = annot.to(MyDevice, dtype=torch.long) model.train() optimizer.zero_grad() score = model(input) # predict = torch.argmax(score, 1) #print(target) loss = criterion(score, target) loss.backward() optimizer.step() global_step = step_per_epoch * epoch + i if i%20 ==0: predict = torch.argmax(score, 1).to(MyCPU, dtype=torch.uint8) writer.add_image("Images/original_image", image[0], global_step=global_step) writer.add_image("Images/segmentation_output", predict[0].view(1, 640, 640)*10, global_step=global_step) writer.add_image("Images/segmentation_ground_truth", annot[0].view(1, 640, 640)*10, global_step=global_step) if i % 20 == 0 and global_step > 0: writer.add_scalar("Monitor/Loss", loss.item(), global_step=global_step) time_elapsed = time.time() - start_time start_time = time.time() print(f"{epoch}/{Config.max_epoch-1} epoch, {i}/{step_per_epoch} step, loss:{loss.item()}, " f"{time_elapsed} sec/step; global step={global_step}") scheduler.step() if epoch >20: mean_precision, mean_recall, mean_iou, m_precision_19, m_racall_19, m_iou_19 = val( model, validation_loader, is_print=True) writer.add_scalar("Monitor/precision20", mean_precision, global_step=epoch) writer.add_scalar("Monitor/recall20", mean_recall, global_step=epoch) writer.add_scalar("Monitor/mIOU20", mean_iou, global_step=epoch) writer.add_scalar("Monitor1/precision19", m_precision_19, global_step=epoch) writer.add_scalar("Monitor1/recall19", m_racall_19, global_step=epoch) writer.add_scalar("Monitor1/mIOU19", m_iou_19, global_step=epoch) print(epoch, '/', Config.max_epoch, ' loss:', loss.item()) torch.save({ 'epoch': epoch, 'model_state_dict': model.state_dict(), 'loss': loss.item(), 'optimizer_state_dict': optimizer.state_dict() }, Config.ckpt_name + "_" + str(epoch) + ".pth") print("model saved!") # else: # print(epoch, '/', Config.max_epoch, ' loss:', loss.item()) # torch.save({ # 'epoch': epoch, # 'model_state_dict': model.state_dict(), # 'loss': loss.item(), # 'optimizer_state_dict': optimizer.state_dict() # }, Config.ckpt_name + "_" + str(epoch) + ".pth") # print("model saved!") val(model, validation_loader, is_print=True) torch.save({ 'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss }, Config.model_path) print("Save model to disk!") writer.close() from test import label2color def run_image(image_path, model): from torchvision.transforms import ToTensor, Normalize image = cv2.imread(image_path) image1 = cv2.imread(image_path) image = image[:,:,(2,1,0)] image = ToTensor()(image) image = image.to(torch.device('cuda')) image.unsqueeze_(0) score = model(image) predict = torch.argmax(score, 1).to(MyCPU, dtype=torch.uint8)[0].numpy() #예측 클래스 값 확인 #color_label = label2color(predict) color_label = predict #cv2.imwrite('image'+image_path, image1) #cv2.imwrite('annot'+image_path, color_label) return image1, color_label import cv2 import matplotlib.pyplot as plt def real_image_test(): imgs = sorted([os.path.join("D:/jyn/samsung/open/test_image//", img) for img in os.listdir("D:/jyn/samsung/open/test_image//")]) #print(imgs) resnet = resnet18(pretrained=True).to(torch.device('cuda')) model = SwiftNet(resnet, num_classes=13) model = model.to(torch.device('cuda')) #checkpoint = torch.load("checkpoints/CKPT/16.pth") #checkpoint = torch.load("./checkpoints/model_swift2/ckpt_0.pth") checkpoint = torch.load("./checkpoints/model_swift/ckpt_20.pth") # print("Load",Config.ckpt_path) #model.load_state_dict(checkpoint['model_state_dict']) model.load_state_dict(checkpoint,strict=False) model.eval() model = model.to(torch.device('cuda')) for img in imgs: image, label = run_image(img, model) print(label) #cv2.imwrite("image1.png", image) #cv2.imwrite("label2.png", label) # 이미지 표시 plt.figure() plt.subplot(1, 2, 1) plt.imshow(image) plt.title("Image") plt.axis('off') plt.subplot(1, 2, 2) plt.imshow(label) plt.title("Label") plt.axis('off') plt.show() #cv2.imshow("image",image) #cv2.imshow("label",label) # esc_flag = False # while True: # key = cv2.waitKey(20) & 0xFF # if key == 27: # esc_flag = True # break # elif key == ord('p'): # break # def real_image_test(): # imgs = sorted([os.path.join("D:/jyn/samsung/open/test_image//", img) for img in os.listdir("D:/jyn/samsung/open/test_image//")]) # resnet = resnet18(pretrained=True).to(torch.device('cuda')) # model = SwiftNet(resnet, num_classes=) # model = model.to(torch.device('cuda')) # checkpoint = torch.load("checkpoints/CKPT/16.pth") # # print("Load",Config.ckpt_path) # model.load_state_dict(checkpoint['model_state_dict']) # model.eval() # model = model.to(torch.device('cuda')) # for img in imgs: # image, label = run_image(img, model) # cv2.imshow("image",image) # cv2.imshow("label",label) # esc_flag = False # while True: # key = cv2.waitKey(20) & 0xFF # if key == 27: # esc_flag = True # return # elif key == ord('p'): # break if __name__ == '__main__': # final_eval() # all_eval() train() #real_image_test() | cs |
텐서보드 기능 사용
ep30
ep40
ep50
ep60
ep70
잘 안 됨.
ep22
ep84의 train loss,val loss, result
84/199 epoch, 537/744 step, loss:0.022022146731615067, 0.8149983882904053 sec/step; global step=63033
84/199 epoch, 538/744 step, loss:0.021794918924570084, 0.8039984703063965 sec/step; global step=63034
84/199 epoch, 539/744 step, loss:0.02333592064678669, 0.8259985446929932 sec/step; global step=63035
84/199 epoch, 540/744 step, loss:0.018680855631828308, 1.1329975128173828 sec/step; global step=63036
84/199 epoch, 541/744 step, loss:0.036249931901693344, 0.6699986457824707 sec/step; global step=63037
84/199 epoch, 542/744 step, loss:0.021462148055434227, 0.7999985218048096 sec/step; global step=63038
84/199 epoch, 543/744 step, loss:0.017779001966118813, 0.7959985733032227 sec/step; global step=63039
84/199 epoch, 544/744 step, loss:0.030720775946974754, 0.7819981575012207 sec/step; global step=63040
84/199 epoch, 545/744 step, loss:0.03327465429902077, 0.8549983501434326 sec/step; global step=63041
84/199 epoch, 546/744 step, loss:0.02243025042116642, 0.8189983367919922 sec/step; global step=63042
84/199 epoch, 547/744 step, loss:0.02255413867533207, 0.838998556137085 sec/step; global step=63043
84/199 epoch, 548/744 step, loss:0.019615720957517624, 0.482999324798584 sec/step; global step=63044
validation step 103/124, 0.5099983215332031 sec/step ...
validation step 104/124, 0.5109987258911133 sec/step ...
validation step 105/124, 0.4979984760284424 sec/step ...
validation step 106/124, 0.515998125076294 sec/step ...
validation step 107/124, 0.5059993267059326 sec/step ...
validation step 108/124, 0.5039989948272705 sec/step ...
validation step 109/124, 0.5029988288879395 sec/step ...
validation step 110/124, 0.5469987392425537 sec/step ...
validation step 111/124, 0.5239987373352051 sec/step ...
validation step 112/124, 0.5140001773834229 sec/step ...
validation step 113/124, 0.5119988918304443 sec/step ...
validation step 114/124, 0.5089986324310303 sec/step ...
validation step 115/124, 0.4999992847442627 sec/step ...
validation step 116/124, 0.26599979400634766 sec/step ...
==================RESULT====================
Mean precision: 0.28477242935273334 ; Mean precision 19: 0.3106608320211637
Mean recall: 0.17778800456993604 ; Mean recall 19: 0.19395055043993023
Mean iou: 0.09166386208763928 ; Mean iou 19: 0.09999694045924286
各类精度:
[0.75582599 0.02915563 0.21565527 0.23253886 0.3656953 0.07058041
0.44484018 0.85019871 0.01649053 0. 0.00177607 0.43451221
0. ]
各类召回率:
[7.71562514e-02 1.81565749e-02 8.74837372e-01 3.56748679e-03
1.42451432e-01 1.25146072e-02 1.36962147e-01 2.13377728e-01
1.56482874e-04 0.00000000e+00 6.36387995e-03 6.47912094e-01
0.00000000e+00]
各类IOU:
[7.52798427e-02 1.13153965e-02 2.09200649e-01 3.52597207e-03
1.14227577e-01 1.07440397e-02 1.16968835e-01 2.05646207e-01
1.55035959e-04 0.00000000e+00 1.39047452e-03 3.51512316e-01
0.00000000e+00]
83.5981674194336 sec/validation
===================END======================
84 / 200 loss: 0.019615720957517624
해당 결과는 모델의 성능을 평가한 메트릭인 정확도, 재현율, 그리고 IOU (Intersection over Union)를 보여줍니다. 이 메트릭들은 주로 컴퓨터 비전 및 객체 감지 작업에서 모델의 성능을 측정하는 데 사용됩니다. 평균 정밀도 (Mean precision): 모델의 예측이 실제와 얼마나 일치하는지 측정한 값입니다. 평균적으로 0.199로 모델이 상당히 정확한 예측을 수행하고 있음을 나타냅니다. 클래스 19에 대한 평균 정밀도는 0.218로, 해당 클래스에 대한 정확도가 더 높음을 나타냅니다. 평균 재현율 (Mean recall): 모델이 실제 객체를 얼마나 잘 감지하는지 측정한 값입니다. 평균적으로 0.132로 모델이 높은 재현율을 가지고 있음을 나타냅니다. 클래스 19에 대한 평균 재현율은 0.144로, 해당 클래스에 대한 재현율이 높음을 나타냅니다. 평균 IOU (Mean IOU): 모델의 예측 영역과 실제 영역이 얼마나 중첩되는지를 나타내는 지표로, 일반적으로 객체 감지 작업에서 사용됩니다. 평균적으로 0.061로 모델이 중첩 정도가 상대적으로 낮음을 나타냅니다. 클래스 19에 대한 평균 IOU는 0.067로, 해당 클래스에 대한 중첩 정도가 높음을 나타냅니다. 각 클래스의 정밀도, 재현율, 그리고 IOU: 각 클래스(혹은 레이블)에 대한 정밀도, 재현율, 그리고 IOU 값이 각각 표시되며, 각 클래스의 모델 성능을 상세히 평가합니다. 마지막으로, 결과에는 검증 소요 시간(79.90 초)도 표시되어 있습니다. 이것은 모델을 검증하는 데 걸린 시간을 나타내며, 모델을 효과적으로 평가하는 데 얼마나 빠르게 수행되는지를 나타냅니다. |
훈련이 잘 안 된 이유
논문의 가중치를 그대로 옮겨와서?
논문은 20개의 클래스임.
|