상세 컨텐츠

본문 제목

[4] pytorch_yolov4로 실행해보기

DI/Mask

by hippo0207 2022. 3. 15. 15:06

본문

0. 환경설정 후 detect.py 돌려보기

python detect.py --weights .\weights\yolov4-csp-x-leaky.weights --source .\images\ --device 0 --classes 0 --cfg .\cfg\yolov4-csp-x-leaky.cfg   

일단 이건 이렇게 나옴


>> 얼굴만 detecting하도록 학습이 필요한데,,

 

네트워크 공유폴더 : \\192.168.0.202 / yjjang@di-solution.co.kr / joung1830.

1. dataset 준비 필요 (새한's dataset /Project/2021년 재난안전부처협력/마스크데이터셋/mask_nomask_dataset)annotation :

  • 학습시킬 이미지들에 대한 주석들
  • 주석 형식
    • [class_id] [center_x] [center_y] [w] [h]
      • 3 0.256 0.326 0.345 .643
      • 34 0.234 0.555 0.115 0.472
    • 각 이미지 마다 주석들이 담긴 텍스트 파일 필요
      • 0000001.txt
      • 0000002.txt
      • ...


      출처: https://eehoeskrap.tistory.com/370 [Enough is not enough]

 

2. cfg 파일, data, naml, names 파일 수정필요

  • (darknet을 학습 설명 : https://m.blog.naver.com/0duddnjs/221713290923)
  • anchor : darknet.exe detector calc_anchors data/obj.data data/yolo-obj.cfg -num_of_clusters 9 -width 416 -height 416
    • obj.data , cfg 파일은 본인의 경로에 맞게 설정해주시고 width 와 heights 역시 본인의 cfg 파일에 설정한 크기대로 설정해주시면 됩니다. 저는 416 416으로 맞췄습니다.
    • 코드를 실행해주면 평균 IoU % 값이 뜨고 anchors값이 txt로 저장이됩니다.
    • 이후에 동일하게 설정한 cfg파일을 사용하여 학습 진행해 주면 됩니다. (https://ultrakid.tistory.com/17)

 

3. weight파일은 기존꺼에서 학습더하면되는거겠쥬..?

 

https://github.com/AlexeyAB/darknet#how-to-train-to-detect-your-custom-objects 

 

GitHub - AlexeyAB/darknet: YOLOv4 / Scaled-YOLOv4 / YOLO - Neural Networks for Object Detection (Windows and Linux version of Da

YOLOv4 / Scaled-YOLOv4 / YOLO - Neural Networks for Object Detection (Windows and Linux version of Darknet ) - GitHub - AlexeyAB/darknet: YOLOv4 / Scaled-YOLOv4 / YOLO - Neural Networks for Object ...

github.com

위 사이트 차근차근보면서 해봅시다

class : yesMask, noMask, wrongMask

1. cfg파일 기존꺼 복붙하여 yolov4-mask-csp-x-leaky.cfg 하나 생성후 수정하라는거 수정

PS C:\PyTorch_YOLOv4> python train.py --weights yolov4-csp-s-leaky_mask.weights --cfg cfg/yolov4-csp-s-leaky_mask.cfg --data data/mask.yaml --device 0 --name mask_test0 --batch-size 8

  • 문제1

>> 위처럼하고 리로드하면 다시 잘되더라 (출처 : https://rasino.tistory.com/294)

 

  • 문제2
    • File "C:\Users\joj10\anaconda3\lib\site-packages\torch\nn\modules\conv.py", line 85, in __init__
          if out_channels % groups != 0:
      TypeError: not all arguments converted during string formatting  에러뜸
      >> cfg 파일에 괜히 필기한다고 뒤에 #붙이고 설명적어둔게 문제였음
      >> 첫글자가 #인거만 무시되는거였음

  • 문제3 

위에꺼 해결하고 다시돌리니ValueError: not enough values to unpack (expected 2, got 1) 에러발생

>> cfg파일에 #앞에 스페이스 한칸때문이었듬..

 

  • 문제4 디버깅으로 찾아보려했는데 

  • 문제5 디버깅말고 

아래코드로 data폴더하단에 train.txt text.txt만드니 오류바뀜

from glob import glob
from sklearn.model_selection import train_test_split

img_list = glob('C:/dataset/images/train/*.jpg')
len(img_list)

train_img_list, test_img_list = train_test_split(img_list, test_size=0.1, random_state=42)
print(len(train_img_list), len(test_img_list))

with open('./data/train.txt', 'w') as f:
    f.write('\n'.join(train_img_list) + '\n')

with open('./data/test.txt', 'w') as f:
    f.write('\n'.join(test_img_list) + '\n')

  File "C:\Users\joj10\anaconda3\envs\apple\lib\site-packages\torch\__init__.py", line 126, in <module>
    raise err

OSError: [WinError 1455] 이 작업을 완료하기 위한 페이징 파일이 너무 작습니다. Error loading "C:\Users\joj10\anaconda3\envs\apple\lib\site-packages\torch\lib\shm.dll" or one of its dependencies.

 

클래스 3개에서 2개로 줄이고(준비된 데이터셋이 마스크 있고 없고 2개뿐이라 일단 2개로 줄임)

다음날 다시돌렸는데

 

  • 문제6

  File "C:\PyTorch_YOLOv4\utils\datasets.py", line 928, in load_image
    assert img is not None, 'Image Not Found ' + path
AssertionError: Image Not Found dataset\images\train\0.jpg

아근데 왜또 이미지못찾는다캄

~~/data/obj/ 폴더생성후 train, valid 이미지, 라벨링셋 다 넣으라캐서 넣고 다시해도 마찬가지 ㅡ,.ㅡ

왜 페이징에러안뜨고 다시 이미지못찾는다는건지ㅡㅡ

 

- 이미지 obj폴더에 때려넣고, mask.data 파일 변경

classes=2
train= data/train.txt
valid= data/test.txt
names= data/mask.names
back = backup/

후 makeTrainTXT 파일 수정해서 다시돌려서 train.txt, test.txt 파일 다시만듦

근데도아직 obj폴더에서 이미지안찾고 dataset\images\train\0.jpg 여기서 찾음

아 yaml파일도 수정해야한다

# train and val datasets (image directory or *.txt file with image paths)
train: data/train.txt  # 118k images
val: data/test.txt  # 5k images
#test: ../coco/testdev2017.txt  # 20k images for submission to https://competitions.codalab.org/competitions/20794

# number of classes
nc: 2

# class names
names: ['noMask', 'yesMask']
#names: ['noMask', 'yesMask', 'wrongMask']

오.. 뭔가 돌아가는거같더니 런타임에러걸림

RuntimeError: CUDA out of memory. Tried to allocate 1.92 GiB (GPU 0; 6.00 GiB total capacity; 1.26 GiB already allocated; 3.15 GiB free; 1.31 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

 

- width, height 512 >> 416으로 수정  >> 안됨

- 배치사이즈 64 >> 32 로 수정 >> 안됨

- https://bskyvision.com/799 

 

[python] 메모리 에러 해결법(MemoryError: Unable to allocate ## for an array with shape ## and data type ##)

저는 윈도우즈 10, 아나콘다 환경에서 파이썬 코드를 실행하다가 종종 다음과 같은 에러를 만났었습니다. 메모리에러 즉, 램(RAM) 메모리가 부족해서 생기는 오류입니다. 참고로 램은 주기억장치

bskyvision.com

3번대로 페이징파일 크기 증가시키기  .. 맘대로해도되나이거 

일단다른방법 찾아보기

train.py 에 train함수 타고들어가서 module.py 의 train 에

		import gc
        
        gc.collect()
        torch.cuda.empty_cache()

위코드 한번더 추가함 (찾아보니 여기저기 엠티캐시 있긴했었음)

 

(보다보니 wandb 가 import안되어있기에 하고 가입까지했더니 학습안되고 그래프만나오기에 일단 None 처리해둠)

 

  • 문제7

RuntimeError: cuDNN error: CUDNN_STATUS_INTERNAL_ERROR

 

배치를 줄이니 모자라다는 메모리는 점점줄음 

ㅠㅠㅠ 저거해도 안되기에 배치사이즈를 8까지줄여도 안되기에 웨이트파일자체를 더 가벼운걸로바꾸니 된다
(cfg도 같이바꾸고 안에내용도 같이수정)

yolov4-csp-x-leaky >> yolov4-csp-s-leaky 로 바꿈

꺄 루

 

https://velog.io/@jhlee508/Object-Detection-YOLOv4-Darknet-%ED%95%99%EC%8A%B5%ED%95%98%EC%97%AC-Custom-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%9D%B8%EC%8B%9D-%EB%AA%A8%EB%8D%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0-feat.-AlexeyABdarknet

 

[Object Detection] YOLOv4 Darknet 학습하여 Custom 데이터 인식 모델 만들기 (feat. AlexeyAB/darknet)

손 쉽게 YOLO 물체 인식 모델을 학습하여 사용자가 원하는 Custom object를 인식하는 모델을 만들어 보자.

velog.io

위 사이트 train시키는거 설명잘해둠 기억안나면 참고하기

     Epoch   gpu_mem       box       obj       cls     total   targets  img_size
   299/299     2.22G   0.01389  0.004427 0.0004691   0.01879         9       640: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████| 291/291 [00:42<00:00,  6.89it/s] 
               Class      Images     Targets           P           R      mAP@.5  mAP@.5:.95:   0%|                                                                                                        | 0/17 [00:00<?, ?it/s] 
Traceback (most recent call last):
  File "train.py", line 542, in <module>
    train(hyp, opt, device, tb_writer, wandb)
  File "train.py", line 341, in train
    results, maps, times = test.test(opt.data,
  File "C:\PyTorch_YOLOv4\test.py", line 226, in test
    plot_images(img, output_to_target(output, width, height), paths, f, names)  # predictions
  File "C:\PyTorch_YOLOv4\utils\plots.py", line 108, in output_to_target
    return np.array(targets)
  File "C:\Users\joj10\anaconda3\lib\site-packages\torch\_tensor.py", line 732, in __array__
    return self.numpy()
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
Internal process exited

트레이닝 결과! 

 

  • 문제8 : TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host emory first.

https://blog.naver.com/PostView.naver?blogId=jaeyoon_95&logNo=222109610256&categoryNo=94&parentCategoryNo=0&viewDate=&currentPage=1&postListTopCurrentPage=1&from=search

라고 하는데 

일단 이렇게 해두고 (원래는 self.numpy() )

[train.py]
# DDP process 0 or single-GPU
        if rank in [-1, 0]:
            # mAP
            if ema:
                ema.update_attr(model)
            final_epoch = epoch + 1 == epochs
            if not opt.notest or final_epoch:  # Calculate mAP
                if epoch >= 3:
                    results, maps, times = test.test(opt.data,

여기서 오류시작된것. test.py 만 다시돌려보기 

yaml파일 수정(test파일 위치넣기), test.txt파일 생성(경로나오게), 

python test.py --batch 8 --data data/mask.yaml --cfg cfg/yolov4-csp-s-leaky_mask.cfg --device 0 --weights runs\train\mask_test44\weights\best_293.pt --task test --names data/mask.names 

wandb 끄면 일캐뜸

wandb 키면

 

detect.py 로 돌려보면 

python detect.py --weight runs/train/mask_test44/weights/best_overall.pt --source ../dataset/images/val --device 0 --cfg cfg/yolov4-csp-s-leaky_mask.cfg --names data/mask.names

 

일케뜸

image 173/176 C:\dataset\images\val\single2-100401000.jpg: 640x640 1 YesMasks, Done. (0.017s)
image 174/176 C:\dataset\images\val\single2-100402055.jpg: 640x640 1 YesMasks, Done. (0.016s)
image 175/176 C:\dataset\images\val\single2-100409003.jpg: 640x640 1 YesMasks, Done. (0.016s)
image 176/176 C:\dataset\images\val\single2-100415000.jpg: 640x640 1 YesMasks, Done. (0.015s)
Results saved to inference\output
Done. (5.163s)

 

'DI > Mask' 카테고리의 다른 글

[5] vscode 디버깅오류  (0) 2022.03.28
[6] dataset 만들기-1 retinaFace 함수알아보기  (0) 2022.03.28
[3.1] darknet.h 파일못찾는 문제 발생  (0) 2022.03.11
[3] yolov4 환경셋팅  (0) 2022.03.11
[2] 마스크 프로젝트 시작  (0) 2022.03.07

관련글 더보기

댓글 영역