• 카테고리

    질문 & 답변
  • 세부 분야

    컴퓨터 비전

  • 해결 여부

    해결됨

mmdetection mask-rcnn 모델 훈련 성공 후 inference 오류

23.04.02 19:59 작성 조회수 958

2

안녕하세요... 좋은 강의 감사합니다.

 

제가 질문 드리고자 하는 부분은 다음과 같습니다.

이미지 데이터셋을 자체적으로 만들어서 코랩에서 학습을 시키고, 학습된 모델을 코랩에서 inference 는 되는데, 이 모델을 제 개인 컴퓨터 ( GPU가 없는 cpu 로 진행)에서 진행하면 아래와 같은 오류가 발생하면서 작동이 되지 않습니다.

진행순서는 다음과 같습니다.

  1. 자체 이미지셋 50장을 코랩에서 mmdetection mask-rcnn 으로 학습 (pre-train 모델 사용)

  2. 학습 성공후, 코랩 유지상태에서 테스트용 이미지 inference 성공, 보기 및 저장 성공

  3. 학습된 epoch.pth 모델을 다운받아서 개인 pc (CPU only) inference. 할 경우 아래와 같은 오류발생,

  4. mmdetection 예제 모델로 예제 이미지를 개인 pc에 다운받아서 inference 할 경우느 성공

  5. 혹시 몰라서 tools  폴더내 publish.py로 모델을 생성해서도 해보았으나, 동일한 오류 발생



    오류 내용은 다음과 같습니다.


    load checkpoint from local path: /Users/category/Projects/WatizB/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_WatizB-ddc77fa4.pth

    The model and loaded state dict do not match exactly

    size mismatch for roi_head.bbox_head.fc_cls.weight: copying a param with shape torch.Size([12, 1024]) from checkpoint, the shape in current model is torch.Size([81, 1024]).

    size mismatch for roi_head.bbox_head.fc_cls.bias: copying a param with shape torch.Size([12]) from checkpoint, the shape in current model is torch.Size([81]).

    size mismatch for roi_head.bbox_head.fc_reg.weight: copying a param with shape torch.Size([44, 1024]) from checkpoint, the shape in current model is torch.Size([320, 1024]).

    size mismatch for roi_head.bbox_head.fc_reg.bias: copying a param with shape torch.Size([44]) from checkpoint, the shape in current model is torch.Size([320]).

    size mismatch for roi_head.mask_head.conv_logits.weight: copying a param with shape torch.Size([11, 256, 1, 1]) from checkpoint, the shape in current model is torch.Size([80, 256, 1, 1]).

    size mismatch for roi_head.mask_head.conv_logits.bias: copying a param with shape torch.Size([11]) from checkpoint, the shape in current model is torch.Size([80]).

    [[[148 148 148]

    [147 147 147]

    [147 147 147]

    ...

    [150 148 140]

    [152 149 141]

    [151 149 139]]

    [[147 147 147]

    [147 147 147]

    [147 147 147]

    ...

    [154 151 146]

    [154 151 143]

    [151 149 139]]

    [[147 147 147]

    [147 147 147]

    [147 147 147]

    ...

    [157 154 149]

    [155 152 144]

    [152 149 141]]

    ...

    [[155 155 155]

    [154 154 154]

    [154 154 154]

    ...

    [150 148 148]

    [151 149 149]

    [151 149 149]]

    [[153 153 153]

    [154 154 154]

    [154 154 154]

    ...

    [149 147 147]

    [150 148 148]

    [150 148 148]]

    [[152 152 152]

    [153 153 153]

    [155 155 155]

    ...

    [149 147 147]

    [149 147 147]

    [150 148 148]]]

    /Users/category/Projects/WatizB/mmdetection/mmdet/datasets/utils.py:66: UserWarning: "ImageToTensor" pipeline is replaced by "DefaultFormatBundle" for batch inference. It is recommended to manually replace it in the test data pipeline in your config file.

    warnings.warn(

 

바쁘시겟지만 확인 혹시 이런 상황에 대한 경험이 있으시면 답변 부탁드립니다.

 

수고하세요>~~

 

답변 1

답변을 작성해보세요.

1

안녕하십니까,

음, 적어주신대로라면 오류가 발생하지는 않아야 합니다만,,,

일단 전체 코드를 보지않고 올려주신 에러만으로는 뭐가 문제인지 찾기가 어렵지만,

제 생각으로는 config가 잘못 설정되어 있지 않나 싶습니다.

오류 메시지를 보면 checkpoint로 로딩한 모델은 label이 12개(background까지 포함)인 걸로 보이는데, 학습하려는 모델의 config는 coco dataset가 동일한 81개(background까지 포함)으로 보입니다.

다시 한번 config 부분을 살펴보셨으면 합니다.

그래도 안되면 전체 소스코드와 어떤 부분을 변경해서 작업을 하신건지 좀 더 상세하게 기재 부탁드립니다.

감사합니다.

 

Ramnant님의 프로필

Ramnant

질문자

2023.04.04

빠른 답신 감사합니다. ^^

참. 이와는 별개로 오늘 코랩에서 테스트를 하는데, 코랩 파이토치 환경이 2.0으로 변경되었던데 그 이후로 mmcv가 설치시 아래와 같이 진행이 안되는데.. 바쁘시겟지만 이것도 한번 확인 부탁드립니다.

import torch
print(torch.__version__)

2.0.0+cu118

image

 

아래는 제가 사용한 train 용 코드와 inference 용 코드입니다.

trian은 선생님 강의에서 balloon maskrcnn train 코드를 일부 발췌해서 코랩에서 진행햇습니다.

훈련용 코드인데,, 코랩 파일을 다시 붙여서 올리다 보니.. 이점 양해부탁드립니다. ^

======================


config_file = '/content/mmdetection/configs/mask_rcnn/mask_rcnn_r101_fpn_1x_coco.py'
checkpoint_file = '/content/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_coco_20200204-1efe0ed5.pth'

from mmdet.datasets.builder import DATASETS
from mmdet.datasets.coco import CocoDataset

@DATASETS.register_module(force=True)
class AlgaeDataset(CocoDataset):
      CLASSES = ('microcystis', 'anabaena', 'oscillatoria', 'aphanizomenon',
                 'synedra', 'aulacoseira', 'fragilaria', 'pediastrum',
                 'staurastrum', 'eudorina', 'asterionella')



from mmcv import Config

cfg = Config.fromfile(config_file)
print(cfg.pretty_text)

from mmdet.apis import set_random_seed

# dataset에 대한 환경 파라미터 수정. 
cfg.dataset_type = 'AlgaeDataset'
cfg.data_root = '/content/drive/MyDrive/AlgaeDB/'

# train, val, test dataset에 대한 type, data_root, ann_file, img_prefix 환경 파라미터 수정. 
cfg.data.train.type = 'AlgaeDataset'
cfg.data.train.data_root = '/content/drive/MyDrive/AlgaeDB/'
cfg.data.train.ann_file = 'train.json'
cfg.data.train.img_prefix = 'train'

cfg.data.val.type = 'AlgaeDataset'
cfg.data.val.data_root = '/content/drive/MyDrive/AlgaeDB/'
cfg.data.val.ann_file = 'val.json'
cfg.data.val.img_prefix = 'val'



# class의 갯수 수정. 
cfg.model.roi_head.bbox_head.num_classes = 11
cfg.model.roi_head.mask_head.num_classes = 11

# pretrained 모델
cfg.load_from = '/content/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_coco_20200204-1efe0ed5.pth'

# 학습 weight 파일로 로그를 저장하기 위한 디렉토리 설정. 
cfg.work_dir = '/content/drive/MyDrive/AlgaeDB/Output'

# 학습율 변경 환경 파라미터 설정. 
#cfg.optimizer.lr = 0.02 / 8
cfg.auto_scale_lr.enable=True #dict(enable=False, base_batch_size=16)
cfg.lr_config.warmup = None
cfg.log_config.interval = 10

# CocoDataset의 경우 metric을 bbox로 설정해야 함.(mAP아님. bbox로 설정하면 mAP를 iou threshold를 0.5 ~ 0.95까지 변경하면서 측정)
cfg.evaluation.metric = ['bbox', 'segm']
#cfg.evaluation.interval = 12
#cfg.checkpoint_config.interval = 12

# 평가 metric 수행할 epoch interval 설정.
cfg.evaluation.interval = 10
# 학습 iteration시마다 모델을 저장할 epoch interval 설정. 
cfg.checkpoint_config.interval = 10

# epochs 횟수는 36으로 증가 
cfg.runner.max_epochs = 10

# 학습 시 Batch size 설정(단일 GPU 별 Batch size로 설정됨)
cfg.data.workers_per_gpu = 1
cfg.data.samples_per_gpu = 5

# 두번 config를 로드하면 lr_config의 policy가 사라지는 오류로 인하여 설정. 
cfg.lr_config.policy='step'
# Set seed thus the results are more reproducible
cfg.seed = 0
set_random_seed(0, deterministic=False)
cfg.gpu_ids = range(1)

# ConfigDict' object has no attribute 'device 오류 발생시 반드시 설정 필요. https://github.com/open-mmlab/mmdetection/issues/7901
cfg.device='cuda'



from mmdet.datasets import build_dataset
from mmdet.models import build_detector
from mmdet.apis import train_detector

# train용 Dataset 생성. 
datasets = [build_dataset(cfg.data.train)]

model = build_detector(cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg.get('test_cfg'))
model.CLASSES = datasets[0].CLASSES
print(model.CLASSES)

import os.path as osp
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
# epochs는 config의 runner 파라미터로 지정됨. 기본 12회 
train_detector(model, datasets, cfg, distributed=False, validate=True)


#inference image

from mmdet.apis import inference_detector, show_result_pyplot


checkpoint_file = '/content/drive/MyDrive/AlgaeDB/Output/epoch_10.pth'

# checkpoint 저장된 model 파일을 이용하여 모델을 생성, 이때 Config는 위에서 update된 config 사용. 
model_ckpt = init_detector(cfg, checkpoint_file, device='cuda:0')


import cv2

imgPath = '/content/drive/MyDrive/AlgaeDB/test/'
imgFile = 'C133301_20220421_162942824.jpg'

img = cv2.imread(imgPath + imgFile)


confidence_level = 0.5
result = inference_detector(model_ckpt, img)
show_result_pyplot(model_ckpt, img, result, score_thr=confidence_level)


 

이후 생성된 모델을 epoch 파일과 publish 도구를 이용하여 생성한 파일 2가지를 가지고 제 PC에서 inference 를 수행했습니다. (제 컴은 맥북 M1 입니다.)

 

코드는 다음과 같습니다. (일부 불필요한 코드도 있는데... 양해 부탁드립니다.)

 

# This is a sample Python script.

import torch
import mmcv
import cv2
import os

print ('=================================')
print (os.getcwd())
print ('==================================')


from mmdet.datasets.builder import DATASETS
from mmdet.datasets.coco import CocoDataset
@DATASETS.register_module(force=True)
class AlgaeDataset(CocoDataset):
      CLASSES = ('microcystis', 'anabaena', 'oscillatoria', 'aphanizomenon',
                 'synedra', 'aulacoseira', 'fragilaria', 'pediastrum',
                 'staurastrum', 'eudorina', 'asterionella')

from mmdet.apis import init_detector, inference_detector, show_result_pyplot




config_file = '/Users/*****/Projects/WatizB/mmdetection/configs/mask_rcnn/mask_rcnn_r101_fpn_1x_coco.py'
#checkpoint_file = 
checkpoint_file = '/Users/*****y/Projects/WatizB/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_WatizB-ddc77fa4.pth'



from mmcv import Config
cfg = Config.fromfile(config_file)


# class의 갯수 수정. 
cfg.model.roi_head.bbox_head.num_classes = 11
cfg.model.roi_head.mask_head.num_classes = 11

cfg.evaluation.metric = ['bbox', 'segm']

######

# dataset에 대한 환경 파라미터 수정. 
cfg.dataset_type = 'AlgaeDataset'
cfg.data_root = '/content/drive/MyDrive/AlgaeDB/'

# train, val, test dataset에 대한 type, data_root, ann_file, img_prefix 환경 파라미터 수정. 
cfg.data.train.type = 'AlgaeDataset'
cfg.data.train.data_root = '/content/drive/MyDrive/AlgaeDB/'
cfg.data.train.ann_file = 'train.json'
cfg.data.train.img_prefix = 'train'

cfg.data.val.type = 'AlgaeDataset'
cfg.data.val.data_root = '/content/drive/MyDrive/AlgaeDB/'
cfg.data.val.ann_file = 'val.json'
cfg.data.val.img_prefix = 'val'







######
print (cfg.pretty_text)

model = init_detector(config_file, checkpoint_file, device='cpu')  # or device='cuda:0'


imgFile = cv2.imread('/Users/category/Projects/WatizB/AlgaeDB/test/test_img15.jpg')
print (imgFile)



#imgFile = 'demo/demo.jpg'

result = inference_detector(model, imgFile)
show_result_pyplot(model, imgFile, result, 0.3)

print (result)

 

 

이렇게 했는데, 제 맥북에서는 위에서 오류가 발생하네요..

config에 문제가 있을까요?? 이것 저것 해보다가 안되어서 경로명도 혹시 몰라 동일하게 변경도 해보았습니다. ㅜㅜ

 

바쁘시겠지만 의견 부탁드립니다.

 

참 mmdetection은 최신버전을 사용했습니다.

하, 벌써 2.0으로 바뀌었군요.

만약에 설치가 잘 안되시면, 런타임 연결해제 및 삭제로 커널을 초기화 하시고

아래 명령어로 pytorch 1.13.0 을 재 설치 하신 후에 mmdetection을 설치하고 실습 코드를 수행하시면 될 것 같습니다.

!pip install torch==1.13.0+cu116 torchvision==0.14.0+cu116 torchaudio==0.13.0 --extra-index-url https://download.pytorch.org/whl/cu116

그리고,,

올려 주신 코드 중 inference 코드에서 오류가 발생하시는 거죠?

아래 checkpoint 파일은 custom 데이터로 학습이 완료된 파일이죠?

checkpoint_file = '/Users/*****y/Projects/WatizB/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_WatizB-ddc77fa4.pth'

학습 후에 가져온 checkpoint 파일은 아래와 같이 보이는데, 혹시나 해서 여쭙습니다.

checkpoint_file = '/content/drive/MyDrive/AlgaeDB/Output/epoch_10.pth'

Ramnant님의 프로필

Ramnant

질문자

2023.04.04

  1. 코랩 설치 관련::: 보내주신 내용대로 설치를 해보았는데.. 아래와 같은 에러는 발생하지만 문제는 해결이 되어 설치가 가능 하네요. ^^ 고맙습니다.~~

     

    image

    2. 모델 학습 및 inference관련 문의하신 부분은 다음과 같습니다.

 

올려 주신 코드 중 inference 코드에서 오류가 발생하시는 거죠?

==> 네 inference 에서 오류가 발생합니다.(코랩에서는 정상작동, 맥으로 다운받아서 inference 실행시 오류발생)

아래 checkpoint 파일은 custom 데이터로 학습이 완료된 파일이죠?

===> 네 수중 조류 이미지를 class 11개를 만들어서 학습완료한것입니다.

====> checkpoint_file = '/content/drive/MyDrive/AlgaeDB/Output/epoch_10.pth' 파일은 코랩 학습 후 생긴 파일이고 이파일로 코랩에서 inference를 수행 했을때 정상작동하였습니다.

=====> 그런데 상기 epoch_10.pth 파일을 제 맥으로 다운 받아서 inference코드로 작성해서 실행하면 이전에 올린 오류 메세지가 발생합니다

=====> mask_rcnn_r101_fpn_1x_WatizB-ddc77fa4.pth' 파일의 경우 publish 도구를 이용해서 만들어서 사용해야 하나 해서 혹시나 하고 한번 더 만들어서 테스트를 해본 파일입니다.

checkpoint_file = '/Users/*****y/Projects/WatizB/mmdetection/checkpoints/mask_rcnn_r101_fpn_1x_WatizB-ddc77fa4.pth'

학습 후에 가져온 checkpoint 파일은 아래와 같이 보이는데, 혹시나 해서 여쭙습니다.

checkpoint_file = '/content/drive/MyDrive/AlgaeDB/Output/epoch_10.pth'

checkpoint_file = '/content/drive/MyDrive/AlgaeDB/Output/epoch_10.pth' 파일이 학습 후 생긴 파일이고 이파일로 코랩에서 inference를 수행 했을때 정상작동하였습니다.

=> 코랩에서 inference할 때도 /content/drive/MyDrive/AlgaeDB/Output/epoch_10.pth 를 init_detector()로 만드신 후 inference를 했는데 아무런 문제가 없었나요?

그리고 config 설정도 코랩에서 사용한 설정을 그대로 맥에서도 적용하신건가요?

아, 그리고 오류가

model = init_detector(config_file, checkpoint_file, device='cpu') 에서 발생하나요?

아님, result = inference_detector(model, imgFile) 에서 발생하나요?

아래 코드에서

model = init_detector(config_file, checkpoint_file, device='cpu')

코드를 보시면 기본 config_file을 인자로 하고 있습니다. 그러니까 checkpoint는 class가 12개 인데 기본 config_file은 coco로 class가 81개 이기 때문에 오류가 발생하는 것 같습니다.

지금 cfg 객체로 기본 config를 수정했으니까 아래와 같이 cfg 를 인자로 넣어줘보십시요.

model = init_detector(cfg, checkpoint_file, device='cpu')

Ramnant님의 프로필

Ramnant

질문자

2023.04.05

너무 기본적인 부분을 미쳐 확인하지 못한것 같습니다. 노안 떄문인지.. ㅜㅜ

알려주신 부분 수정하니 정상적으로 작동되는 것 확인했습니다.

너무 신속하고 친절하게 답변 해주셔서 고맙습니다.

기초를 좀더 다지기 위해서 철민님의 파이썬 머신러닝 완벽가이드도 수강신청했는데 얼른 강의를 시청해야할것 같습니다.

좋은 하루 되세요.~~

해결이 되었다니 다행입니다 ^^

다른 강의도 수강해 주시고, 감사합니다.