주제
목표
- Data Preprocessing(1일차)
- CNN 모델링
- Data Augmentation & Transfer Learning
개인 목표
- 모델링 수행 과정 체계적으로 작성하기
- 결과 파일 및 폴더 일관성있게 정리하기
- VGG, ResNet 등 3개 이상 모델 사용해보기
0. 환경설정
colab-구글 드라이브 연동
데이터셋 불러오기
- 주어진 데이터가 zip파일 -> zipfile 모듈 활용
import zipfile
data = zipfile.ZipFile(압축파일의 경로)
data.extractall(압축 해제한 파일들 저장할 위치)
1. 데이터 전처리
데이터 분할
방법 1. splitfolders 모듈
- train, validation, test 데이터셋을 만들기
- splitfolders 모듈 활용: pip install split-folders
- 데이터셋을 지정한 비율 또는 개수에 따라 나누어 줌
import splitfoders
splitfolders.ratio(input = '분리할 전체 데이터셋이 저장된 위치',
output = '분리한 각 데이터셋이 저장될 위치',
seed = 시드 값,
ratio = (train 비율, val 비율, (test 비율 - 생략 가능)))
방법 2. shutil 모듈
shutil 모듈
- 파일 및 디렉토리 복사, 이동, 삭제 등의 작업을 수행 가능
shutil.copy(src, dst) : 파일 복사
shutil.copy2(src, dst) : 파일을 복사하면서 파일 권한 및 메타데이터도 복사
shutil.copytree(src, dst) : 디렉토리 복사
shutil.rmtree(path) : 디렉토리 삭제
shutil.move(src, dst) : 파일이나 디렉토리 이동
- shutil 모듈을 활용해 데이터를 분할하는 코드 구현
file_n_list = os.listdir(tr_n_path)
random.shuffle(file_n_list)
file_ab_list = os.listdir(tr_ab_path)
random.shuffle(file_ab_list)
def split_files(file_list, src_path, te_data_num, val_data_num, test_dst_path, valid_dst_path, category):
for i, file_name in enumerate(file_list):
src_file_path = os.path.join(src_path, file_name)
dst_path = ''
if i < te_data_num:
dst_path = os.path.join(test_dst_path, category)
elif i < te_data_num + val_data_num:
dst_path = os.path.join(valid_dst_path, category)
else:
break
if not os.path.exists(dst_path):
os.mkdir(dst_path)
shutil.move(src_file_path, dst_path)
split_files(file_n_list, tr_n_path,
te_data_num[0], val_data_num[0],
test_path, valid_path, 'normal')
split_files(file_ab_list, tr_ab_path,
te_data_num[1], val_data_num[1],
test_path, valid_path, 'abnormal')
데이터 복사 및 이동
- 폴더 내 파일 전체를 옮기면 되므로 'shutil.copytree()' 사용
- 이미 존재하는 디렉토리가 dst일 경우, 'dirs_exist_ok = True'를 넣어줘야 함
shutil.copytree(os.path.join(train_path, 'abnormal'),
'/content/drive/MyDrive/Datasets/copy_images/trainset')
shutil.copytree(os.path.join(train_path, 'normal'),
'/content/drive/MyDrive/Datasets/copy_images/trainset', dirs_exist_ok = True)
os 모듈
os.getcwd() : 현재 작업 디렉토리를 반환
os.chdir(path) : 현재 작업 디렉토리를 변경
os.listdir(path) : 지정된 디렉토리에 있는 파일 및 디렉토리의 목록을 반환
os.remove(path) : 파일을 삭제
os.mkdir(path) : 디렉토리를 생성
os.rmdir(path) : 디렉토리를 삭제
os.path.join(path1, path2, ...) : 경로 구성 요소를 연결하여 새 경로를 생성
os.rename(src, dst): 파일이나 디렉토리의 이름을 변경
어려웠던 부분
- os, shutil, splitfolders 모듈 모두 경험이 없어 사용법을 찾아보며 하다보니 시간이 많이 걸림
- 디렉토리가 없는 경우, 자동으로 생성되는 경우와 그렇지 않은 경우가 나누어져 있어 헷갈리는 부분이 있었음
- shutil.copytree(src, dst): dst의 디렉토리가 없는 경우, 자동 생성(이미 있는 경우 오류 발생할 수 있음)
- shutil.move(src, dst): dst의 디렉토리가 없는 경우, 에러 발생 -> 미리 생성해주어야 함
마무리
- 전처리 과정은 어렵지 않게 구현할 수 있었음
- 시간이 남아 모델링까지 시도해 본 결과, 성능이 0.70 근처에서 진전이 없었음
- 데이터가 적기도 하고, 파손 상태가 사진으로 판별이 쉽지 않을 수 있음
- ImageDataGenerator로 데이터를 증강하고, 파손 상태를 여러 관점에서 확인할 수 있도록 이미지 처리 적용할 예정