본문 바로가기

딥러닝/CNN

[Object Detection] [Birds Classification] 3. 구글 colab 환경에서 darknet 신경망에 넣어 학습 (가중치, 환경구성파일)

라벨링된 이미지 폴더 .zip 파일 구글 드라이브에 올려놓기. 

  • 라벨링된 이미지 폴더 .zip 파일 구글 드라이브에 올려놓기
    • 업로드 시간 걸림
    • 구글 드라이브에 직접 yolo_custom_model_Training3 폴더에 animal.zip 파일 올리기
    • 후에 리눅스 명령어로 unzip 명령어로 압축 풀 예정 -> custom_data 폴더로 압축 풂 ⇒ 링크 6번

코랩의 GPU 체크하기

!nvidia-smi -L

 

Mount Google Drive → 구글 드라이브에 마운트 하기

from google.colab import drive
drive.mount('/content/drive')

 

unzip picture_data(for train_test) yolo_custom_model_Training3 폴더 만들기

%cd /content/drive/MyDrive
!mkdir yolo_custom_model_Training3

 

yolo_custom_model_Training3 폴더 밑에 어떤 파일있는지 확인하기

  • 라벨링된 이미지 데이터 .zip 파일 있어야함 없으면 옮겨 놓기
!ls '/content/drive/MyDrive/yolo_custom_model_Training3'

 

(1) ‘yolo_custom_model_Training3’로 경로 이동

(2) 라벨링된 이미지 폴더 (.zip 파일) 압축 해제할 폴더 만들기 → 여기서는 ‘custom_data’ 라는 이름으로 생성

%cd /content/drive/MyDrive/yolo_custom_model_Training3
!mkdir custom_data

 

압축 풀기 (zip 파일을 위에 만든 custom_data 폴더에 푼다.)

!unzip '/content/drive/MyDrive/yolo_custom_model_Training3/animal.zip' -d '/content/drive/MyDrive/yolo_custom_model_Training3/custom_data'

현재디렉토리 확인하기

%pwd

Object detection 을 전문으로 하는 darknet 신경망 다운

git 허브 주소 입력하여 다운받을 경로 입력하기

  • 나중에 다운 완료후 폴더 확인해보면 여러가지 폴더가 많이 생긴것 확인 가능
# download dataset in current directory(above path)
!git clone '<https://github.com/AlexeyAB/darknet.git>' '/content/drive/MyDrive/yolo_custom_model_Training3/darknet'

 

현재 디렉토리에서 → 다크넷(신경망) 디렉토리로 이동하기

# move current directory to darknet
%cd /content/drive/MyDrive/yolo_custom_model_Training3/darknet

darknet 환경설정 변경

makefile 내용 수정

- makefile 이라는 file 이 있는데 그 내용이 수정이 필요하다.
- 지금 0 으로 사용하지 않겠다고 되어있는데 1 로 바꿔서 사용하겠다고 바꿔주는 리눅스 명령어 이다.(vi 편집기 명령어)
- Makefile 에서 ~~ 라고 바꿔라 라고 하는 명령어 내용이다.
- opencv, GPU, (CUCNN , CUDNN_HALF ) -> 쿠다(CUDA)를 사용하기위한 , LIBSO 를 사용하는것으로 환경설정 바꿈
    - CUDA? : GUP를 현재 피씨에서 사용할 수 있게 해주는 펌웨어 (하드웨어를 작동시키기 위한 소프트웨어)
    - LIBSO : Library 관련한 파라미터인 것
# change setting values in 'Makefile' file 
!sed -i 's/OPENCV=0/OPENCV=1/' Makefile
!sed -i 's/GPU=0/GPU=1/' Makefile
!sed -i 's/CUDNN=0/CUDNN=1/' Makefile
!sed -i 's/CUDNN_HALF=0/CUDNN_HALF=1/' Makefile
!sed -i 's/LIBSO=0/LIBSO=1/' Makefile

 

makefile 수정한 내용 compile 시키기

  • 쭉 길게 나요는 내용들은 에러가 아님
# Compile model
"""  take care do not disconnect : file directory may be interupted 
if your network down during compile, I recommend delete darknet folder and restart number 4(get AlexeyAB/darknet)"""

!make

 

다운 받은 다크넷 신경망 setting 하기

  • 상위디렉토리로 이동
  • 그냥 darknet 을 실행하기만 하면 된다.
  • 성공했을때 나오는 문구 : usage: darknet/darknet
%cd ..
!darknet/darknet

훈련 & 테스트 데이터 생성하기

