특정한 파일들을 각 파일이 가진 특성에 따라서, 0 또는 1이라는 폴더로 파일들을 나누어 저장했다고 가정합시다.
이제 이 파일들을 1 : 1: 8 비율로 나누어 분류할 겁니다.
예컨대 100개의 파일을 가지고 처음 구분을 해뒀다면,
이것을 Train, Val, Test 라는 3개의 용도로 분류된 폴더 안에 다시 0과 1의 폴더를 만들고,
처음 100개의 파일을 각 폴더에, 10개 10개 80개씩 분류하다는 뜻입니다.
아래 코드가 위에서 가정한 로직의 구현을 위한 코드 예시입니다.
import os
import shutil
from sklearn.model_selection import train_test_split
# 기존 폴더 경로
source_folder_0 = r"path_to_the_folder_containing_0"
source_folder_1 = r"path_to_the_folder_containing_1"
# 새로운 폴더 경로
destination_folder = r"path_to_the_new_folder_structure"
# Val, Test, Train 폴더 내의 0과 1 폴더를 생성합니다.
subfolders = ['Val', 'Test', 'Train']
labels = ['0', '1']
for subfolder in subfolders:
for label in labels:
new_folder_path = os.path.join(destination_folder, subfolder, label)
os.makedirs(new_folder_path, exist_ok=True)
# 파일을 무작위로 섞고, 1:1:8 비율로 나누어 각각 Val, Test, Train 폴더에 배정합니다.
def distribute_files(source_folder, label):
files = os.listdir(source_folder)
train_files, test_files = train_test_split(files, test_size=0.2, random_state=42)
val_files, test_files = train_test_split(test_files, test_size=0.5, random_state=42)
for file in val_files:
shutil.move(os.path.join(source_folder, file),
os.path.join(destination_folder, 'Val', label, file))
for file in test_files:
shutil.move(os.path.join(source_folder, file),
os.path.join(destination_folder, 'Test', label, file))
for file in train_files:
shutil.move(os.path.join(source_folder, file),
os.path.join(destination_folder, 'Train', label, file))
# 각 레이블에 대해 파일 분배 함수 호출
distribute_files(source_folder_0, '0')
distribute_files(source_folder_1, '1')
기존 폴더 경로로 각각 처음 100개의 파일을 0과 1로 분류해둔 폴더를 각각 지정해줍니다.
그 이후, Train Val Test 라는 폴더를 생성할 경로를 새로운 폴더 경로로 지정을 해줍시다.
먼저 subfolders 내부에 있는 이름으로 해당 경로에 폴더가 쭈르를 생길 것이고,
그 안에 label 이라는 폴더가 자동으로 같이 생성이 될 수 있도록 16번 줄 코드가 작동이 됩니다.
이후 22번 줄의 함수는 각 폴더 속에 있는 파일들을 섞어서 1: 1: 8 로 분배를 완료하는 역할을 합니다.
결과적으로 40, 41번 줄과 같이 함수를 사용하면 해당 특정 폴더에 있는 모든 파일을,
우리가 설정한 subfolders 들의 내부에 있는 각 0이라는 폴더에 1: 1: 8 로 파일을 랜덤하게 배정합니다.
이렇게 Trian 으로 분류한 파일들을 활용해서 모델을 똑똑하게 하고,
이 똑똑한 모델이 잘 학습하고 있는지 중간중간 확인하는 차원에서 Val 폴더 내의 데이터를 활용합니다.
이후, Test 내에 있는 파일들을 가지고 완성된 모델이 실제 환경에서도 통할지 실제 확인을 하기 위해 사용합니다.