object detection 에 필요한 파이썬 코드 4개 다운받기

!git clone '<https://github.com/jakkcoder/training_yolo_custom_object_detection_files>' '/content/drive/MyDrive/yolo_custom_model_Training3/training_yolo_custom_object_detection_files-main'

 

다운받은 위치로 이동

%cd /content/drive/MyDrive/yolo_custom_model_Training3/training_yolo_custom_object_detection_files-main

 

training_yolo_custom_object_detection_files-main 파일명안에 4개 존재해야함

  • 해당 파일 역할 : 훈련시키기 전에 파일들의 이름을 바꾸고 변경하는 코드들
# check out current dir files
!ls

 

위의 코드중 ‘creating-files-data-and-name.py’ ,’ creating-train-and-test-txt-files.py’ , 두가지 py 파일을 custom_data 폴더밑으로 복사하기

# copy creating-train-and-test-txt-files.py & creating-files-data-and-name.py
"""creating-train-and-test-txt-files.py >> create 'train.txt' & 'test.txt' files
   creating-files-data-and-name.py >> create label 'labelled_data.data' file
   <if you excute both .py files, you get mentioned files upper lines 2,3>"""

!cp creating-train-and-test-txt-files.py /content/drive/MyDrive/yolo_custom_model_Training3/**custom_data**
!cp creating-files-data-and-name.py /content/drive/MyDrive/yolo_custom_model_Training3/**custom_data**

 

복사해놓은 custom_data 폴더로 위치 이동하기

%cd /content/drive/MyDrive/yolo_custom_model_Training3/custom_data

 

내용 수정하기

1. 리눅스 명령어로 creating-train-and-test-txt-files.py 의 내용중 39 번째 라인에있는 디렉토리를 custom_data 로 변경
@ 를 쓴다. 첫번째 sed 위치 변경 내용
변경 전 내용 : !sed -i '39 s@/home/my_name/Downloads/video-to-annotate
변경 후 내용 : custom_data

2. creating-train-and-test-txt-files.py
jpeg 를 현재파일형식인 jpg 로 바꿈

3. creating-files-data-and-name.py
변경 전 내용 : home/my_name/Downloads/video-to-annotate
변경 후 내용 : custom_data
# change paths in both .py files
!sed -i '39 s@/home/my_name/Downloads/video-to-annotate@**custom_data**@' creating-train-and-test-txt-files.py
!sed -i '74 s@jpeg@jpg@' creating-train-and-test-txt-files.py
!sed -i '36 s@/home/my_name/Downloads/video-to-annotate@**custom_data@**' creating-files-data-and-name.py

 

다시 상위디렉토리로 이동하기

# move current dir one step before
%cd ..

 

훈련데이터(train.txt 에 있음) 목록과 테스트 데이터(test.txt) 목록을 custom_data 폴더에 생성하는 코드 실행

  • 랜덤으로 골라서 만들어 낸다.
# excute .py file >> 'train.txt', 'test.txt'   
!python **custom_data**/creating-train-and-test-txt-files.py

 

훈련데이터 목록, 테스트 데이터 목록 , class 이름이 어디있는지 목록정보를 custom_data 폴더에 만들어주는 코드

클릭해서 들어가보면


classes = 2 train = custom_data/
train.txtvalid = custom_data/
test.txtnames = custom_data/
classes.names
backup = backup


의 내용들이 존재

# excute .py file >> 'labelled_data.data'
!python custom_data/creating-files-data-and-name.py

%pwd

yolo4.conv.137 다운받기

  • 인터넷에 google 검색 : yolo4.conv.137 후 다운
  • 현재 내 컴퓨터에 위치 경로는 : C:\deeplearning\object_detection
  • 해당 파일 구글 드라이브에 업로드한다. (위치 : yolo_custom_model_Training3 폴더)
  • 이 파일은 컨볼루션 층 정보이다.

훈련모델 만들기 위한 밑 작업

custom_weight 폴더 생성

# create directory 'custom_weight'
!mkdir custom_weight

내 위치 확인

%pwd

yolov4.conv.137 파일 확인하기

%ls -l
# 결과 
total 166074
drwx------  2 root root      4096 May  1 05:27backup/
drwx------  2 root root      4096 May  1 05:25custom_data/
drwx------  2 root root      4096 May  1 05:27**custom_weight/**
drwx------ 16 root root      4096 May  1 05:24darknet/
drwx------  3 root root      4096 May  1 05:24training_yolo_custom_object_detection_files-main/
**-rw-------  1 root root 170038676 May  1 01:16 yolov4.conv.137**

리눅스 명령어로 yolov4.conv.137 파일 custom_weight 로 이동시키기

# move 'yolov4.conv.137' file to 'custom_weight' dir
!mv /content/drive/MyDrive/yolo_custom_model_Training3/yolov4.conv.137 custom_weight/

darknet 신경망의 cfg 파일 환경설정 변경하기

  • yolo_custom_model_Training3/darknet/cfg 로 가면 다양한 환경구성 파일들이 존재하는데 가장 마지막인 yolo4 의 환경구성 파일을 변경한다.

환경구성 파일로 이동하기

%cd /content/drive/MyDrive/yolo_custom_model_Training3/darknet/cfg

 

다크넷 폴더 밑 cfg 밑에 yolo 의 환경구성파일들이 버전별로 존재 → 그쪽으로 리눅스 명령어로 yolov4.cfg 를 yolov4_custom.cfg 이름으로 다시 복사

  • object detection 을 구성하기 위한것들
  • custom.cfg 가 생성된것을 볼 수 있고 → 나중에 이것을 따로 다운로드 받을 예정이다.
# copy yolov4.cfg file & rename & paste
!cp yolov4.cfg yolov4_custom.cfg

 

복사한 yolov4_custom.cfg 를 가지고 나의 환경에맞게 변경한다.

yolov4_custom.cfg 환경설정 변경

1. 2번째 라인 : 배치사이즈 8로 변경 (메모리 초과오류 방지를 위한 과정)

2. 7,8번째 라인 : 이미지의 가로세로 사이즈 변경 (메모리 초과 오류 방지위함)

3. 19 번째 라인 : class(2개) * 2000 이므로4000으로 바꾸기 

4. 21 라인 : 40000,45000 사이즈를 0.8,0.9 를 곱하여 작은 사이즈 3200,3600로변경

5. 기존코드에서는 클래스의 갯수가 80 개였다. 우리는 2개(너구리,고라니)이기때문에 2개로 변경한다.

6. 961,1049,1137 번째라인 : 합성곱 filters=255@filters=21 로 필터 갯수 변경하기
# change values for training
!sed -i '2 s@batch=64@batch=8@' yolov4_custom.cfg # 64 로 돌리면 메모리 초과오류 날 수 있음 8로 변경 

!sed -i '7 s@width=608@width=416@' yolov4_custom.cfg # 이미지의 가로 세로 변경 
!sed -i '8 s@height=608@height=416@' yolov4_custom.cfg  

!sed -i '19 s@500500@4000@' yolov4_custom.cfg  #maxbatch = class*2000 (클래스갯수 * 2000 )
!sed -i '21 s@400000,450000@3200,3600@' yolov4_custom.cfg  # maxbatch*0.8, maxbatch*0.9

# 기존코드에서는 클래스 갯수 80개 변경할 클래수 갯수는 2개 
!sed -i '968 s@classes=80@classes=2@' yolov4_custom.cfg
!sed -i '1056 s@classes=80@classes=2@' yolov4_custom.cfg
!sed -i '1144 s@classes=80@classes=2@' yolov4_custom.cfg

# 합성곱시 쓰이는 filter 의 갯수 
!sed -i '961 s@filters=255@filters=21@' yolov4_custom.cfg  #filters=(4+1+classes)*3 
!sed -i '1049 s@filters=255@filters=21@' yolov4_custom.cfg
!sed -i '1137 s@filters=255@filters=21@' yolov4_custom.cfg

 

폴더 위치 이동하기 /content/drive/MyDrive/yolo_custom_model_Training3

%cd /content/drive/MyDrive/yolo_custom_model_Training3

  1. 학습될 가중치를 저장할 backup 폴더 생성
!mkdir backup

 

/content/drive/MyDrive/yolo_custom_model_Training3로 이동

%cd /content/drive/MyDrive/yolo_custom_model_Training3

신경망 학습

학습시 필요한 파일은

  1. labelled_data.data
  2. yolov4_custom.cfg
  3. yolov4.conv.137

이렇게 세가지 이다.

!darknet/darknet detector train custom_data/labelled_data.data darknet/cfg/yolov4_custom.chg custom_weight/yolov4.conv.137 -dont_show

학습이 완료 된 뒤 로컬로 다운받아야하는것

가중치와 cfg

  1. yolov4_custom.cfg
    • darknet/cfg/yolov4_custom.dfg
  2. 가중치!! (backup 밑에 있습니다. )
    • backup/yolov4_custom_last.weights